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,2152 @@
1
+ """The memory-lifecycle handlers (A5, ADR 0028): `remember`, `confirm` (and `observe`), `refute`, `forget`, `triage`, `supersede`, `merge`, `distinct`, `restore`, `promote`, `memories`, `rules`, `memory` (edit) and `settle`, with the logic only they use."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import datetime
7
+ import json
8
+ import logging
9
+ import os
10
+ import re
11
+ import shutil
12
+ import sys
13
+ import textwrap
14
+ import time
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import TYPE_CHECKING, Any
18
+
19
+ import yaml
20
+
21
+ from memory_cli.commands import common
22
+ from memory_cli.core import safe_io
23
+ from memory_cli.corroborate import decide as corroborate_decide
24
+ from memory_cli.memories import model, records, rules
25
+ from memory_cli.notes import index as index_files
26
+ from memory_cli.notes import links as link_rules
27
+ from memory_cli.notes import note as note_files
28
+ from memory_cli.settle import state as settle_state
29
+ from memory_cli.settle import verdicts as settle_verdicts
30
+ from memory_cli.syntheses import document
31
+ from memory_cli.syntheses import edit as synthesis_edit
32
+
33
+ if TYPE_CHECKING:
34
+ import argparse
35
+ from collections.abc import Callable, Sequence
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+
40
+ _CLAIM_PREVIEW_CHARS = 160 # a claim longer than this is cut in a listing
41
+
42
+
43
+ def _register_project(project: Path | None) -> None:
44
+ """Record the project in the local registry; never fails or prints, the command it follows has succeeded."""
45
+ if project is None:
46
+ return
47
+ try:
48
+ records.register_project(common.data_dir(os.environ), project, datetime.date.today())
49
+ except Exception:
50
+ logger.debug("registering the project failed", exc_info=True)
51
+
52
+
53
+ def _same_claim(a: str, b: str) -> bool:
54
+ """Exact duplicate by word sequence in any script; claims with no word characters compare as stripped text."""
55
+ wa, wb = re.findall(r"\w+", a.casefold()), re.findall(r"\w+", b.casefold())
56
+ return wa == wb if wa or wb else a.strip() == b.strip()
57
+
58
+
59
+ def _approval(args: argparse.Namespace) -> dict[str, bool]:
60
+ return {"owner_approved": True} if getattr(args, "owner_approved", False) else {}
61
+
62
+
63
+ def _add_sightings(
64
+ same: Sequence[records.Memory],
65
+ args: argparse.Namespace,
66
+ today: datetime.date,
67
+ folder: Path,
68
+ project: Path | None,
69
+ ) -> bool:
70
+ """An identical claim from another session: when both the existing record and this call come from a transcript,
71
+ the session goes onto the existing record. True when the call was handled (the caller still exits 3)."""
72
+ keys = [records.sighting_entry(*f) for f in map(records.sighting, args.source) if f]
73
+ target = next((m for m in same if m.origin == "transcript"), None)
74
+ if target is None or getattr(args, "origin", None) != "transcript" or not keys:
75
+ return False
76
+ added = cased = False
77
+ for key in keys:
78
+ if records.counted(target, key):
79
+ print(f"mem: {key} is already counted for m:{target.handle}.", file=sys.stderr)
80
+ explicit = getattr(args, "outcome", None)
81
+ sid = records.session_key(key)
82
+ if explicit and sid and not records.has_case(target, sid, explicit):
83
+ records.log_before(target, "confirm")
84
+ target, _ = records.add_case(
85
+ target, key, getattr(args, "seen_on", None) or today, explicit, today
86
+ )
87
+ cased = True
88
+ print(f"mem: case {explicit} added to m:{target.handle}.", file=sys.stderr)
89
+ continue
90
+ records.log_before(target, "confirm")
91
+ target, _ = records.add_sighting(
92
+ target,
93
+ key,
94
+ today,
95
+ outcome=getattr(args, "outcome", None) or "seen",
96
+ on=getattr(args, "seen_on", None),
97
+ )
98
+ added = True
99
+ print(f"mem: {key} added to m:{target.handle}.", file=sys.stderr)
100
+ print(f"m:{target.handle}\t{'sighting' if added else 'case' if cased else 'already counted'}")
101
+ return True
102
+
103
+
104
+ def _check_short_topic(args: argparse.Namespace) -> int | None:
105
+ """Collapse the whitespace of `args.short`, then 2 after a message when it or `args.topic` is not valid
106
+ (empty is allowed: it means none), else None."""
107
+ if args.short and len(args.short.splitlines()) > 1:
108
+ print("mem: the short form must be one line: it has a line break.", file=sys.stderr)
109
+ return 2
110
+ if args.short is not None:
111
+ args.short = " ".join(args.short.split())
112
+ if args.short and not records.valid_short(args.short):
113
+ print(
114
+ f"mem: the short form must be one line of at most {records.SHORT_LIMIT} characters.",
115
+ file=sys.stderr,
116
+ )
117
+ return 2
118
+ if args.topic and not records.valid_topic(args.topic):
119
+ print(
120
+ f"mem: the topic must be one or two lowercase words, at most {records.TOPIC_LIMIT} characters, "
121
+ f'not "other".',
122
+ file=sys.stderr,
123
+ )
124
+ return 2
125
+ return None
126
+
127
+
128
+ def _check_short_claim(args: argparse.Namespace, claim: str) -> int | None:
129
+ """2 after a message when `--user-read` has no `--short`, or a short form the owner did not read is stronger
130
+ than the claim it will sit on; else None."""
131
+ user_read = getattr(args, "user_read", False)
132
+ if user_read and args.short is None:
133
+ print(
134
+ "mem: --user-read goes with --short: it says the owner read that text.", file=sys.stderr
135
+ )
136
+ return 2
137
+ if args.short and not user_read and (reasons := model.short_problems(claim, args.short)):
138
+ print(
139
+ "mem: the short form is refused: "
140
+ + "; ".join(reasons)
141
+ + ". Reword it, or pass --user-read if the "
142
+ "owner read this text.",
143
+ file=sys.stderr,
144
+ )
145
+ return 2
146
+ return None
147
+
148
+
149
+ class _RememberRefusalError(Exception):
150
+ """`mem remember` refused the call, after a message on stderr; `code` is its exit code."""
151
+
152
+ def __init__(self, code: int) -> None:
153
+ super().__init__(code)
154
+ self.code = code
155
+
156
+
157
+ @dataclasses.dataclass(frozen=True)
158
+ class _RememberTarget:
159
+ """Where a memory is written: its scope, the folder, and the project root for a project memory."""
160
+
161
+ scope: str
162
+ folder: Path
163
+ project: Path | None
164
+
165
+
166
+ def _refuse(code: int | None) -> None:
167
+ """Stop `mem remember` with `code` when a check returned one."""
168
+ if code:
169
+ raise _RememberRefusalError(code)
170
+
171
+
172
+ def _remember_check_args(args: argparse.Namespace) -> None:
173
+ args.claim = " ".join(args.claim.split())
174
+ if args.context is not None:
175
+ args.context = " ".join(args.context.split()) or None
176
+ if not args.claim:
177
+ print("mem: the claim is empty.", file=sys.stderr)
178
+ raise _RememberRefusalError(2)
179
+ if args.kind not in records.KINDS:
180
+ print(f"mem: unknown kind {args.kind!r}.", file=sys.stderr)
181
+ raise _RememberRefusalError(2)
182
+ _refuse(_check_short_topic(args))
183
+ _refuse(_check_short_claim(args, args.claim))
184
+
185
+
186
+ def _remember_global_target(store: Path | None) -> _RememberTarget:
187
+ folder = records.memories_root(os.environ, store)
188
+ if folder is None:
189
+ print(
190
+ 'mem: no folder for global memories: set the plugin\'s "memories" option, '
191
+ 'or MEM_MEMORIES, or use a store made with "mem init".',
192
+ file=sys.stderr,
193
+ )
194
+ raise _RememberRefusalError(2)
195
+ if common._read_only_store(store, folder.resolve()):
196
+ print(common._READ_ONLY_MEMORIES, file=sys.stderr)
197
+ raise _RememberRefusalError(2)
198
+ return _RememberTarget("global", folder, None)
199
+
200
+
201
+ def _remember_project_target(store: Path | None) -> _RememberTarget:
202
+ project = records.project_root(Path.cwd(), os.environ)
203
+ if project is None:
204
+ print(
205
+ "mem: not inside a git repository: pass --global, or set MEM_PROJECT to the project folder.",
206
+ file=sys.stderr,
207
+ )
208
+ raise _RememberRefusalError(2)
209
+ folder = records.project_dir(project)
210
+ if common._read_only_store(store, project) or common._read_only_store(store, folder.resolve()):
211
+ print(common._READ_ONLY_PROJECT, file=sys.stderr)
212
+ raise _RememberRefusalError(2)
213
+ return _RememberTarget("project", folder, project)
214
+
215
+
216
+ def _remember_target(args: argparse.Namespace, store: Path | None) -> _RememberTarget:
217
+ return _remember_global_target(store) if args.is_global else _remember_project_target(store)
218
+
219
+
220
+ def _remember_check_options(args: argparse.Namespace, today: datetime.date) -> None:
221
+ if not args.source and (getattr(args, "outcome", None) or getattr(args, "seen_on", None)):
222
+ print("mem: --outcome and --seen-on need --source.", file=sys.stderr)
223
+ raise _RememberRefusalError(2)
224
+ if getattr(args, "seen_on", None) is not None and args.seen_on > today:
225
+ print("mem: --seen-on cannot be later than today.", file=sys.stderr)
226
+ raise _RememberRefusalError(2)
227
+ if args.kind in {"finding", "document"} and not args.source:
228
+ print(f"mem: a {args.kind} needs at least one --source.", file=sys.stderr)
229
+ raise _RememberRefusalError(2)
230
+
231
+
232
+ def _remember_body(args: argparse.Namespace) -> str:
233
+ try:
234
+ return common._memory_body(args.body_file)
235
+ except (OSError, UnicodeDecodeError) as exc:
236
+ print(f"mem: cannot read the body: {exc}", file=sys.stderr)
237
+ raise _RememberRefusalError(2) from exc
238
+
239
+
240
+ def _remember_check_text(args: argparse.Namespace, body: str) -> None:
241
+ """Refuse a text that looks like a secret (4), and for the global scope one with a forbidden term."""
242
+ if common._refuse_secret([
243
+ args.claim,
244
+ args.context or "",
245
+ body,
246
+ *args.source,
247
+ args.short or "",
248
+ ]):
249
+ raise _RememberRefusalError(4)
250
+ if args.is_global:
251
+ _refuse(
252
+ common._check_terms(
253
+ [
254
+ args.claim,
255
+ args.context or "",
256
+ body,
257
+ *args.source,
258
+ records.slug_of(args.claim),
259
+ args.short or "",
260
+ ],
261
+ args.kind,
262
+ args.owner_approved,
263
+ )
264
+ )
265
+
266
+
267
+ def _remember_check_sessions(args: argparse.Namespace) -> None:
268
+ """A source of a transcript record that starts like a session entry must be one."""
269
+ if getattr(args, "origin", None) != "transcript":
270
+ return
271
+ for source in args.source:
272
+ if (
273
+ " ".join(source.split()).lower().startswith(records.SESSION_PREFIX)
274
+ and records.sighting(source) is None
275
+ ):
276
+ print(
277
+ f"mem: --source {source!r} is not a session entry: write 'session <id>' or "
278
+ f"'session <id> project <{records.PROJECT_KEY_LEN} hex characters>'.",
279
+ file=sys.stderr,
280
+ )
281
+ raise _RememberRefusalError(2)
282
+
283
+
284
+ def _remember_check_valid_until(
285
+ args: argparse.Namespace, target: _RememberTarget, today: datetime.date
286
+ ) -> None:
287
+ if getattr(args, "origin", None) != "transcript" or args.valid_until is None:
288
+ return
289
+ draft = records.Memory(
290
+ target.scope,
291
+ target.folder,
292
+ "",
293
+ args.kind,
294
+ args.claim,
295
+ today,
296
+ 1,
297
+ "active",
298
+ None,
299
+ None,
300
+ records.normalized_sources(args.source),
301
+ "",
302
+ None,
303
+ origin="transcript",
304
+ weight=getattr(args, "weight", None),
305
+ )
306
+ if records.standing(draft) != "established":
307
+ print(
308
+ f"mem: --valid-until is refused: the life of a record from a transcript is "
309
+ f"{records.UNCONFIRMED_DAYS} days from the last session that showed it.",
310
+ file=sys.stderr,
311
+ )
312
+ raise _RememberRefusalError(2)
313
+
314
+
315
+ def _remember_same_claim(
316
+ args: argparse.Namespace, existing: list[records.Memory], live: list[records.Memory]
317
+ ) -> list[records.Memory]:
318
+ """The live memories with the claim, and, for a call from a session, the lapsed ones from a transcript."""
319
+ from_session = getattr(args, "origin", None) == "transcript" and any(
320
+ map(records.session_key, args.source)
321
+ )
322
+ lapsed = [
323
+ m
324
+ for m in existing
325
+ if from_session
326
+ and m.error is None
327
+ and m.status == "active"
328
+ and m.origin == "transcript"
329
+ and m not in live
330
+ ]
331
+ return [m for m in live + lapsed if _same_claim(m.claim, args.claim)]
332
+
333
+
334
+ def _remember_check_duplicates(
335
+ args: argparse.Namespace,
336
+ target: _RememberTarget,
337
+ today: datetime.date,
338
+ existing: list[records.Memory],
339
+ live: list[records.Memory],
340
+ ) -> None:
341
+ """Exit 3 when the claim exists, unless `--force`."""
342
+ if args.force:
343
+ return
344
+ same = _remember_same_claim(args, existing, live)
345
+ if not same:
346
+ return
347
+ if _add_sightings(same, args, today, target.folder, target.project):
348
+ raise _RememberRefusalError(3)
349
+ for m in same:
350
+ print(f"m:{m.handle}\t{m.claim}", file=sys.stderr)
351
+ print(
352
+ f'mem: a memory with the same claim exists; run "mem observe m:{same[0].handle}" if it is the same, '
353
+ "or repeat with --force to write a new one.",
354
+ file=sys.stderr,
355
+ )
356
+ raise _RememberRefusalError(3)
357
+
358
+
359
+ def _remember_exclude_failed(project: Path | None) -> bool:
360
+ """Keep `.memory/` out of git status for a project; True when that failed."""
361
+ if project is None:
362
+ return False
363
+ try:
364
+ records.ensure_excluded(project)
365
+ except OSError:
366
+ return True
367
+ return False
368
+
369
+
370
+ def _remember_write(
371
+ args: argparse.Namespace, target: _RememberTarget, body: str, today: datetime.date
372
+ ) -> records.Memory:
373
+ try:
374
+ return records.write_memory(
375
+ target.folder,
376
+ target.scope,
377
+ kind=args.kind,
378
+ claim=args.claim,
379
+ body=body,
380
+ today=today,
381
+ context=args.context,
382
+ valid_until=args.valid_until,
383
+ sources=args.source,
384
+ origin=getattr(args, "origin", None),
385
+ reach=getattr(args, "reach", None),
386
+ weight=getattr(args, "weight", None),
387
+ short=args.short or None,
388
+ topic=args.topic or None,
389
+ short_by="model" if args.short and not getattr(args, "user_read", False) else None,
390
+ outcome=getattr(args, "outcome", None),
391
+ on=getattr(args, "seen_on", None),
392
+ )
393
+ except (ValueError, OSError) as exc:
394
+ print(f"mem: {exc}", file=sys.stderr)
395
+ raise _RememberRefusalError(2) from exc
396
+
397
+
398
+ def _remember_report(
399
+ m: records.Memory,
400
+ target: _RememberTarget,
401
+ exclude_failed: bool,
402
+ related: Sequence[records.Memory],
403
+ ) -> None:
404
+ """The handle and path on stdout; the warning and the related memories on stderr."""
405
+ _register_project(target.project)
406
+ rel = m.path.relative_to(target.project if target.project is not None else target.folder)
407
+ print(f"m:{m.handle}\t{rel.as_posix()}")
408
+ if exclude_failed:
409
+ print(
410
+ "mem: could not add .memory/ to .git/info/exclude; the folder may appear in git status.",
411
+ file=sys.stderr,
412
+ )
413
+ if related:
414
+ print(
415
+ 'related memories (if one is the same, run "mem observe m:<handle>"; if one says the opposite, keep both):',
416
+ file=sys.stderr,
417
+ )
418
+ for r in related:
419
+ print(
420
+ f"m:{r.handle}\t[{r.kind}, observed {r.observed}, {r.created.isoformat() if r.created else '?'}]\t{r.claim}",
421
+ file=sys.stderr,
422
+ )
423
+
424
+
425
+ def _remember_log(
426
+ args: argparse.Namespace,
427
+ store: Path | None,
428
+ target: _RememberTarget,
429
+ m: records.Memory,
430
+ today: datetime.date,
431
+ ) -> None:
432
+ common.log_usage(store, {"cmd": "remember", "scope": target.scope, **_approval(args)})
433
+ if (
434
+ target.scope == "global"
435
+ and getattr(args, "origin", None) != "pipeline"
436
+ and not records.quarantined(m)
437
+ ):
438
+ settle_state.maybe_start(target.folder, store, os.environ, time.time(), today)
439
+
440
+
441
+ def _remember(args: argparse.Namespace) -> None:
442
+ """The steps of `mem remember`; a refusal raises `_RememberRefusalError`."""
443
+ today = datetime.date.today()
444
+ store = common._optional_store(args)
445
+ _remember_check_args(args)
446
+ target = _remember_target(args, store)
447
+ _remember_check_options(args, today)
448
+ body = _remember_body(args)
449
+ _remember_check_text(args, body)
450
+ _remember_check_sessions(args)
451
+ _remember_check_valid_until(args, target, today)
452
+ existing = records.load_memories(target.folder, target.scope)
453
+ live = [m for m in existing if records.is_live(m, today)]
454
+ _remember_check_duplicates(args, target, today, existing, live)
455
+ related = records.match_memories(
456
+ common._readable(live, today),
457
+ records.tokenize(args.claim),
458
+ today,
459
+ tokenize=records.tokenize,
460
+ )
461
+ exclude_failed = _remember_exclude_failed(target.project)
462
+ m = _remember_write(args, target, body, today)
463
+ _remember_report(m, target, exclude_failed, related)
464
+ _remember_log(args, store, target, m, today)
465
+
466
+
467
+ def cmd_remember(args: argparse.Namespace) -> int:
468
+ try:
469
+ _remember(args)
470
+ except _RememberRefusalError as refusal:
471
+ return refusal.code
472
+ return 0
473
+
474
+
475
+ def _memory_scopes(args: argparse.Namespace) -> dict[str, dict[str, records.Memory]]:
476
+ """The memories of each scope by handle."""
477
+ project = records.project_root(Path.cwd(), os.environ)
478
+ folders = {
479
+ "project": records.project_dir(project) if project else None,
480
+ "global": records.memories_root(os.environ, common._optional_store(args)),
481
+ }
482
+ return {
483
+ scope: {m.handle: m for m in records.load_memories(folder, scope)}
484
+ for scope, folder in folders.items()
485
+ }
486
+
487
+
488
+ def _memory_missing(
489
+ loaded: dict[str, dict[str, records.Memory]], order: Sequence[str], handles: Sequence[str]
490
+ ) -> str | None:
491
+ """The first handle that no scope in `order` holds."""
492
+ for handle in handles:
493
+ if not any(handle.removeprefix("m:") in loaded[scope] for scope in order):
494
+ return handle
495
+ return None
496
+
497
+
498
+ def _memory_pick(
499
+ loaded: dict[str, dict[str, records.Memory]], order: Sequence[str], handles: Sequence[str]
500
+ ) -> list[records.Memory] | None:
501
+ """The memories of the first scope in `order` that holds all `handles`; None after a message on stderr."""
502
+ missing = _memory_missing(loaded, order, handles)
503
+ if missing is not None:
504
+ print(f"mem: no memory named {missing}", file=sys.stderr)
505
+ return None
506
+ names = [h.removeprefix("m:") for h in handles]
507
+ scope = next((s for s in order if all(name in loaded[s] for name in names)), None)
508
+ if scope is None:
509
+ print(
510
+ f"mem: {' and '.join('m:' + n for n in names)} are in different scopes: both must be in the same one.",
511
+ file=sys.stderr,
512
+ )
513
+ return None
514
+ return [loaded[scope][name] for name in names]
515
+
516
+
517
+ def _memory_refused(found: Sequence[records.Memory], store: Path | None) -> bool:
518
+ """Whether a memory cannot be changed (an unreadable record, or a read-only store), after a message on stderr."""
519
+ for m in found:
520
+ if m.error is not None:
521
+ print(f"mem: {m.path}: {m.error}", file=sys.stderr)
522
+ return True
523
+ if common._read_only_store(store, m.path.resolve()):
524
+ print(
525
+ common._READ_ONLY_PROJECT if m.scope == "project" else common._READ_ONLY_MEMORIES,
526
+ file=sys.stderr,
527
+ )
528
+ return True
529
+ return False
530
+
531
+
532
+ def _memory_of(args: argparse.Namespace, handles: Sequence[str]) -> list[records.Memory] | None:
533
+ """The named memories, all in one scope: the project's unless --global; None after a message on stderr.
534
+
535
+ A handle found in both scopes means the project one, as for any lookup; with several handles the scope is
536
+ one that holds all of them, and handles that exist only in different scopes are refused."""
537
+ loaded = _memory_scopes(args)
538
+ order = ("global",) if args.is_global else ("project", "global")
539
+ found = _memory_pick(loaded, order, handles)
540
+ if found is None or _memory_refused(found, common._optional_store(args)):
541
+ return None
542
+ return found
543
+
544
+
545
+ def _with_note(body: str, heading: str, text: str) -> str:
546
+ """The body with a heading line and the text under it added at the end."""
547
+ head = body.rstrip("\n")
548
+ return (
549
+ f"{head}\n\n{heading}\n{text.strip()}\n" if head.strip() else f"{heading}\n{text.strip()}\n"
550
+ )
551
+
552
+
553
+ def _reason_allowed(memory: records.Memory, because: str | None, approved: bool) -> int:
554
+ """0 when the reason may be written: it goes through the secret patterns; one written into a global memory also
555
+ through the term list, failing closed. Else the exit code, after a message."""
556
+ if not because:
557
+ return 0
558
+ if common._refuse_secret([because]):
559
+ return 4
560
+ if memory.scope != "global":
561
+ return 0
562
+ return common._check_terms([because], memory.kind, approved)
563
+
564
+
565
+ def _act(
566
+ args: argparse.Namespace,
567
+ handles: Sequence[str],
568
+ apply: Callable[[list[records.Memory], datetime.date], list[str]],
569
+ name: str,
570
+ because: str | None = None,
571
+ ) -> int:
572
+ found = _memory_of(args, handles)
573
+ if found is None:
574
+ return 2
575
+ refused = _reason_allowed(found[0], because, getattr(args, "owner_approved", False))
576
+ if refused:
577
+ return refused
578
+ try:
579
+ lines = apply(found, datetime.date.today())
580
+ except (OSError, ValueError, yaml.YAMLError) as exc:
581
+ print(f"mem: {exc}", file=sys.stderr)
582
+ return 2
583
+ if found[0].scope == "project":
584
+ _register_project(records.project_root(Path.cwd(), os.environ))
585
+ print("\n".join(lines))
586
+ common.log_usage(
587
+ common._optional_store(args), {"cmd": name, "scope": found[0].scope, **_approval(args)}
588
+ )
589
+ return 0
590
+
591
+
592
+ def _add_plain_source(
593
+ memory: records.Memory, source: str, today: datetime.date, note: str | None
594
+ ) -> records.Memory:
595
+ """A source (URL, path or session) appended once to a memory that is not from a transcript, with the note."""
596
+ changes: dict = {}
597
+ if source not in memory.sources:
598
+ changes["sources"] = [*memory.sources, source]
599
+ if note and note.strip():
600
+ head = memory.body if memory.body.endswith("\n") or not memory.body else memory.body + "\n"
601
+ changes["body"] = f"{head}{' '.join(note.split())}\n"
602
+ return records.update(memory, today, **changes) if changes else memory
603
+
604
+
605
+ @dataclasses.dataclass(frozen=True)
606
+ class _ConfirmOptions:
607
+ """The validated flags of `mem confirm`; `outcome` is None when none was given."""
608
+
609
+ until: datetime.date | None
610
+ source: str | None
611
+ note: str | None
612
+ outcome: str | None
613
+ seen_on: datetime.date | None
614
+
615
+
616
+ def _confirm_options(args: argparse.Namespace, today: datetime.date) -> _ConfirmOptions:
617
+ until = getattr(args, "until", None)
618
+ if until is not None:
619
+ try:
620
+ until = datetime.date.fromisoformat(until)
621
+ except ValueError:
622
+ raise ValueError(f"--until needs a date as YYYY-MM-DD, not {until!r}") from None
623
+ source = getattr(args, "source", None)
624
+ if source is None and getattr(args, "note", None):
625
+ raise ValueError("--note needs --source")
626
+ if source is None and (getattr(args, "outcome", None) or getattr(args, "seen_on", None)):
627
+ raise ValueError("--outcome and --seen-on need --source")
628
+ if getattr(args, "seen_on", None) is not None and args.seen_on > today:
629
+ raise ValueError("--seen-on cannot be later than today")
630
+ return _ConfirmOptions(
631
+ until,
632
+ source,
633
+ getattr(args, "note", None),
634
+ getattr(args, "outcome", None),
635
+ getattr(args, "seen_on", None),
636
+ )
637
+
638
+
639
+ def _confirm_by_owner(
640
+ options: _ConfirmOptions, m: records.Memory, today: datetime.date
641
+ ) -> tuple[list[str], bool]:
642
+ """The owner confirms a lesson captured from a transcript; True in the second place when it already was."""
643
+ if options.source is not None or options.until is not None:
644
+ raise ValueError("--by-owner stands alone: it takes no --source or --until")
645
+ if m.origin != "transcript":
646
+ raise ValueError(
647
+ f"m:{m.handle} is not from a transcript: the owner's confirmation applies to a "
648
+ "lesson captured from one"
649
+ )
650
+ if m.status != "active":
651
+ raise ValueError(f"m:{m.handle} is {m.status}: the owner confirms only an active memory")
652
+ if m.owner_confirmed:
653
+ return [f"m:{m.handle}\talready confirmed by the owner: nothing changed"], True
654
+ records.log_before(m, "confirm")
655
+ after = dataclasses.replace(m, owner_confirmed=today)
656
+ records.update(m, today, owner_confirmed=today, **records.standing_changes(m, after, today))
657
+ return [f"m:{m.handle}\tconfirmed by the owner"], False
658
+
659
+
660
+ def _confirm_check_source(options: _ConfirmOptions, m: records.Memory) -> None:
661
+ source = options.source
662
+ if source is not None and not source.strip():
663
+ raise ValueError("--source is empty")
664
+ if source is not None and m.origin == "transcript" and records.session_key(source) is None:
665
+ raise ValueError(f"--source takes a session ('session <id>'), not {source!r}")
666
+ if options.until is not None and records.standing(m) == "unconfirmed":
667
+ raise ValueError(
668
+ "a record from a transcript is confirmed only by another session showing it: "
669
+ "use --source 'session <id>', not --until"
670
+ )
671
+ if source is not None and m.status != "active":
672
+ raise ValueError(f"m:{m.handle} is {m.status}: a source is added only to an active memory")
673
+
674
+
675
+ def _confirm_is_counted(options: _ConfirmOptions, m: records.Memory) -> bool:
676
+ """Whether the source is already one of the memory's sources (a session already counted)."""
677
+ source = options.source
678
+ if source is None:
679
+ return False
680
+ if m.origin == "transcript":
681
+ return records.counted(m, source)
682
+ seen = {records.session_key(s) or s.strip() for s in m.sources}
683
+ return (records.session_key(source) or source.strip()) in seen
684
+
685
+
686
+ def _confirm_add_case(
687
+ options: _ConfirmOptions, source: str, found: list[records.Memory], today: datetime.date
688
+ ) -> list[str]:
689
+ """A counted session gets a case only on request: `--outcome` that the memory does not have yet."""
690
+ outcome = options.outcome or "seen"
691
+ records.log_before(found[0], "confirm")
692
+ found[0], _ = records.add_case(found[0], source, options.seen_on or today, outcome, today)
693
+ if options.until is None:
694
+ return [f"m:{found[0].handle}\tcase {outcome} added"]
695
+ records.update(found[0], today, valid_until=options.until)
696
+ return [f"m:{found[0].handle}\tcase {outcome} added; valid until {options.until.isoformat()}"]
697
+
698
+
699
+ def _confirm_counted(
700
+ options: _ConfirmOptions, found: list[records.Memory], today: datetime.date
701
+ ) -> tuple[list[str], bool]:
702
+ """The source is already counted: a case when asked for, else nothing but `--until`; True in the second place
703
+ when the call changed nothing."""
704
+ source = options.source
705
+ m = found[0]
706
+ key = records.session_key(source) if source is not None else None
707
+ if (
708
+ m.origin == "transcript"
709
+ and key
710
+ and source is not None # a session key comes only from a source
711
+ and options.outcome
712
+ and not records.has_case(m, key, options.outcome)
713
+ ):
714
+ return _confirm_add_case(options, source, found, today), False
715
+ if options.until is None:
716
+ return [f"m:{m.handle}\t{source} is already a source: nothing changed"], True
717
+ records.log_before(m, "confirm") # the source is not counted again; the date is still set
718
+ records.update(m, today, valid_until=options.until)
719
+ return [
720
+ f"m:{m.handle}\t{source} is already a source; valid until {options.until.isoformat()}"
721
+ ], True
722
+
723
+
724
+ def _confirm_observe(
725
+ options: _ConfirmOptions, m: records.Memory, today: datetime.date
726
+ ) -> list[str]:
727
+ """Count one more observation, with the source and the note when given, and `--until`."""
728
+ source = options.source
729
+ records.log_before(m, "confirm")
730
+ if source is not None and m.origin == "transcript":
731
+ updated, _ = records.add_sighting(
732
+ m, source, today, options.note, outcome=options.outcome or "seen", on=options.seen_on
733
+ )
734
+ else:
735
+ updated = records.observe(m, today)
736
+ if source is not None:
737
+ updated = _add_plain_source(updated, source.strip(), today, options.note)
738
+ if options.until is not None:
739
+ updated = records.update(updated, today, valid_until=options.until)
740
+ return [f"m:{updated.handle}\tobserved {updated.observed}"]
741
+
742
+
743
+ def _confirm_apply(
744
+ args: argparse.Namespace, found: list[records.Memory], today: datetime.date
745
+ ) -> tuple[list[str], bool]:
746
+ """The lines to print, and whether the call repeated what the memory already had."""
747
+ options = _confirm_options(args, today)
748
+ if getattr(args, "by_owner", False):
749
+ return _confirm_by_owner(options, found[0], today)
750
+ _confirm_check_source(options, found[0])
751
+ if _confirm_is_counted(options, found[0]):
752
+ return _confirm_counted(options, found, today)
753
+ return _confirm_observe(options, found[0], today), False
754
+
755
+
756
+ def cmd_confirm(args: argparse.Namespace) -> int:
757
+ repeated: list[bool] = []
758
+
759
+ def apply(found, today):
760
+ lines, again = _confirm_apply(args, found, today)
761
+ if again:
762
+ repeated.append(True)
763
+ return lines
764
+
765
+ code = _act(args, [args.handle], apply, args.command, because=getattr(args, "note", None))
766
+ return 3 if code == 0 and repeated else code
767
+
768
+
769
+ def _text_change(
770
+ found: list[records.Memory],
771
+ key: str,
772
+ heading: str,
773
+ because: str | None,
774
+ today: datetime.date,
775
+ **extra,
776
+ ) -> records.Memory:
777
+ m = found[0]
778
+ records.log_before(m, {"refuted": "refute", "forgotten": "forget"}[key])
779
+ changes = {"status": key, key: today, **extra}
780
+ if because and because.strip():
781
+ changes["body"] = _with_note(m.body, f"{heading} {today.isoformat()}:", because)
782
+ return records.update(m, today, **changes)
783
+
784
+
785
+ def cmd_refute(args: argparse.Namespace) -> int:
786
+ def apply(found, today):
787
+ _text_change(found, "refuted", "Refuted", args.because, today)
788
+ return [f"m:{found[0].handle}\trefuted"]
789
+
790
+ return _act(args, [args.handle], apply, "refute", args.because)
791
+
792
+
793
+ def cmd_forget(args: argparse.Namespace) -> int:
794
+ def apply(found, today):
795
+ _text_change(
796
+ found, "forgotten", "Forgotten", args.because, today, triage=None, triage_reason=None
797
+ )
798
+ return [f"m:{found[0].handle}\tforgotten"]
799
+
800
+ return _act(args, [args.handle], apply, "forget", args.because)
801
+
802
+
803
+ def _project_md_files(folder: Path, n: int, total: int) -> list[Path]:
804
+ try: # os.listdir raises on a folder that cannot be read; Path.glob would return nothing
805
+ return [folder / name for name in os.listdir(folder) if name.endswith(".md")]
806
+ except OSError as exc:
807
+ raise ValueError(f"project memory folder {n} of {total} cannot be read ({exc})") from exc
808
+
809
+
810
+ def _linked_in_folder(
811
+ handle: str, named: re.Pattern[str], folder: Path, files: list[Path]
812
+ ) -> list[records.Memory]:
813
+ found = []
814
+ for m in records.load_memories(folder, "project"):
815
+ if m.error is None:
816
+ if m.general == handle:
817
+ found.append(m)
818
+ elif m.path in files and named.search(m.path.read_text(encoding="utf-8", errors="replace")):
819
+ raise ValueError(
820
+ f"project record m:{m.handle} names it in `general` but cannot be parsed "
821
+ f"({m.error})"
822
+ )
823
+ return found
824
+
825
+
826
+ def _linked_in_counted_projects(handle: str) -> list[records.Memory]:
827
+ named = re.compile(rf"^general:\s*['\"]?{re.escape(handle)}['\"]?\s*$", re.MULTILINE)
828
+ found: list[records.Memory] = []
829
+ projects = corroborate_decide.counted_projects(
830
+ records.read_registry(common.data_dir(os.environ))
831
+ )
832
+ for n, project in enumerate(projects, 1):
833
+ folder = records.project_dir(project)
834
+ files = _project_md_files(folder, n, len(projects))
835
+ found += _linked_in_folder(handle, named, folder, files)
836
+ return found
837
+
838
+
839
+ def _linked_project_records(handle: str) -> list[records.Memory]:
840
+ """Step 1 of a reject: every project record, in every counted project, whose `general` names `handle`.
841
+ ValueError, with nothing changed yet, when a registry, a folder or a file that may name it cannot be read."""
842
+ try:
843
+ return _linked_in_counted_projects(handle)
844
+ except (OSError, ValueError) as exc:
845
+ raise ValueError(
846
+ f"reject stopped while looking for the project records that name it: {exc}; "
847
+ "no change was made"
848
+ ) from exc
849
+
850
+
851
+ def _reject(found: list[records.Memory], today: datetime.date) -> list[str]:
852
+ m = found[0]
853
+ linked = _linked_project_records(
854
+ m.handle
855
+ ) # before any change: a refusal leaves everything as it was
856
+ done: list[str] = []
857
+ try:
858
+ for record in linked:
859
+ records.log_before(record, "triage")
860
+ records.update(record, today, promote="no", general=None)
861
+ done.append(f"m:{record.handle}")
862
+ except (OSError, ValueError, yaml.YAMLError) as exc:
863
+ raise ValueError(
864
+ f"reject failed while unlinking the project records ({exc}); unlinked so far: "
865
+ f"{', '.join(done) or 'none'}; the global record is still active"
866
+ ) from exc
867
+ try:
868
+ _text_change(found, "forgotten", "Forgotten", None, today, triage=None, triage_reason=None)
869
+ except (OSError, ValueError, yaml.YAMLError) as exc:
870
+ raise ValueError(
871
+ f"reject failed while retiring m:{m.handle} ({exc}); the project records were already "
872
+ f"unlinked: {', '.join(done) or 'none'}; the global record is still active"
873
+ ) from exc
874
+ return [
875
+ f"m:{m.handle}\trejected",
876
+ f"unlinked {len(done)} project record{'' if len(done) == 1 else 's'}",
877
+ *(f"{h}\tunlinked" for h in done),
878
+ ]
879
+
880
+
881
+ def _triage_hold(m: records.Memory, today: datetime.date, because: str | None) -> list[str]:
882
+ if m.status != "active":
883
+ raise ValueError(f"m:{m.handle} is {m.status}: only an active lesson can be held")
884
+ if records.quarantined(m):
885
+ raise ValueError(
886
+ f"m:{m.handle} is in quarantine: it is not shown anyway until corroborated"
887
+ )
888
+ records.log_before(m, "triage")
889
+ records.update(m, today, triage="pending", triage_reason=because)
890
+ return [f"m:{m.handle}\theld"]
891
+
892
+
893
+ def _triage_refuse_unawaited(m: records.Memory) -> None:
894
+ """Raise: `m` is not awaiting triage, and say why."""
895
+ if records.quarantined(m):
896
+ raise ValueError(
897
+ f"m:{m.handle} is still in quarantine: it leaves quarantine when seen in a second "
898
+ "project or confirmed with mem confirm --by-owner"
899
+ )
900
+ raise ValueError(f"m:{m.handle} was already accepted or never awaited triage")
901
+
902
+
903
+ def _triage_decide(command: str, found: list[records.Memory], today: datetime.date) -> list[str]:
904
+ """Accept or reject (`command`) the lesson `found[0]`, which must be active and awaiting triage."""
905
+ m = found[0]
906
+ if m.status != "active":
907
+ raise ValueError(f"m:{m.handle} is {m.status}: only an active general lesson awaits triage")
908
+ if command == "accept" and m.triage != "pending" and records.got_worse(m):
909
+ records.log_before(m, "triage")
910
+ records.update(m, today, reviewed=today)
911
+ return [f"m:{m.handle}\tkept as worded"]
912
+ if m.triage != "pending":
913
+ _triage_refuse_unawaited(m)
914
+ if command == "accept":
915
+ records.log_before(m, "triage")
916
+ records.update(m, today, triage=None, triage_reason=None)
917
+ return [f"m:{m.handle}\taccepted"]
918
+ return _reject(found, today)
919
+
920
+
921
+ def _triage_apply(
922
+ args: argparse.Namespace,
923
+ because: str | None,
924
+ found: list[records.Memory],
925
+ today: datetime.date,
926
+ ) -> list[str]:
927
+ m = found[0]
928
+ if (
929
+ getattr(args, "project_scope", False) and m.scope != "project"
930
+ ): # the lookup falls back to the global scope
931
+ raise ValueError(f"no memory named m:{m.handle}")
932
+ if args.triage_command == "hold":
933
+ return _triage_hold(m, today, because)
934
+ return _triage_decide(args.triage_command, found, today)
935
+
936
+
937
+ def cmd_triage(args: argparse.Namespace) -> int:
938
+ """Accept or reject a general lesson that left quarantine, on the global scope; accept also keeps the wording
939
+ of a lesson that got worse, and with --project-scope that lesson may be a project one."""
940
+ args.is_global = not getattr(args, "project_scope", False)
941
+ because = None
942
+ if args.triage_command == "hold":
943
+ because = " ".join((args.because or "").split())
944
+ if not because or not records.valid_triage_reason(because):
945
+ print(
946
+ f"mem: hold needs --because, one line of at most {records.TRIAGE_REASON_LIMIT} characters.",
947
+ file=sys.stderr,
948
+ )
949
+ return 2
950
+
951
+ def apply(found, today):
952
+ return _triage_apply(args, because, found, today)
953
+
954
+ return _act(args, [args.handle], apply, f"triage-{args.triage_command}", because)
955
+
956
+
957
+ def _two(args: argparse.Namespace, first: str, second: str, name: str, apply) -> int:
958
+ if first.removeprefix("m:") == second.removeprefix("m:"):
959
+ print(f"mem: {name} needs two different memories.", file=sys.stderr)
960
+ return 2
961
+ return _act(args, [first, second], apply, name)
962
+
963
+
964
+ def _supersede_pair(old: records.Memory, new: records.Memory, today: datetime.date) -> list[str]:
965
+ records.log_before(old, "supersede")
966
+ records.update(old, today, status="superseded", superseded_by=new.handle)
967
+ return [f"m:{old.handle}\tsuperseded by m:{new.handle}"]
968
+
969
+
970
+ def cmd_supersede(args: argparse.Namespace) -> int:
971
+ def apply(found: list[records.Memory], today: datetime.date) -> list[str]:
972
+ return _supersede_pair(found[0], found[1], today)
973
+
974
+ return _two(args, args.old, args.new, "supersede", apply)
975
+
976
+
977
+ def _undo_failed_edit(
978
+ m: records.Memory, original: bytes, updating: bool, log: Path, log_before: bytes | None
979
+ ) -> None:
980
+ """Put a memory file and its curation log back as they were before an edit that failed."""
981
+ if updating and m.path.read_bytes() != original:
982
+ common._swap_file(m.path, original)
983
+ if log_before is None:
984
+ log.unlink(missing_ok=True)
985
+ else:
986
+ safe_io.replace_file(log, log_before)
987
+
988
+
989
+ def _reword_failed_conflicts(args: argparse.Namespace) -> bool:
990
+ """True when `--reword-failed` comes with another change."""
991
+ others = (args.claim, args.context, args.body_file, args.short, args.topic)
992
+ flags = (args.no_load, args.load, args.index_only, args.reworded, args.user_read)
993
+ return any(o is not None for o in others) or any(flags)
994
+
995
+
996
+ def _reword_failed(args: argparse.Namespace) -> int:
997
+ """`mem memory edit <h> --reword-failed`: note the version the automatic rewording gave up on; nothing else changes."""
998
+ if _reword_failed_conflicts(args):
999
+ print(
1000
+ "mem: --reword-failed stands alone: it changes no other part of the lesson.",
1001
+ file=sys.stderr,
1002
+ )
1003
+ return 2
1004
+ found = _memory_of(args, [args.handle])
1005
+ if found is None:
1006
+ return 2
1007
+ m = found[0]
1008
+ versions = records.version_list(m)
1009
+ if not versions:
1010
+ print(f"mem: m:{m.handle} has no short form version to give up on.", file=sys.stderr)
1011
+ return 2
1012
+ log = m.path.parent / records.CURATION_LOG
1013
+ log_before = log.read_bytes() if log.exists() else None
1014
+ original = m.path.read_bytes()
1015
+ updating = False
1016
+ try:
1017
+ records.log_before(m, "edit")
1018
+ updating = True
1019
+ records.update(m, datetime.date.today(), reword_failed=versions[-1][0])
1020
+ except (
1021
+ OSError,
1022
+ ValueError,
1023
+ yaml.YAMLError,
1024
+ ) as exc: # any failure leaves the memory and its log as they were
1025
+ _undo_failed_edit(m, original, updating, log, log_before)
1026
+ print(f"mem: {exc}", file=sys.stderr)
1027
+ return 2
1028
+ print(f"m:{m.handle}\tedited reword failed")
1029
+ common.log_usage(
1030
+ common._optional_store(args),
1031
+ {"cmd": "memory", "action": "edit", "scope": m.scope, **_approval(args)},
1032
+ )
1033
+ return 0
1034
+
1035
+
1036
+ @dataclass(frozen=True)
1037
+ class _MemoryEditInputs:
1038
+ """What `mem memory edit` was asked to write, cleaned: whitespace folded, the body file read."""
1039
+
1040
+ claim: str | None
1041
+ context: str | None
1042
+ body: str | None
1043
+ texts: list[str]
1044
+
1045
+
1046
+ def _memory_edit_flags_refused(args: argparse.Namespace) -> int | None:
1047
+ """The exit code of an edit whose flags contradict each other or ask for nothing; None when they are fine."""
1048
+ if args.reworded and (not args.short or args.user_read):
1049
+ print(
1050
+ "mem: --reworded goes with a non-empty --short and without --user-read: it marks a model's rewording.",
1051
+ file=sys.stderr,
1052
+ )
1053
+ return 2
1054
+ asks = (args.claim, args.context, args.body_file, args.short, args.topic)
1055
+ if all(a is None for a in asks) and not args.no_load and not args.load and not args.index_only:
1056
+ raise common.UsageError(
1057
+ "memory edit needs --claim, --context, --body-file, --short, --topic, --no-load, --index-only or --load"
1058
+ )
1059
+ return None
1060
+
1061
+
1062
+ def _memory_edit_inputs(args: argparse.Namespace) -> _MemoryEditInputs | int:
1063
+ """The cleaned texts of an edit, or the exit code of the refusal (empty claim, bad short form, secret)."""
1064
+ claim = " ".join(args.claim.split()) if args.claim is not None else None
1065
+ context = " ".join(args.context.split()) if args.context is not None else None
1066
+ try:
1067
+ body = common._read_body(args.body_file) if args.body_file else None
1068
+ except common.NewNoteError as exc:
1069
+ print(f"mem: {exc}", file=sys.stderr)
1070
+ return 2
1071
+ if claim is not None and not claim:
1072
+ print("mem: the claim is empty.", file=sys.stderr)
1073
+ return 2
1074
+ if (refused := _check_short_topic(args)) is not None:
1075
+ return refused
1076
+ texts = [t for t in (claim, context, body, args.short) if t]
1077
+ if common._refuse_secret(texts):
1078
+ return 4
1079
+ return _MemoryEditInputs(claim, context, body, texts)
1080
+
1081
+
1082
+ def _memory_edit_target(args: argparse.Namespace, edit: _MemoryEditInputs) -> records.Memory | int:
1083
+ """The memory to edit, or the exit code of the refusal (unknown, not active, bad short form, forbidden terms)."""
1084
+ found = _memory_of(args, [args.handle])
1085
+ if found is None:
1086
+ return 2
1087
+ m = found[0]
1088
+ if m.status != "active":
1089
+ print(
1090
+ f"mem: m:{m.handle} is {m.status}: run mem restore m:{m.handle} to bring it back before editing it.",
1091
+ file=sys.stderr,
1092
+ )
1093
+ return 2
1094
+ if (
1095
+ refused := _check_short_claim(args, edit.claim if edit.claim is not None else m.claim)
1096
+ ) is not None:
1097
+ return refused
1098
+ if (
1099
+ m.scope == "global"
1100
+ and edit.texts
1101
+ and (
1102
+ refused := common._check_terms(
1103
+ edit.texts, m.kind, getattr(args, "owner_approved", False)
1104
+ )
1105
+ )
1106
+ ):
1107
+ return refused
1108
+ return m
1109
+
1110
+
1111
+ def _memory_edit_wording(
1112
+ args: argparse.Namespace,
1113
+ m: records.Memory,
1114
+ edit: _MemoryEditInputs,
1115
+ changes: dict[str, Any],
1116
+ what: list[str],
1117
+ ) -> None:
1118
+ """Add the claim, context and body changes to `changes`, refusing a shrink the guard stops."""
1119
+ if edit.claim is not None:
1120
+ if not args.shrink:
1121
+ synthesis_edit._guard_shrink(m.claim, edit.claim, sentences=False)
1122
+ changes["claim"] = edit.claim
1123
+ what.append("claim")
1124
+ if edit.context is not None:
1125
+ changes["context"] = edit.context or None
1126
+ what.append("context")
1127
+ if edit.body is not None:
1128
+ if not args.shrink:
1129
+ synthesis_edit._guard_shrink(m.body.strip("\n"), edit.body.strip("\n"))
1130
+ changes["body"] = edit.body
1131
+ what.append("body")
1132
+
1133
+
1134
+ def _memory_edit_short(
1135
+ args: argparse.Namespace,
1136
+ m: records.Memory,
1137
+ claim: str | None,
1138
+ changes: dict[str, Any],
1139
+ what: list[str],
1140
+ ) -> bool:
1141
+ """Add the short form change to `changes`; True when a new claim removed the old short form."""
1142
+ if args.short is not None:
1143
+ changes["short"] = args.short or None
1144
+ changes["short_by"] = "model" if args.short and not args.user_read else None
1145
+ if args.reworded:
1146
+ changes["reworded"] = datetime.date.today()
1147
+ what.append("short")
1148
+ elif claim is not None and claim != m.claim and (m.short or m.short_by):
1149
+ changes["short"] = None # a short form never outlives the claim it was drawn from
1150
+ changes["short_by"] = None
1151
+ if m.short:
1152
+ what.append("short removed")
1153
+ return True
1154
+ return False
1155
+
1156
+
1157
+ def _memory_edit_topic_load(
1158
+ args: argparse.Namespace, changes: dict[str, Any], what: list[str]
1159
+ ) -> None:
1160
+ """Add the topic and load changes to `changes`."""
1161
+ if args.topic is not None:
1162
+ changes["topic"] = args.topic or None
1163
+ what.append("topic")
1164
+ if args.no_load:
1165
+ changes["load"] = "no"
1166
+ what.append("load")
1167
+ elif args.index_only:
1168
+ changes["load"] = "index"
1169
+ what.append("load")
1170
+ elif args.load:
1171
+ changes["load"] = None
1172
+ what.append("load")
1173
+
1174
+
1175
+ def _memory_edit_commit(
1176
+ m: records.Memory,
1177
+ changes: dict[str, Any],
1178
+ original: bytes,
1179
+ log: Path,
1180
+ log_before: bytes | None,
1181
+ ) -> None:
1182
+ """Write `changes` with undo: refused when the file changed since `original`, and any failure restores it."""
1183
+ updating = False
1184
+ try:
1185
+ records.log_before(m, "edit")
1186
+ if m.path.read_bytes() != original:
1187
+ raise ValueError(
1188
+ f"{m.path.name} changed since it was read, so nothing was written: run the command again"
1189
+ )
1190
+ updating = True
1191
+ records.update(m, datetime.date.today(), **changes)
1192
+ except BaseException: # any failure leaves the memory and its log as they were
1193
+ _undo_failed_edit(m, original, updating, log, log_before)
1194
+ raise
1195
+
1196
+
1197
+ def _memory_edit_write(
1198
+ args: argparse.Namespace,
1199
+ m: records.Memory,
1200
+ edit: _MemoryEditInputs,
1201
+ log: Path,
1202
+ log_before: bytes | None,
1203
+ ) -> tuple[list[str], bool]:
1204
+ """Write an edit; the parts it changed, and whether a new claim removed the short form."""
1205
+ original = m.path.read_bytes()
1206
+ what: list[str] = []
1207
+ changes: dict[str, Any] = {}
1208
+ _memory_edit_wording(args, m, edit, changes, what)
1209
+ short_removed = _memory_edit_short(args, m, edit.claim, changes, what)
1210
+ _memory_edit_topic_load(args, changes, what)
1211
+ _memory_edit_commit(m, changes, original, log, log_before)
1212
+ return what, short_removed
1213
+
1214
+
1215
+ def _memory_edit_finish(
1216
+ args: argparse.Namespace, m: records.Memory, what: list[str], short_removed: bool
1217
+ ) -> None:
1218
+ """Report an edit that was written: register the project, print the result, log the use."""
1219
+ if m.scope == "project":
1220
+ _register_project(records.project_root(Path.cwd(), os.environ))
1221
+ if short_removed:
1222
+ print(
1223
+ "mem: the short form was removed with the old claim: write a new one with --short",
1224
+ file=sys.stderr,
1225
+ )
1226
+ print(f"m:{m.handle}\tedited {', '.join(what)}")
1227
+ common.log_usage(
1228
+ common._optional_store(args),
1229
+ {"cmd": "memory", "action": "edit", "scope": m.scope, **_approval(args)},
1230
+ )
1231
+ if m.scope == "global" and m.origin != "pipeline":
1232
+ settle_state.maybe_start(
1233
+ m.path.parent,
1234
+ common._optional_store(args),
1235
+ os.environ,
1236
+ time.time(),
1237
+ datetime.date.today(),
1238
+ )
1239
+
1240
+
1241
+ def cmd_memory(args: argparse.Namespace) -> int:
1242
+ """`mem memory edit`: the claim, context or body of a memory, through the guard, with undo."""
1243
+ if args.reword_failed:
1244
+ return _reword_failed(args)
1245
+ if (refused := _memory_edit_flags_refused(args)) is not None:
1246
+ return refused
1247
+ edit = _memory_edit_inputs(args)
1248
+ if isinstance(edit, int):
1249
+ return edit
1250
+ m = _memory_edit_target(args, edit)
1251
+ if isinstance(m, int):
1252
+ return m
1253
+ log = m.path.parent / records.CURATION_LOG
1254
+ log_before = log.read_bytes() if log.exists() else None
1255
+ try:
1256
+ what, short_removed = _memory_edit_write(args, m, edit, log, log_before)
1257
+ except (OSError, ValueError, yaml.YAMLError) as exc:
1258
+ print(f"mem: {exc}", file=sys.stderr)
1259
+ return 2
1260
+ _memory_edit_finish(args, m, what, short_removed)
1261
+ return 0
1262
+
1263
+
1264
+ def _merge_session_changes(
1265
+ keep: records.Memory, drop: records.Memory, today: datetime.date
1266
+ ) -> dict[str, Any]:
1267
+ """The `sources` of a merge, and the standing that goes with them when the kept record came from a session."""
1268
+ sources = records.normalized_sources([*keep.sources, *drop.sources])
1269
+ changes: dict[str, Any] = {"sources": sources}
1270
+ if keep.origin == "transcript":
1271
+ after = dataclasses.replace(keep, sources=sources)
1272
+ standing_changes = records.standing_changes(keep, after, today)
1273
+ if records.standing(after) == "established" or len(records.sessions(after)) > len(
1274
+ records.sessions(keep)
1275
+ ):
1276
+ changes.update(
1277
+ standing_changes
1278
+ ) # enough evidence now, or a new session renews the 30 days
1279
+ return changes
1280
+
1281
+
1282
+ def _merge_pair(keep: records.Memory, drop: records.Memory, today: datetime.date) -> list[str]:
1283
+ records.log_before(keep, "merge")
1284
+ records.log_before(drop, "merge")
1285
+ records.update(drop, today, status="superseded", superseded_by=keep.handle)
1286
+ changes: dict[str, Any] = {"observed": keep.observed + drop.observed}
1287
+ if drop.body.strip():
1288
+ changes["body"] = _with_note(
1289
+ keep.body, f"Merged from m:{drop.handle} on {today.isoformat()}:", drop.body
1290
+ )
1291
+ if "transcript" in {
1292
+ keep.origin,
1293
+ drop.origin,
1294
+ }: # a session must survive the merge, whichever record holds it
1295
+ changes.update(_merge_session_changes(keep, drop, today))
1296
+ log = records.merged_log(keep, drop)
1297
+ if log != keep.log:
1298
+ changes["log"] = log
1299
+ versions = records.merged_versions(keep, drop, today)
1300
+ if versions and versions != keep.versions:
1301
+ changes["versions"] = versions
1302
+ updated = records.update(keep, today, **changes)
1303
+ return [f"m:{updated.handle}\tobserved {updated.observed}, merged m:{drop.handle}"]
1304
+
1305
+
1306
+ def cmd_merge(args: argparse.Namespace) -> int:
1307
+ def apply(found, today):
1308
+ keep, drop = found
1309
+ flagged = records.flagged_words(keep.claim, drop.claim)
1310
+ if flagged and not args.force:
1311
+ raise ValueError(
1312
+ f"these claims differ in {', '.join(flagged)}: they may be opposites or different "
1313
+ "versions; use --force to merge anyway."
1314
+ )
1315
+ return _merge_pair(keep, drop, today)
1316
+
1317
+ return _two(args, args.keep, args.drop, "merge", apply)
1318
+
1319
+
1320
+ def _distinct_note_paths(args: argparse.Namespace, store: Path) -> tuple[Path, Path] | None:
1321
+ """The two notes `mem distinct` names; None when the arguments are not both notes of the store."""
1322
+ if args.a.startswith("m:") or args.b.startswith("m:"):
1323
+ return None
1324
+ first, second = common.resolve_note(store, args.a), common.resolve_note(store, args.b)
1325
+ if not isinstance(first, Path) or not isinstance(second, Path):
1326
+ return None
1327
+ return first, second
1328
+
1329
+
1330
+ def _distinct_edit(path: Path, other_name: str) -> tuple[bytes, str]:
1331
+ """A note's current bytes, and its text with `other_name` added to `distinct_from`."""
1332
+ text = note_files._read_text(path)
1333
+ meta, _, _ = note_files.split_frontmatter(text)
1334
+ listed = meta.get("distinct_from") if isinstance(meta, dict) else None
1335
+ known = [h for h in listed if isinstance(h, str)] if isinstance(listed, list) else []
1336
+ return (
1337
+ path.read_bytes(),
1338
+ common._set_field(text, "distinct_from", sorted({*known, other_name})),
1339
+ )
1340
+
1341
+
1342
+ def _distinct_write(root: Path, first: Path, second: Path) -> dict[Path, str]:
1343
+ """Mark the two notes as distinct from each other and log the group; the handle of each note."""
1344
+ names = {p: note_files._handle(p.relative_to(root).as_posix()) for p in (first, second)}
1345
+ originals, edits = {}, {}
1346
+ for path, other in ((first, second), (second, first)):
1347
+ originals[path], edits[path] = _distinct_edit(path, names[other])
1348
+ for path, text in edits.items():
1349
+ safe_io.replace_file(path, text.encode("utf-8"))
1350
+ common._log_group(root, originals, "distinct")
1351
+ return names
1352
+
1353
+
1354
+ def _distinct_notes(args: argparse.Namespace, store: Path) -> int | None:
1355
+ """`mem distinct` for two notes of the store; None when the arguments are not both notes."""
1356
+ paths = _distinct_note_paths(args, store)
1357
+ if paths is None:
1358
+ return None
1359
+ first, second = paths
1360
+ root = _writable_store(args, "distinct")
1361
+ if root is None:
1362
+ return 2
1363
+ root = root.resolve()
1364
+ if first == second:
1365
+ print("mem: distinct needs two different notes.", file=sys.stderr)
1366
+ return 2
1367
+ try:
1368
+ names = _distinct_write(root, first, second)
1369
+ except (OSError, ValueError, note_files.FrontmatterError) as exc:
1370
+ print(f"mem: {exc}", file=sys.stderr)
1371
+ return 2
1372
+ print(f"{names[first]}\tkept apart from {names[second]}")
1373
+ common.log_usage(root, {"cmd": "distinct", "scope": "note"})
1374
+ return 0
1375
+
1376
+
1377
+ def _distinct_pair(a: records.Memory, b: records.Memory, today: datetime.date) -> list[str]:
1378
+ for m in (a, b):
1379
+ records.log_before(m, "distinct")
1380
+ for m, other in ((a, b), (b, a)):
1381
+ records.update(m, today, distinct_from=sorted({*m.distinct_from, other.handle}))
1382
+ return [f"m:{a.handle}\tkept apart from m:{b.handle}"]
1383
+
1384
+
1385
+ def cmd_distinct(args: argparse.Namespace) -> int:
1386
+ store = common._optional_store(args)
1387
+ if store is not None and store.is_dir() and (done := _distinct_notes(args, store)) is not None:
1388
+ return done
1389
+
1390
+ def apply(found: list[records.Memory], today: datetime.date) -> list[str]:
1391
+ return _distinct_pair(found[0], found[1], today)
1392
+
1393
+ return _two(args, args.a, args.b, "distinct", apply)
1394
+
1395
+
1396
+ def _writable_store(args: argparse.Namespace, command: str) -> Path | None:
1397
+ root = args.root
1398
+ if not isinstance(root, Path) or not root.is_dir():
1399
+ print(
1400
+ common.no_store_message(os.environ) if root is None else common.NO_STORE,
1401
+ file=sys.stderr,
1402
+ )
1403
+ return None
1404
+ if not records.store_is_writable(root):
1405
+ print(
1406
+ f"mem: {command} writes to the store, which is read-only: it has no mem-store.yaml "
1407
+ '(create a store with "mem init").',
1408
+ file=sys.stderr,
1409
+ )
1410
+ return None
1411
+ return root
1412
+
1413
+
1414
+ def _synthesis_ref_path(root: Path, ref: str) -> tuple[str, Path] | None:
1415
+ """The handle and file of the synthesis `ref` names; None when it names no synthesis (or a section of one)."""
1416
+ handle, section = document.split_ref(ref)
1417
+ path = document.path_of(root / document.SYNTHESES_DIR, handle)
1418
+ if section is not None or path is None or not path.is_file():
1419
+ return None
1420
+ return handle, path
1421
+
1422
+
1423
+ def _synthesis_newest_group(root: Path, rel: str, path: Path, entry: dict | None) -> dict | None:
1424
+ """The logged group action (rename or remove) that is the newest change to a synthesis; None when its own entry is."""
1425
+ group = records.last_log_entry(
1426
+ _StoreLog(root / "note", rel)
1427
+ ) # a rename or remove logs its files as a group
1428
+ if (
1429
+ group is not None
1430
+ and group.get("group")
1431
+ and (entry is None or common._sha(path.read_bytes()) == group.get("after"))
1432
+ ):
1433
+ # the file is as the group's action left it (or has no own entry): the group is the newest change; when
1434
+ # the file differs, a change came after the group and its own entry is the one to undo
1435
+ return group
1436
+ return None
1437
+
1438
+
1439
+ def _restore_logged_text(syn: document.Synthesis, entry: dict) -> bool:
1440
+ """Put back the text before the logged change; False, with the error printed, when the file cannot be written."""
1441
+ if entry["skipped"]:
1442
+ print(
1443
+ f"mem: skipped {entry['skipped']} unreadable lines in the curation log", file=sys.stderr
1444
+ )
1445
+ try:
1446
+ records.restore(syn, entry)
1447
+ except OSError as exc:
1448
+ print(f"mem: {exc}", file=sys.stderr)
1449
+ return False
1450
+ return True
1451
+
1452
+
1453
+ def _restore_synthesis(args: argparse.Namespace) -> int:
1454
+ root = _writable_store(args, "restore")
1455
+ if root is None:
1456
+ return 2
1457
+ located = _synthesis_ref_path(root, args.handle)
1458
+ if located is None:
1459
+ print(f"mem: no synthesis named {args.handle}", file=sys.stderr)
1460
+ return 2
1461
+ handle, path = located
1462
+ syn = document.Synthesis(path, handle)
1463
+ entry = records.last_log_entry(syn)
1464
+ rel = f"{document.SYNTHESES_DIR}/{path.name}"
1465
+ group = _synthesis_newest_group(root, rel, path, entry)
1466
+ if group is not None:
1467
+ return _restore_group(root, rel, group, f"s:{handle}")
1468
+ if entry is None:
1469
+ print(f"mem: no logged text for s:{handle}: nothing to restore", file=sys.stderr)
1470
+ return 2
1471
+ if not _restore_logged_text(syn, entry):
1472
+ return 2
1473
+ print(f"s:{handle}\trestored to before {entry.get('action')} of {str(entry.get('t'))[:10]}")
1474
+ common.log_usage(root, {"cmd": "restore", "scope": "synthesis"})
1475
+ return 0
1476
+
1477
+
1478
+ @dataclass
1479
+ class _StoreLog:
1480
+ """A note's entry in the store-level `.curation-log` (the log sits beside `path`, the store's root)."""
1481
+
1482
+ path: Path
1483
+ handle: str
1484
+
1485
+
1486
+ def _restore_log_record(line: str) -> dict | None:
1487
+ """A curation log line as a record; None for a line that is not JSON or not an object."""
1488
+ try:
1489
+ logged = json.loads(line)
1490
+ except ValueError:
1491
+ return None
1492
+ return logged if isinstance(logged, dict) else None
1493
+
1494
+
1495
+ def _restore_group_members(root: Path, entry: dict) -> list[tuple[int, dict]]:
1496
+ """The log lines (number, record) of the group `entry` belongs to that no restore has undone yet."""
1497
+ lines = (root / records.CURATION_LOG).read_text(encoding="utf-8").split("\n")
1498
+ members: list[tuple[int, dict]] = []
1499
+ undone: set[int] = set()
1500
+ for number, line in enumerate(lines):
1501
+ logged = _restore_log_record(line)
1502
+ if logged is None:
1503
+ continue
1504
+ if logged.get("action") == "restore" and isinstance(logged.get("undone"), int):
1505
+ undone.add(logged["undone"])
1506
+ elif logged.get("group") == entry["group"] and isinstance(logged.get("before"), str):
1507
+ members.append((number, logged))
1508
+ return [(n, e) for n, e in members if n not in undone]
1509
+
1510
+
1511
+ def _restore_file_current(root: Path, e: dict) -> bool:
1512
+ """True when the file of the logged change is still as that change left it."""
1513
+ return (root / e["handle"]).is_file() and common._sha(
1514
+ (root / e["handle"]).read_bytes()
1515
+ ) == e.get("after")
1516
+
1517
+
1518
+ def _restore_member(root: Path, e: dict, number: int, stamp: str) -> None:
1519
+ """Undo one logged file change (moving a renamed note and its sources back) and log the undo."""
1520
+ target = root / e.get("from", e["handle"])
1521
+ safe_io.replace_file(target, e["before"].encode("utf-8"))
1522
+ if "from" in e:
1523
+ (root / e["handle"]).unlink()
1524
+ sources, was = (
1525
+ root / common.SOURCES_DIR / Path(e["handle"]).stem,
1526
+ root / common.SOURCES_DIR / Path(e["from"]).stem,
1527
+ )
1528
+ if sources.is_dir() and not was.exists():
1529
+ sources.rename(was)
1530
+ marker = {"t": stamp, "action": "restore", "handle": e["handle"], "undone": number}
1531
+ safe_io.append_text(root / records.CURATION_LOG, json.dumps(marker, ensure_ascii=False) + "\n")
1532
+
1533
+
1534
+ def _restore_members(
1535
+ root: Path, members: list[tuple[int, dict]], rebuild: bool, stamp: str
1536
+ ) -> None:
1537
+ for number, e in members:
1538
+ _restore_member(root, e, number, stamp)
1539
+ if rebuild:
1540
+ index_files.apply_index(root)
1541
+
1542
+
1543
+ def _restore_group(root: Path, rel: str, entry: dict, label: str | None = None) -> int:
1544
+ """Undo every file of the unify, rename or distinct that logged `entry`, or none: refused when any changed since.
1545
+
1546
+ A README listing that changed since is left alone (not a refusal) and rebuilt by `apply_index`; one that is
1547
+ as the action left it gets its exact previous bytes back."""
1548
+ members = _restore_group_members(root, entry)
1549
+ listing = {n: link_rules._is_index_readme(e["handle"]) for n, e in members}
1550
+ moved = [
1551
+ e["handle"] for n, e in members if not listing[n] and not _restore_file_current(root, e)
1552
+ ]
1553
+ if moved:
1554
+ print(
1555
+ f"mem: {', '.join(moved)} changed since {entry.get('action')}, so nothing was restored: "
1556
+ "restore or edit those files by hand",
1557
+ file=sys.stderr,
1558
+ )
1559
+ return 2
1560
+ kept = [(n, e) for n, e in members if not listing[n] or _restore_file_current(root, e)]
1561
+ rebuild = not any(listing.values()) or len(kept) < len(members)
1562
+ members = kept
1563
+ stamp = datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
1564
+ try:
1565
+ _restore_members(root, members, rebuild, stamp)
1566
+ except (OSError, note_files.FrontmatterError) as exc:
1567
+ print(f"mem: {exc}", file=sys.stderr)
1568
+ return 2
1569
+ print(
1570
+ f"{label or note_files._handle(rel)}\trestored to before {entry.get('action')} of {str(entry.get('t'))[:10]} "
1571
+ f"({len(members)} files)"
1572
+ )
1573
+ common.log_usage(root, {"cmd": "restore", "scope": "note"})
1574
+ return 0
1575
+
1576
+
1577
+ def _restore_note(args: argparse.Namespace, root: Path, note: Path) -> int:
1578
+ rel = note.relative_to(root.resolve()).as_posix()
1579
+ log = _StoreLog(root / "note", rel)
1580
+ entry = records.last_log_entry(log)
1581
+ if entry is None:
1582
+ print(
1583
+ f"mem: no logged text for {note_files._handle(rel)}: nothing to restore",
1584
+ file=sys.stderr,
1585
+ )
1586
+ return 2
1587
+ if entry.get("group"):
1588
+ return _restore_group(root, rel, entry)
1589
+ try:
1590
+ safe_io.replace_file(note, entry["before"].encode("utf-8"))
1591
+ marker = {
1592
+ "t": datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
1593
+ "action": "restore",
1594
+ "handle": rel,
1595
+ "undone": entry["line"],
1596
+ }
1597
+ safe_io.append_text(
1598
+ root / records.CURATION_LOG, json.dumps(marker, ensure_ascii=False) + "\n"
1599
+ )
1600
+ except OSError as exc:
1601
+ print(f"mem: {exc}", file=sys.stderr)
1602
+ return 2
1603
+ print(
1604
+ f"{note_files._handle(rel)}\trestored to before {entry.get('action')} of {str(entry.get('t'))[:10]}"
1605
+ )
1606
+ common.log_usage(root, {"cmd": "restore", "scope": "note"})
1607
+ return 0
1608
+
1609
+
1610
+ def _restore_store_note(args: argparse.Namespace) -> int | None:
1611
+ """Restore the note of the store that `args.handle` names; None when it names no note."""
1612
+ if args.handle.startswith("m:"):
1613
+ return None
1614
+ store = common._optional_store(args)
1615
+ if store is None or not isinstance(found := common.resolve_note(store, args.handle), Path):
1616
+ return None
1617
+ root = _writable_store(args, "restore")
1618
+ return 2 if root is None else _restore_note(args, root, found)
1619
+
1620
+
1621
+ def _restore_memory_text(found: list[records.Memory], today: datetime.date) -> list[str]:
1622
+ m = found[0]
1623
+ entry = records.last_log_entry(m)
1624
+ if entry is None:
1625
+ raise ValueError(f"no logged text for m:{m.handle}: nothing to restore")
1626
+ if entry["skipped"]:
1627
+ print(
1628
+ f"mem: skipped {entry['skipped']} unreadable lines in the curation log",
1629
+ file=sys.stderr,
1630
+ )
1631
+ records.restore(m, entry)
1632
+ return [f"m:{m.handle}\trestored to before {entry.get('action')} of {str(entry.get('t'))[:10]}"]
1633
+
1634
+
1635
+ def cmd_restore(args: argparse.Namespace) -> int:
1636
+ if args.handle.startswith("s:"):
1637
+ return _restore_synthesis(args)
1638
+ if (done := _restore_store_note(args)) is not None:
1639
+ return done
1640
+ return _act(args, [args.handle], _restore_memory_text, "restore")
1641
+
1642
+
1643
+ def _global_memory_exists(args: argparse.Namespace, handle: str) -> bool:
1644
+ """True when a readable global memory has this handle."""
1645
+ return any(
1646
+ m.handle == handle and m.error is None
1647
+ for m in records.load_memories(
1648
+ records.memories_root(os.environ, common._optional_store(args)), "global"
1649
+ )
1650
+ )
1651
+
1652
+
1653
+ def _promote_mark(args: argparse.Namespace, target: str | None) -> int:
1654
+ """`mem promote --no` or `--done`: mark each lesson as not to be promoted, or promoted (to `target`)."""
1655
+ value, text = ("no", "not to be promoted") if args.no else ("done", "promoted")
1656
+ extra = {"general": target} if target else {}
1657
+
1658
+ def apply(found, today):
1659
+ records.log_before(found[0], "promote")
1660
+ records.update(found[0], today, promote=value, **extra)
1661
+ return [f"m:{found[0].handle}\t{text}"]
1662
+
1663
+ for handle in args.handles:
1664
+ if _act(args, [handle], apply, "promote") != 0:
1665
+ return 2
1666
+ return 0
1667
+
1668
+
1669
+ def _promote_draft(args: argparse.Namespace) -> int:
1670
+ """`mem promote`: print the lessons to rewrite as one general lesson, and the command that records the promotion."""
1671
+ found = []
1672
+ for handle in args.handles:
1673
+ got = _memory_of(args, [handle])
1674
+ if got is None:
1675
+ return 2
1676
+ found.append(got[0])
1677
+ print('Draft for: mem remember --global --kind lesson --claim "\u2026"')
1678
+ for m in found:
1679
+ print(f"m:{m.handle}\t{' '.join(m.claim.split())}")
1680
+ if m.context:
1681
+ print(f" context: {' '.join(m.context.split())}")
1682
+ print(
1683
+ "Rewrite the claim in general terms, with no name of a project, system, client or person, "
1684
+ "before you run it; then run: mem promote --done <h>"
1685
+ )
1686
+ return 0
1687
+
1688
+
1689
+ def cmd_promote(args: argparse.Namespace) -> int:
1690
+ args.is_global = False
1691
+ if args.to and not args.done:
1692
+ print("mem: --to goes with --done.", file=sys.stderr)
1693
+ return 2
1694
+ target = args.to.removeprefix("m:") if args.to else None
1695
+ if args.to and not _global_memory_exists(args, args.to.removeprefix("m:")):
1696
+ print(f"mem: --to names no global memory: {args.to}", file=sys.stderr)
1697
+ return 2
1698
+ if args.no or args.done:
1699
+ return _promote_mark(args, target)
1700
+ return _promote_draft(args)
1701
+
1702
+
1703
+ def _loaded(
1704
+ folders: Sequence[tuple[str, Path | None]],
1705
+ ) -> list[tuple[str, Path | None, list[records.Memory]]]:
1706
+ out = []
1707
+ for scope, folder in folders:
1708
+ loaded = records.load_memories(folder, scope)
1709
+ for m in loaded:
1710
+ if m.error is not None:
1711
+ print(f"mem: skipped {m.path}: {m.error}", file=sys.stderr)
1712
+ out.append((scope, folder, loaded))
1713
+ return out
1714
+
1715
+
1716
+ def _flat(text: str) -> str:
1717
+ return " ".join(
1718
+ text.split()
1719
+ ) # a hand-edited tab or newline must not split the claim's paragraph
1720
+
1721
+
1722
+ def add_memories_arguments(parser: argparse.ArgumentParser) -> None:
1723
+ parser.add_argument("--kind", choices=records.KINDS)
1724
+ parser.add_argument(
1725
+ "--quarantine",
1726
+ action="store_true",
1727
+ help="only the global lessons in quarantine (not shown anywhere else until corroborated)",
1728
+ )
1729
+ parser.add_argument(
1730
+ "--dead", action="store_true", help="also list refuted, superseded, forgotten and expired"
1731
+ )
1732
+ parser.add_argument("--names", action="store_true", help="list only the m:<handle> names")
1733
+ parser.add_argument(
1734
+ "--pretty", action="store_true", help="group by topic and wrap claims to the terminal width"
1735
+ )
1736
+
1737
+
1738
+ def _memory_meta(m: records.Memory, args: argparse.Namespace, today: datetime.date) -> str:
1739
+ dead = common._memory_status(m, today)
1740
+ created = m.created.isoformat() if m.created else "undated"
1741
+ return (
1742
+ f"{m.kind} · topic: {m.topic or 'none'} · observed {m.observed} · {created}"
1743
+ f"{common._unconfirmed(m).replace(', ', ' · ')}"
1744
+ f"{' · quarantine' if args.quarantine else ''}"
1745
+ f"{' · ' + dead if dead else ''}"
1746
+ )
1747
+
1748
+
1749
+ def _memories_footer(shown: list[records.Memory]) -> str:
1750
+ if not shown:
1751
+ return "0 memories"
1752
+ topics = len({m.topic for m in shown if m.topic})
1753
+ bare = sum(1 for m in shown if not m.topic)
1754
+ memories = "1 memory" if len(shown) == 1 else f"{len(shown)} memories"
1755
+ return (
1756
+ f"{memories} · {topics} {'topic' if topics == 1 else 'topics'}"
1757
+ f"{f' ({bare} without topic)' if bare else ''}"
1758
+ )
1759
+
1760
+
1761
+ def _memories_groups(shown: list[records.Memory]) -> list[tuple[str, list[records.Memory]]]:
1762
+ """Topic groups by count descending then name; the no-topic group last."""
1763
+ groups: dict[str, list[records.Memory]] = {}
1764
+ for m in shown:
1765
+ groups.setdefault(m.topic or "", []).append(m)
1766
+ named = sorted(((t, g) for t, g in groups.items() if t), key=lambda x: (-len(x[1]), x[0]))
1767
+ return [*named, *([("no topic", groups[""])] if "" in groups else [])]
1768
+
1769
+
1770
+ def _memory_entry(m: records.Memory, args: argparse.Namespace, today: datetime.date) -> str:
1771
+ claim = _flat(m.claim)
1772
+ if args.pretty:
1773
+ claim = textwrap.fill(claim, width=shutil.get_terminal_size((100, 24)).columns)
1774
+ return f"### m:{m.handle}\n{_memory_meta(m, args, today)}\n\n{claim}"
1775
+
1776
+
1777
+ def _memories_body(
1778
+ items: list[records.Memory], args: argparse.Namespace, today: datetime.date
1779
+ ) -> str:
1780
+ if args.names:
1781
+ return "\n".join(f"{'- ' if args.pretty else ''}m:{m.handle}" for m in items)
1782
+ return "\n\n".join(_memory_entry(m, args, today) for m in items)
1783
+
1784
+
1785
+ def _print_memories(
1786
+ shown: list[records.Memory], args: argparse.Namespace, today: datetime.date
1787
+ ) -> None:
1788
+ if args.pretty:
1789
+ text = "\n\n".join(
1790
+ f"## {topic} ({len(items)})\n\n{_memories_body(items, args, today)}"
1791
+ for topic, items in _memories_groups(shown)
1792
+ )
1793
+ else:
1794
+ text = _memories_body(shown, args, today)
1795
+ if shown:
1796
+ print(f"{text}\n")
1797
+ print(_memories_footer(shown))
1798
+
1799
+
1800
+ def cmd_memories(args: argparse.Namespace) -> int:
1801
+ today = datetime.date.today()
1802
+ if args.project:
1803
+ named = common._other_projects([args.project], False)
1804
+ if named is None:
1805
+ return 2
1806
+ folder = common._named_folder(args.project)
1807
+ if folder is not None and not folder.is_dir():
1808
+ print(
1809
+ f"mem: the memory folder of project {args.project} was not found: {folder} (moved or deleted?)",
1810
+ file=sys.stderr,
1811
+ )
1812
+ return 2
1813
+ folders = [("project", folder)]
1814
+ else:
1815
+ folders = common._memory_folders(args)
1816
+ if not args.all:
1817
+ folders = [f for f in folders if (f[0] == "global") == args.is_global]
1818
+ shown = [
1819
+ m
1820
+ for _, _, loaded in _loaded(folders)
1821
+ for m in loaded
1822
+ if m.error is None
1823
+ and (args.kind is None or m.kind == args.kind)
1824
+ and (
1825
+ args.dead or records.is_live(m, today) or (args.quarantine and m.status == "active")
1826
+ ) # a lapsed lesson in quarantine is still listed
1827
+ and records.quarantined(m) == args.quarantine
1828
+ ]
1829
+ shown.sort(
1830
+ key=lambda m: (m.kind != "state", -(m.created or datetime.date.min).toordinal(), m.handle)
1831
+ )
1832
+ _print_memories(shown, args, today)
1833
+ return 0
1834
+
1835
+
1836
+ RULES_OFF_NOTICE = "Loaded rules are switched off (plugin option loaded_rules): nothing below loads at session start."
1837
+
1838
+
1839
+ def _rules_read_targets(
1840
+ args: argparse.Namespace, pool: list[records.Memory], unread: list[records.Memory]
1841
+ ) -> list[records.Memory] | None:
1842
+ """The memories `--read` names (`all` is every unread short form); None, with the error printed, when one is not live."""
1843
+ if args.read == ["all"]:
1844
+ return unread
1845
+ targets = []
1846
+ for raw in args.read:
1847
+ name = raw.removeprefix("m:")
1848
+ hit = next(
1849
+ (m for m in pool if m.handle == name), None
1850
+ ) # project first: the order of the scopes
1851
+ if hit is None:
1852
+ print(f"mem: no live memory named {raw}", file=sys.stderr)
1853
+ return None
1854
+ targets.append(hit)
1855
+ return targets
1856
+
1857
+
1858
+ def _rules_read_only_refused(args: argparse.Namespace, targets: list[records.Memory]) -> bool:
1859
+ """True, with the reason printed, when a target sits in a store that cannot be written."""
1860
+ store = common._optional_store(args)
1861
+ for m in targets:
1862
+ if common._read_only_store(store, m.path.resolve()):
1863
+ print(
1864
+ common._READ_ONLY_PROJECT if m.scope == "project" else common._READ_ONLY_MEMORIES,
1865
+ file=sys.stderr,
1866
+ )
1867
+ return True
1868
+ return False
1869
+
1870
+
1871
+ def _rules_print_unread(unread: list[records.Memory]) -> None:
1872
+ for m in unread:
1873
+ print(f"m:{m.handle}\t{m.scope}\t{m.short}\n\tclaim: {_flat(m.claim)}")
1874
+ if not unread:
1875
+ print("No short form is waiting to be read.")
1876
+
1877
+
1878
+ def _rules_mark_read(targets: list[records.Memory], today: datetime.date) -> None:
1879
+ for m in targets:
1880
+ if m.short_by:
1881
+ records.log_before(m, "edit")
1882
+ records.update(m, today, short_by=None)
1883
+ print(f"m:{m.handle}\tread")
1884
+
1885
+
1886
+ def _rules_unread(args: argparse.Namespace, today: datetime.date) -> int:
1887
+ """`--unread` lists the short forms a model wrote that nobody read; `--read` marks them read."""
1888
+ if args.unread and args.read:
1889
+ print("mem: --unread and --read cannot be used together.", file=sys.stderr)
1890
+ return 2
1891
+ scopes = _loaded(common._memory_folders(args))
1892
+ pool = [
1893
+ m
1894
+ for _, _, loaded in scopes
1895
+ for m in loaded
1896
+ if m.error is None and records.is_live(m, today)
1897
+ ]
1898
+ unread = [m for m in pool if m.short_by == "model" and m.short]
1899
+ if args.unread:
1900
+ _rules_print_unread(unread)
1901
+ return 0
1902
+ targets = _rules_read_targets(args, pool, unread)
1903
+ if targets is None or _rules_read_only_refused(args, targets):
1904
+ return 2
1905
+ _rules_mark_read(targets, today)
1906
+ return 0
1907
+
1908
+
1909
+ def _rules_stuck(
1910
+ choice: rules.Choice, root: Path | None, attempts: dict, today: datetime.date
1911
+ ) -> int:
1912
+ """How many established lessons without a short form the automatic fill will not write."""
1913
+ if common._rules_off():
1914
+ return 0 # the pass skips the fill while the loaded rules are off (`cmd_auto` of mem-corroborate)
1915
+ return sum(
1916
+ 1
1917
+ for m in choice.unready_lessons
1918
+ if (root is not None or m.scope != "project")
1919
+ and corroborate_decide.fill_wont_write(
1920
+ m, root if m.scope == "project" else None, attempts, today
1921
+ )
1922
+ )
1923
+
1924
+
1925
+ def _rules_unready_sentence(choice: rules.Choice, stuck: int) -> str:
1926
+ """The line about the established lessons that have no short form yet, and who writes it."""
1927
+ unready = f"{choice.unready} established lesson{' has' if choice.unready == 1 else 's have'} no short form yet"
1928
+ if common._rules_off():
1929
+ return unready + "."
1930
+ if stuck == choice.unready:
1931
+ return (
1932
+ unready
1933
+ + ": the automatic fill will not write "
1934
+ + f"{'it, so it needs' if stuck == 1 else 'them, so they need'} curation (mem curate)."
1935
+ )
1936
+ if stuck:
1937
+ return (
1938
+ unready
1939
+ + f": {stuck} need{'s' if stuck == 1 else ''} curation (mem curate), the background pass writes the "
1940
+ + f"{'other' if choice.unready - stuck == 1 else 'others'} when auto_capture is on (mem-corroborate status shows the last one)."
1941
+ )
1942
+ return (
1943
+ unready
1944
+ + ": the background pass writes them when auto_capture is on (mem-corroborate status shows the last one)."
1945
+ )
1946
+
1947
+
1948
+ def _rules_more_line(m: records.Memory, why: str) -> str:
1949
+ """One row of `mem rules --more`: a lesson that was left out, and why."""
1950
+ claim = _flat(m.claim)
1951
+ claim = (
1952
+ claim
1953
+ if len(claim) <= _CLAIM_PREVIEW_CHARS
1954
+ else claim[: _CLAIM_PREVIEW_CHARS - 1] + "\u2026"
1955
+ )
1956
+ return f"m:{m.handle}\t{m.scope}\t{why}\t{rules.standing_words(m)}\t{m.topic or '-'}\t{claim}\t{records.mark_words(m) or '-'}"
1957
+
1958
+
1959
+ def _rules_more(more: str | bool, choice: rules.Choice, unready: str) -> int:
1960
+ """`mem rules --more [topic]`: list the lessons left out of the loaded rules (all, or one topic)."""
1961
+ topic = None if more is True else more
1962
+ shown = [
1963
+ (m, why)
1964
+ for m, why in choice.left
1965
+ if topic is None or (m.topic or "other") == topic or (topic == "other" and not m.topic)
1966
+ ]
1967
+ order = [t for t, _ in rules.topic_counts(choice)] + [None]
1968
+ for group in order:
1969
+ for m, why in (x for x in shown if x[0].topic == group):
1970
+ print(_rules_more_line(m, why))
1971
+ if shown:
1972
+ print("mem show m:<handle> prints a whole lesson.")
1973
+ else:
1974
+ print("No lessons left out" + (f" under {topic}." if topic else "."))
1975
+ if choice.unready:
1976
+ print(unready)
1977
+ return 0
1978
+
1979
+
1980
+ def _rules_print(
1981
+ args: argparse.Namespace,
1982
+ choice: rules.Choice,
1983
+ global_: list[records.Memory],
1984
+ today: datetime.date,
1985
+ unready: str,
1986
+ ) -> int:
1987
+ """Print the rules block, the index lines and the lessons that failed after they loaded."""
1988
+ digest_data, topics = common._rules_digest(global_, today)
1989
+ lines = rules.block(
1990
+ choice, common._rules_layout(args.layout), digest=digest_data, topics=topics
1991
+ )
1992
+ print("\n".join(lines) if lines else "No rules loaded.")
1993
+ index = rules.index_lines(choice, digest=digest_data, topics=topics)
1994
+ if index: # also alone: index-only lessons are reachable when no rule loads
1995
+ print("\n".join(index))
1996
+ if not lines and choice.unready:
1997
+ print(unready)
1998
+ failed = [
1999
+ (m, words)
2000
+ for m in [*choice.loaded, *(m for m, why in choice.left if why == rules.OVER)]
2001
+ if (words := records.mark_words(m))
2002
+ ]
2003
+ if failed:
2004
+ print("Failed after it loaded:")
2005
+ for m, words in failed:
2006
+ print(f"m:{m.handle}\t{words}")
2007
+ return 0
2008
+
2009
+
2010
+ def cmd_rules(args: argparse.Namespace) -> int:
2011
+ """Print the rules block and the line after it exactly as session start does; --more lists what was left out."""
2012
+ today = datetime.date.today()
2013
+ if args.unread or args.read:
2014
+ return _rules_unread(args, today)
2015
+ (_, _, project), (_, _, global_) = _loaded(common._memory_folders(args))
2016
+ try:
2017
+ root = records.project_root(Path.cwd(), os.environ)
2018
+ except OSError:
2019
+ root = None
2020
+ project = records.mark_repository(
2021
+ project, records.tracked_memories(root) if root else frozenset()
2022
+ )
2023
+ choice = rules.choose(project, global_, today)
2024
+ if common._rules_off():
2025
+ print(RULES_OFF_NOTICE)
2026
+ stuck = _rules_stuck(choice, root, common._fill_attempts(os.environ), today)
2027
+ unready = _rules_unready_sentence(choice, stuck)
2028
+ if args.more is not None:
2029
+ return _rules_more(args.more, choice, unready)
2030
+ return _rules_print(args, choice, global_, today, unready)
2031
+
2032
+
2033
+ def _settle_actions() -> settle_verdicts.Actions:
2034
+ return settle_verdicts.Actions(_merge_pair, _supersede_pair, _distinct_pair)
2035
+
2036
+
2037
+ def _settle_reason_ok(reason: str) -> bool:
2038
+ return (
2039
+ not common._refuse_secret([reason]) and common._check_terms([reason], "lesson", False) == 0
2040
+ )
2041
+
2042
+
2043
+ def _settle_missing_folder(command: str) -> int:
2044
+ """The exit code of a settle subcommand when there is no global memories folder."""
2045
+ if command == "due":
2046
+ return 1
2047
+ if command in {"pending", "log"}:
2048
+ return 0
2049
+ print("mem: there is no global memories folder.", file=sys.stderr)
2050
+ return 2
2051
+
2052
+
2053
+ def _settle_due(args: argparse.Namespace, folder: Path, today: datetime.date) -> int:
2054
+ count = settle_verdicts.due(folder, args.minutes, time.time(), today)
2055
+ if count is None:
2056
+ return 1
2057
+ print(count)
2058
+ return 0
2059
+
2060
+
2061
+ def _settle_pending(args: argparse.Namespace, folder: Path, today: datetime.date) -> int:
2062
+ with settle_verdicts.locked(folder):
2063
+ state = settle_verdicts.load_state(folder)
2064
+ found = settle_verdicts.pending(
2065
+ records.load_memories(folder, "global"), state, today, tokenize=records.tokenize
2066
+ )
2067
+ settle_verdicts.offer(folder, state, found, time.time())
2068
+ if args.json:
2069
+ print(json.dumps(found, ensure_ascii=False, indent=1))
2070
+ else:
2071
+ for p in found:
2072
+ flagged = f" flagged: {', '.join(p['flagged_words'])}" if p["flagged_words"] else ""
2073
+ print(
2074
+ f"pair {p['pair']} newer: m:{p['newer']}{flagged}\n m:{p['a']}\t{p['claim_a']}\n "
2075
+ f"m:{p['b']}\t{p['claim_b']}"
2076
+ )
2077
+ return 0
2078
+
2079
+
2080
+ def _settle_apply(args: argparse.Namespace, folder: Path, today: datetime.date) -> int:
2081
+ try:
2082
+ rows = json.loads(Path(args.verdicts).read_text(encoding="utf-8"))
2083
+ except (OSError, ValueError) as exc:
2084
+ print(f"mem: cannot read the verdicts: {exc}", file=sys.stderr)
2085
+ return 2
2086
+ try:
2087
+ with settle_verdicts.locked(folder):
2088
+ lines = settle_verdicts.apply_verdicts(
2089
+ folder,
2090
+ records.load_memories(folder, "global"),
2091
+ rows,
2092
+ today,
2093
+ time.time(),
2094
+ actions=_settle_actions(),
2095
+ reason_ok=_settle_reason_ok,
2096
+ tokenize=records.tokenize,
2097
+ )
2098
+ except settle_verdicts.NoListing as exc:
2099
+ print("\n".join(exc.lines))
2100
+ print(f"mem: {exc}", file=sys.stderr)
2101
+ return 1
2102
+ print("\n".join(lines))
2103
+ return 0
2104
+
2105
+
2106
+ def _settle_log(args: argparse.Namespace, folder: Path, _today: datetime.date) -> int:
2107
+ out = settle_verdicts.listing(folder, args.all)
2108
+ if out:
2109
+ print("\n".join(out))
2110
+ return 0
2111
+
2112
+
2113
+ def _settle_ack(_args: argparse.Namespace, folder: Path, _today: datetime.date) -> int:
2114
+ print(f"acknowledged {settle_verdicts.ack(folder)}")
2115
+ return 0
2116
+
2117
+
2118
+ def _settle_undo(args: argparse.Namespace, folder: Path, today: datetime.date) -> int:
2119
+ try:
2120
+ with settle_verdicts.locked(folder):
2121
+ print("\n".join(settle_verdicts.undo(folder, args.number, today)))
2122
+ except settle_verdicts.NothingToUndo as exc:
2123
+ print(f"mem: {exc}", file=sys.stderr)
2124
+ return 1
2125
+ return 0
2126
+
2127
+
2128
+ _SETTLE_HANDLERS: dict[str, Callable[[argparse.Namespace, Path, datetime.date], int]] = {
2129
+ "due": _settle_due,
2130
+ "pending": _settle_pending,
2131
+ "apply": _settle_apply,
2132
+ "log": _settle_log,
2133
+ "ack": _settle_ack,
2134
+ } # any other subcommand is `undo`
2135
+
2136
+
2137
+ def cmd_settle(args: argparse.Namespace) -> int:
2138
+ """`mem settle`: the engine side of settling new global memories (see settle.py)."""
2139
+ store = common._optional_store(args)
2140
+ folder = records.memories_root(os.environ, store)
2141
+ command = args.settle_command
2142
+ if folder is None or not folder.is_dir():
2143
+ return _settle_missing_folder(command)
2144
+ if common._read_only_store(store, folder.resolve()):
2145
+ print(common._READ_ONLY_MEMORIES, file=sys.stderr)
2146
+ return 2
2147
+ today = datetime.date.today()
2148
+ try:
2149
+ return _SETTLE_HANDLERS.get(command, _settle_undo)(args, folder, today)
2150
+ except (OSError, ValueError, yaml.YAMLError) as exc:
2151
+ print(f"mem: {exc}", file=sys.stderr)
2152
+ return 2