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
memory_cli/mem.py ADDED
@@ -0,0 +1,1180 @@
1
+ #!/usr/bin/env -S uv run --script
2
+ # /// script
3
+ # requires-python = ">=3.12,<3.16" # an upper bound: a newer Python may have no prebuilt pyyaml yet
4
+ # dependencies = ["pyyaml"]
5
+ # ///
6
+ """Memory engine: parsing primitives and the mem commands."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import os
12
+ import sys
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ from memory_cli.commands import (
16
+ admin,
17
+ common,
18
+ curate,
19
+ edit,
20
+ hooks,
21
+ integrate,
22
+ memory,
23
+ read,
24
+ sources,
25
+ split,
26
+ synthesis,
27
+ )
28
+ from memory_cli.commands.diagnostics import add_parser as _parser_add_diagnostics
29
+ from memory_cli.commands.install import add_parser as _parser_add_install
30
+ from memory_cli.core import config, safe_io
31
+ from memory_cli.memories import records, rules
32
+ from memory_cli.notes import due as due_queries
33
+ from memory_cli.notes.fields import (
34
+ LEVELS,
35
+ )
36
+ from memory_cli.notes.index import (
37
+ INDEX_FOLDERS,
38
+ )
39
+ from memory_cli.syntheses import project as project_syntheses
40
+
41
+ if TYPE_CHECKING:
42
+ import datetime
43
+ from collections.abc import Mapping
44
+ from pathlib import Path
45
+
46
+
47
+ _WRITE_COMMANDS = ("new", "note", "rename", "unify", "index", "fetch-sources", "import")
48
+ _SYNTHESIS_WRITES = (
49
+ "new",
50
+ "add",
51
+ "edit",
52
+ "append",
53
+ "attach",
54
+ "rename",
55
+ "remove",
56
+ "detach",
57
+ "topics",
58
+ "refs",
59
+ )
60
+ _NO_STORE_NEEDED = (
61
+ "remember",
62
+ "observe",
63
+ "confirm",
64
+ "refute",
65
+ "supersede",
66
+ "merge",
67
+ "forget",
68
+ "promote",
69
+ "distinct",
70
+ "restore",
71
+ "triage",
72
+ "memory",
73
+ "memories",
74
+ "curate",
75
+ "settle",
76
+ "session-index",
77
+ "rules",
78
+ "compact-log",
79
+ "signal",
80
+ "projects",
81
+ "project-synthesis",
82
+ "install-command",
83
+ )
84
+
85
+
86
+ def store_source(cli_root: str | None, env: Mapping[str, str]) -> config.StoreSource | None:
87
+ """Where the store path comes from: --root, MEM_STORE, the config file or the default store."""
88
+ return config.store_source(cli_root, env)
89
+
90
+
91
+ # --- new -----------------------------------------------------------------------
92
+
93
+
94
+ DETAILS = ("paths", "titles", "facts", "snippet", "summary")
95
+
96
+
97
+ # --- rename --------------------------------------------------------------------
98
+
99
+
100
+ # --- unify ---------------------------------------------------------------------
101
+
102
+
103
+ # --- fetch-sources, import -----------------------------------------------------
104
+
105
+
106
+ # --- CLI ---------------------------------------------------------------------
107
+
108
+
109
+ # --- note edit -----------------------------------------------------------------
110
+
111
+
112
+ def _today(value: str) -> datetime.date:
113
+ if (date := due_queries._iso_date(value)) is None:
114
+ raise argparse.ArgumentTypeError("use a real date as YYYY-MM-DD")
115
+ return date
116
+
117
+
118
+ def _offset(value: str) -> int:
119
+ n = int(value)
120
+ if n < 0:
121
+ raise argparse.ArgumentTypeError("must be >= 0")
122
+ return n
123
+
124
+
125
+ def _limit(value: str) -> int:
126
+ n = int(value)
127
+ if n < 1:
128
+ raise argparse.ArgumentTypeError("must be >= 1")
129
+ return n
130
+
131
+
132
+ _KINDS = ("paper", "book", "article", "web", "talk", "repo", "dataset")
133
+ _CONFIDENCE = ("high", "medium", "low")
134
+ _ORIGINS = ("literature", "research", "experience")
135
+
136
+
137
+ _OWNER_APPROVED = "the owner agreed to a write that mentions a soft term: never add it on your own"
138
+
139
+
140
+ _USER_READ = (
141
+ "with --short: the owner read this text, so it skips the code check and carries no mark; "
142
+ "without it the short form is checked against the claim and marked as written by a model"
143
+ )
144
+
145
+
146
+ def _parser_add_search(sub: Any) -> None:
147
+ check_parser = sub.add_parser("check", help="validate the hub rules")
148
+ check_parser.add_argument(
149
+ "paths", nargs="*", metavar="PATH", help="print only problems in these notes or folders"
150
+ )
151
+ check_parser.set_defaults(func=read.cmd_check)
152
+ index_parser = sub.add_parser("index", help="regenerate the index blocks in the folder READMEs")
153
+ index_parser.set_defaults(func=read.cmd_index)
154
+ find_parser = sub.add_parser("find", help="list notes matching all filters")
155
+ search_parser = sub.add_parser("search", help="rank notes by BM25 relevance to a query")
156
+ search_parser.add_argument("query")
157
+ search_parser.add_argument("--limit", type=_limit, default=10)
158
+ search_parser.add_argument(
159
+ "--offset", type=_offset, default=0, help="skip the first N results (default: 0)"
160
+ )
161
+ search_parser.add_argument(
162
+ "--also",
163
+ action="append",
164
+ default=[],
165
+ metavar="QUERY",
166
+ help="another query over the same corpus (repeatable); each list is headed `== <query> ==`",
167
+ )
168
+ search_parser.add_argument(
169
+ "--links",
170
+ action="store_true",
171
+ help="also list up to 10 notes linked to or from the first 10 printed results",
172
+ )
173
+ search_parser.add_argument(
174
+ "--scope",
175
+ choices=("all", "notes", "memories"),
176
+ default="all",
177
+ help="what to search: notes and memories (default), only notes, only memories",
178
+ )
179
+ search_parser.add_argument(
180
+ "--deep",
181
+ action="store_true",
182
+ help="also rank source notes and investigations, and list syntheses "
183
+ "(default: knowledge notes and memories)",
184
+ )
185
+ search_parser.add_argument(
186
+ "--all-memories",
187
+ action="store_true",
188
+ help="also match refuted, superseded and expired memories",
189
+ )
190
+ search_parser.add_argument(
191
+ "--project",
192
+ action="append",
193
+ default=[],
194
+ metavar="NAME",
195
+ help="also search this registered project's memories (repeatable; see mem projects list)",
196
+ )
197
+ search_parser.add_argument(
198
+ "--all-projects",
199
+ action="store_true",
200
+ help="also search the memories of every registered project but the current one",
201
+ )
202
+ search_parser.set_defaults(func=read.cmd_search)
203
+ for filtered in (find_parser, search_parser):
204
+ filtered.add_argument("--type", choices=INDEX_FOLDERS)
205
+ filtered.add_argument("--topic")
206
+ filtered.add_argument("--kind", choices=_KINDS)
207
+ filtered.add_argument("--status", choices=("idea", "active", "paused", "done", "abandoned"))
208
+ filtered.add_argument("--confidence", choices=_CONFIDENCE)
209
+ filtered.add_argument("--level", choices=LEVELS)
210
+ filtered.add_argument(
211
+ "--superseded", action="store_true", help="also list notes that a unified note replaced"
212
+ )
213
+ filtered.add_argument(
214
+ "--handles",
215
+ action="store_true",
216
+ help="print a short handle in place of each path (accepted wherever a note is named)",
217
+ )
218
+ filtered.add_argument(
219
+ "--detail",
220
+ choices=DETAILS,
221
+ default="titles",
222
+ help="per result: path only, title, key facts, a matching line, or the lead section",
223
+ )
224
+ find_parser.add_argument(
225
+ "--limit", type=_limit, default=50, help="print at most N notes (default: 50)"
226
+ )
227
+ find_parser.add_argument(
228
+ "--offset", type=_offset, default=0, help="skip the first N notes (default: 0)"
229
+ )
230
+ find_parser.set_defaults(func=read.cmd_find)
231
+
232
+
233
+ def _parser_add_read(sub: Any) -> None:
234
+ passages_parser = sub.add_parser(
235
+ "passages", help="print the passages of a note's local source that best match"
236
+ )
237
+ passages_parser.add_argument("path", metavar="PATH")
238
+ passages_parser.add_argument("query")
239
+ passages_parser.add_argument(
240
+ "--count", type=_limit, default=5, help="passages to print (default: 5)"
241
+ )
242
+ passages_parser.add_argument(
243
+ "--words", type=_limit, default=500, help="words per passage (default: 500)"
244
+ )
245
+ passages_parser.set_defaults(func=read.cmd_passages)
246
+ related_parser = sub.add_parser(
247
+ "related", help="list a note's links, backlinks and most similar notes"
248
+ )
249
+ related_parser.add_argument("path", metavar="PATH")
250
+ related_parser.add_argument(
251
+ "--limit", type=_limit, default=5, help="print at most N similar notes (default: 5)"
252
+ )
253
+ related_parser.add_argument(
254
+ "--detail",
255
+ choices=DETAILS,
256
+ default="titles",
257
+ help="per result: path only, title, key facts, a matching line, or the lead section",
258
+ )
259
+ related_parser.add_argument(
260
+ "--superseded", action="store_true", help="also list notes that a unified note replaced"
261
+ )
262
+ related_parser.add_argument(
263
+ "--unlinked-mentions",
264
+ action="store_true",
265
+ help="print only the notes that name this one in their text without linking to it",
266
+ )
267
+ related_parser.set_defaults(func=read.cmd_related)
268
+ show_parser = sub.add_parser("show", aliases=["read"], help="print chosen sections of notes")
269
+ show_parser.add_argument("paths", nargs="+", metavar="PATH")
270
+ show_parser.add_argument(
271
+ "--section", action="append", help="a `## ` section to print (repeatable)"
272
+ )
273
+ show_parser.add_argument(
274
+ "--outline", action="store_true", help="list headings with line numbers"
275
+ )
276
+ show_parser.add_argument(
277
+ "--ranges",
278
+ action="store_true",
279
+ help="with --outline: print start-end lines and word count per heading",
280
+ )
281
+ show_parser.add_argument(
282
+ "--all", action="store_true", help="a synthesis: print the whole file, not its outline"
283
+ )
284
+ show_parser.add_argument(
285
+ "--project", metavar="NAME", help="read a memory of this registered project"
286
+ )
287
+ show_parser.add_argument(
288
+ "--stored",
289
+ action="store_true",
290
+ help="a synthesis: print each reference as stored, not as `[n]`, the place of its note on the `Sources:` line",
291
+ )
292
+ show_parser.set_defaults(func=read.cmd_show)
293
+ topics_parser = sub.add_parser("topics", help="print the topic tree with note counts")
294
+ topics_parser.add_argument(
295
+ "topic", nargs="?", metavar="ID", help="print only this topic's subtree"
296
+ )
297
+ topics_parser.set_defaults(func=read.cmd_topics)
298
+ stats_parser = sub.add_parser("stats", help="print note, topic and size counts")
299
+ stats_parser.add_argument(
300
+ "--orphans", action="store_true", help="list notes no other file links to"
301
+ )
302
+ stats_parser.add_argument(
303
+ "paths", nargs="*", metavar="PATH", help="with --orphans: only these notes or folders"
304
+ )
305
+ stats_parser.set_defaults(func=read.cmd_stats)
306
+ review_parser = sub.add_parser(
307
+ "review",
308
+ help="list concrete requirements due for review and notes due for re-testing or re-reading",
309
+ )
310
+ review_parser.add_argument(
311
+ "--today", type=_today, default=None, help="YYYY-MM-DD (default: today)"
312
+ )
313
+ review_parser.set_defaults(func=read.cmd_review)
314
+
315
+
316
+ def _parser_add_sources(sub: Any) -> None:
317
+ fetch_parser = sub.add_parser(
318
+ "fetch-sources", help="download literature note urls into .sources/"
319
+ )
320
+ fetch_parser.add_argument("paths", nargs="*", metavar="PATH")
321
+ fetch_parser.add_argument("--force", action="store_true", help="refetch notes already cached")
322
+ fetch_parser.add_argument(
323
+ "--text-only",
324
+ action="store_true",
325
+ help="no download: write source.txt in cached folders that hold no .txt",
326
+ )
327
+ fetch_parser.set_defaults(func=sources.cmd_fetch_sources)
328
+ eval_parser = sub.add_parser("search-eval", help="measure search recall on docs/search-eval.md")
329
+ eval_parser.add_argument(
330
+ "--min",
331
+ type=float,
332
+ help="exit 1 when recall@10 is below this (replaces the default revisit triggers)",
333
+ )
334
+ eval_parser.set_defaults(func=read.cmd_search_eval)
335
+ rename_parser = sub.add_parser(
336
+ "rename", help="rename a note in its folder and rewrite the links to it"
337
+ )
338
+ rename_parser.add_argument("note", metavar="NOTE")
339
+ rename_parser.add_argument("new_stem", metavar="NEW-STEM", help="the new file name without .md")
340
+ rename_parser.set_defaults(func=edit.cmd_rename)
341
+
342
+
343
+ def _parser_add_note(sub: Any) -> None:
344
+ note_parser = sub.add_parser(
345
+ "note", help="change a note through mem, never by editing its file"
346
+ )
347
+ note_sub = note_parser.add_subparsers(dest="note_command", required=True)
348
+ note_edit = note_sub.add_parser(
349
+ "edit", help="replace the text of one section, the claim or the topics of a note"
350
+ )
351
+ note_edit.add_argument("note", metavar="NOTE", help="a path or a handle, as in mem show")
352
+ note_edit.add_argument(
353
+ "--section", metavar="HEADING", help="the `## ` heading whose text is replaced"
354
+ )
355
+ note_edit.add_argument(
356
+ "--body-file", metavar="PATH", help="the new section text; - reads standard input"
357
+ )
358
+ note_edit.add_argument(
359
+ "--claim", metavar="TEXT", help="the new frontmatter claim (one sentence)"
360
+ )
361
+ note_edit.add_argument(
362
+ "--topics", metavar="A,B", help="the new topic ids: in topics.yaml, in the note's domain"
363
+ )
364
+ note_edit.add_argument(
365
+ "--shrink",
366
+ action="store_true",
367
+ help="accept a text that drops over 20%% of the words, a sentence or a link",
368
+ )
369
+ note_edit.add_argument("--owner-approved", action="store_true", help=_OWNER_APPROVED)
370
+ note_parser.set_defaults(func=edit.cmd_note)
371
+ for verb, what in (
372
+ ("confirm", "append a source-confirmed line to the note's Evidence section"),
373
+ ("dispute", "mark the note as contradicted by a source (the claim stays as it is)"),
374
+ ):
375
+ marked = note_sub.add_parser(verb, help=what)
376
+ marked.add_argument(
377
+ "note", metavar="NOTE", help="a path or a handle of a knowledge note, as in mem show"
378
+ )
379
+ marked.add_argument("--fact", metavar="TEXT", help="what the source says about the claim")
380
+ marked.add_argument("--source", metavar="URL", help="the http(s) URL of the page")
381
+ marked.add_argument("--quote", metavar="TEXT", help="the words of the page that show it")
382
+ if verb == "dispute":
383
+ marked.add_argument(
384
+ "--clear", action="store_true", help="remove the mark: the owner settled it"
385
+ )
386
+ marked.add_argument("--owner-approved", action="store_true", help=_OWNER_APPROVED)
387
+ marked.set_defaults(func=edit.cmd_note_mark)
388
+
389
+
390
+ def _parser_add_import(sub: Any) -> None:
391
+ import_parser = sub.add_parser(
392
+ "import",
393
+ help="copy the notes of another folder of notes into the store; the source is never changed",
394
+ )
395
+ import_parser.add_argument(
396
+ "source",
397
+ metavar="SOURCE",
398
+ help="the folder to read (literature/, knowledge/, research/, topics.yaml)",
399
+ )
400
+ import_parser.add_argument(
401
+ "--dry-run", action="store_true", help="change nothing; print the report a real run would"
402
+ )
403
+ import_parser.add_argument(
404
+ "--overwrite",
405
+ action="store_true",
406
+ help="replace files that differ (the old text goes to the curation log)",
407
+ )
408
+ import_parser.add_argument(
409
+ "--with-sources", action="store_true", help="also copy the source's .sources/ folder"
410
+ )
411
+ import_parser.add_argument(
412
+ "--research-data",
413
+ action="store_true",
414
+ help="also copy the data and code under research/ (by default only its Markdown files)",
415
+ )
416
+ import_parser.set_defaults(func=sources.cmd_import)
417
+ recover = sub.add_parser("import-recover", help="roll back an interrupted import")
418
+ recover.set_defaults(func=sources.cmd_import_recover)
419
+ unify_parser = sub.add_parser(
420
+ "unify",
421
+ help="replace several notes of one type with one, keeping the others as "
422
+ "superseded files and pointing their links at it",
423
+ )
424
+ unify_parser.add_argument("keep", metavar="KEEP", help="the note that takes the unified text")
425
+ unify_parser.add_argument("others", nargs="+", metavar="OTHER", help="notes that KEEP replaces")
426
+ unify_parser.add_argument(
427
+ "--body-file",
428
+ required=True,
429
+ metavar="PATH",
430
+ help="the unified body (after the frontmatter); - reads standard input",
431
+ )
432
+ unify_parser.add_argument("--owner-approved", action="store_true", help=_OWNER_APPROVED)
433
+ unify_parser.add_argument(
434
+ "--drop", action="store_true", help="accept a unified text that lacks a link the notes had"
435
+ )
436
+ unify_parser.set_defaults(func=edit.cmd_unify)
437
+
438
+
439
+ def _parser_add_new(sub: Any) -> None:
440
+ new_parser = sub.add_parser("new", help="create a note from its template")
441
+ new_sub = new_parser.add_subparsers(dest="type", required=True)
442
+ for note_type, flags in {
443
+ "literature": {
444
+ "title": {},
445
+ "author": {},
446
+ "year": {"type": int},
447
+ "kind": {"choices": _KINDS},
448
+ "level": {"choices": LEVELS},
449
+ "url": {},
450
+ "topics": {},
451
+ "slug": {},
452
+ },
453
+ "knowledge": {
454
+ "slug": {},
455
+ "claim": {},
456
+ "topics": {},
457
+ "confidence": {"choices": _CONFIDENCE},
458
+ "level": {"choices": LEVELS},
459
+ "origin": {"choices": _ORIGINS},
460
+ },
461
+ "research": {"slug": {}, "title": {}, "question": {}, "topics": {}},
462
+ }.items():
463
+ type_parser = new_sub.add_parser(note_type)
464
+ type_parser.add_argument(
465
+ "--body-file",
466
+ metavar="PATH",
467
+ help="text (or - for standard input) that replaces the template body",
468
+ )
469
+ for flag, opts in flags.items():
470
+ type_parser.add_argument(f"--{flag}", required=True, **opts)
471
+ if note_type == "knowledge":
472
+ type_parser.add_argument(
473
+ "--part-of",
474
+ metavar="s:HANDLE#SECTION",
475
+ help="the synthesis section this note summarizes",
476
+ )
477
+ type_parser.add_argument("--owner-approved", action="store_true", help=_OWNER_APPROVED)
478
+ type_parser.set_defaults(func=edit.cmd_new)
479
+
480
+
481
+ def _parser_add_remember(sub: Any) -> None:
482
+ remember_parser = sub.add_parser(
483
+ "remember", help="write a memory in the project or, with --global, in the global folder"
484
+ )
485
+ remember_parser.add_argument("--kind", required=True, choices=records.KINDS)
486
+ remember_parser.add_argument("--claim", required=True)
487
+ remember_parser.add_argument(
488
+ "--body-file", metavar="PATH", help="text (or - for standard input); may be empty"
489
+ )
490
+ remember_parser.add_argument("--context")
491
+ remember_parser.add_argument(
492
+ "--short",
493
+ metavar="TEXT",
494
+ help="the claim as one line of at most 120 characters, loaded at session start",
495
+ )
496
+ remember_parser.add_argument("--user-read", action="store_true", help=_USER_READ)
497
+ remember_parser.add_argument(
498
+ "--topic", metavar="TEXT", help="one or two lowercase words that group rules"
499
+ )
500
+ remember_parser.add_argument("--valid-until", type=_today, default=None, metavar="YYYY-MM-DD")
501
+ remember_parser.add_argument("--source", action="append", default=[], metavar="URL_OR_PATH")
502
+ remember_parser.add_argument(
503
+ "--origin",
504
+ choices=records.ORIGINS,
505
+ help="where the claim came from when not a session: web (a finding), pipeline (a pipeline's write) "
506
+ "or transcript (a lesson captured from a session transcript)",
507
+ )
508
+ remember_parser.add_argument(
509
+ "--reach", choices=records.REACHES, help="how far the lesson reaches"
510
+ )
511
+ remember_parser.add_argument(
512
+ "--weight",
513
+ choices=records.WEIGHTS,
514
+ help="how much it weighs: light needs 1 session to be established, medium 2, strong 3",
515
+ )
516
+ remember_parser.add_argument(
517
+ "--outcome",
518
+ choices=records.OUTCOMES,
519
+ help="what the session showed about the lesson; recorded as a case of its log",
520
+ )
521
+ remember_parser.add_argument(
522
+ "--seen-on",
523
+ type=_today,
524
+ default=None,
525
+ metavar="YYYY-MM-DD",
526
+ help="the day of the session, when it is not today",
527
+ )
528
+ remember_parser.add_argument("--global", dest="is_global", action="store_true")
529
+ remember_parser.add_argument(
530
+ "--force", action="store_true", help="write even when a memory has the same claim"
531
+ )
532
+ remember_parser.add_argument("--owner-approved", action="store_true", help=_OWNER_APPROVED)
533
+ remember_parser.set_defaults(func=memory.cmd_remember)
534
+
535
+
536
+ def _parser_add_hooks(sub: Any) -> None:
537
+ index_cmd = sub.add_parser(
538
+ "session-index", help="print the text that opens a session: usage rules and counts"
539
+ )
540
+ index_cmd.add_argument(
541
+ "--hook",
542
+ action="store_true",
543
+ help="read the hook's JSON from standard input (its cwd locates the project) and log the call",
544
+ )
545
+ index_cmd.add_argument(
546
+ "--list",
547
+ type=int,
548
+ default=0,
549
+ metavar="N",
550
+ help="also list up to N of the project's newest memories",
551
+ )
552
+ index_cmd.set_defaults(func=hooks.cmd_session_index)
553
+ compact_cmd = sub.add_parser(
554
+ "compact-log", help="check the handoff block of a compaction summary and log counts"
555
+ )
556
+ compact_cmd.add_argument(
557
+ "--hook", action="store_true", help="read the hook's JSON from standard input"
558
+ )
559
+ compact_cmd.set_defaults(func=hooks.cmd_compact_log)
560
+ signal_cmd = sub.add_parser(
561
+ "signal", help="print the records related to a brief read from standard input"
562
+ )
563
+ signal_cmd.add_argument(
564
+ "--hook",
565
+ action="store_true",
566
+ help="read a PreToolUse hook's JSON from standard input and print the brief with the signal appended",
567
+ )
568
+ signal_cmd.set_defaults(func=hooks.cmd_signal)
569
+
570
+
571
+ def _parser_memory_command(
572
+ sub: Any, name: str, help_text: str, *handles: str, because: bool = False
573
+ ) -> argparse.ArgumentParser:
574
+ cmd = sub.add_parser(name, help=help_text)
575
+ for h in handles:
576
+ cmd.add_argument(h, metavar="m:HANDLE")
577
+ if because:
578
+ cmd.add_argument(
579
+ "--because", metavar="TEXT", help="the reason, appended to the memory's body"
580
+ )
581
+ cmd.add_argument("--owner-approved", action="store_true", help=_OWNER_APPROVED)
582
+ cmd.add_argument(
583
+ "--global",
584
+ dest="is_global",
585
+ action="store_true",
586
+ help="act on the global memory when the handle exists in both scopes",
587
+ )
588
+ return cmd
589
+
590
+
591
+ def _parser_add_memory_marks(sub: Any) -> None:
592
+ for name, text in (
593
+ ("confirm", "count one more observation of a memory"),
594
+ ("observe", "alias of confirm"),
595
+ ):
596
+ confirm_parser = _parser_memory_command(sub, name, text, "handle")
597
+ confirm_parser.add_argument(
598
+ "--until", metavar="YYYY-MM-DD", help="also set valid_until to this date"
599
+ )
600
+ confirm_parser.add_argument(
601
+ "--source",
602
+ metavar="'session ID'",
603
+ help="another session shows it: add it as a source (exit 3 when already one)",
604
+ )
605
+ confirm_parser.add_argument(
606
+ "--note", metavar="TEXT", help="with --source: a line added to the body"
607
+ )
608
+ confirm_parser.add_argument(
609
+ "--outcome",
610
+ choices=records.OUTCOMES,
611
+ help="with --source: what that session showed about the lesson (default seen)",
612
+ )
613
+ confirm_parser.add_argument(
614
+ "--seen-on",
615
+ type=_today,
616
+ default=None,
617
+ metavar="YYYY-MM-DD",
618
+ help="with --source: the day of that session (default today)",
619
+ )
620
+ confirm_parser.add_argument(
621
+ "--by-owner",
622
+ action="store_true",
623
+ help="the owner vouches for a transcript lesson: it is established (exit 3 when already)",
624
+ )
625
+ confirm_parser.set_defaults(func=memory.cmd_confirm)
626
+ _parser_memory_command(
627
+ sub, "refute", "mark a memory refuted", "handle", because=True
628
+ ).set_defaults(func=memory.cmd_refute)
629
+ _parser_memory_command(
630
+ sub, "forget", "mark a memory forgotten", "handle", because=True
631
+ ).set_defaults(func=memory.cmd_forget)
632
+
633
+
634
+ def _parser_add_triage(sub: Any) -> None:
635
+ triage_parser = sub.add_parser(
636
+ "triage",
637
+ help="decide what a corroborated general lesson becomes",
638
+ description="Triage is deciding what a corroborated general lesson becomes: one seen in two projects leaves "
639
+ "quarantine and waits here (mem curate --global lists it).",
640
+ )
641
+ triage_sub = triage_parser.add_subparsers(dest="triage_command", required=True)
642
+ triage_hold = triage_sub.add_parser(
643
+ "hold",
644
+ help="keep a general lesson out of the rules until the owner decides",
645
+ description="Hold: a global lesson is set to await triage, with the reason, and stops loading as a rule.",
646
+ )
647
+ triage_hold.add_argument("handle", metavar="m:HANDLE")
648
+ triage_hold.add_argument(
649
+ "--because", metavar="TEXT", help="why it is held (one line, at most 200 characters)"
650
+ )
651
+ for verb, text in (
652
+ (
653
+ "accept",
654
+ "a general lesson that awaits triage stays a general lesson every project may read",
655
+ ),
656
+ (
657
+ "reject",
658
+ (
659
+ "a general lesson that awaits triage is retired (mem restore brings it back), and "
660
+ "its project records are marked so they are not promoted again"
661
+ ),
662
+ ),
663
+ ):
664
+ triage_verb = triage_sub.add_parser(
665
+ verb, help=text, description=f"{verb.capitalize()}: {text}."
666
+ )
667
+ triage_verb.add_argument("handle", metavar="m:HANDLE")
668
+ if verb == "accept":
669
+ triage_verb.add_argument(
670
+ "--project-scope",
671
+ dest="project_scope",
672
+ action="store_true",
673
+ help="keep the wording of a project lesson that got worse",
674
+ )
675
+ triage_parser.set_defaults(func=memory.cmd_triage)
676
+
677
+
678
+ def _parser_add_memory_pairs(sub: Any) -> None:
679
+ _parser_memory_command(
680
+ sub, "supersede", "mark OLD as superseded by NEW", "old", "new"
681
+ ).set_defaults(func=memory.cmd_supersede)
682
+ merge_parser = _parser_memory_command(
683
+ sub, "merge", "add DROP's count and body to KEEP and supersede DROP", "keep", "drop"
684
+ )
685
+ merge_parser.add_argument(
686
+ "--force",
687
+ action="store_true",
688
+ help="merge although the claims differ by a negation or a number",
689
+ )
690
+ merge_parser.set_defaults(func=memory.cmd_merge)
691
+ _parser_memory_command(
692
+ sub,
693
+ "distinct",
694
+ "record that two memories are different claims: the queue stops pairing them",
695
+ "a",
696
+ "b",
697
+ ).set_defaults(func=memory.cmd_distinct)
698
+ _parser_memory_command(
699
+ sub, "restore", "put back the text a memory had before its last curation action", "handle"
700
+ ).set_defaults(func=memory.cmd_restore)
701
+ promote_parser = sub.add_parser(
702
+ "promote", help="print a draft of a global memory from project memories"
703
+ )
704
+ promote_parser.add_argument(
705
+ "--no", action="store_true", help="record that the memory is not for a global note"
706
+ )
707
+ promote_parser.add_argument(
708
+ "--done", action="store_true", help="record that the memory was promoted"
709
+ )
710
+ promote_parser.add_argument(
711
+ "--to", metavar="m:HANDLE", help="with --done: the global memory it was promoted to"
712
+ )
713
+ promote_parser.add_argument("handles", nargs="+", metavar="m:HANDLE")
714
+ promote_parser.set_defaults(func=memory.cmd_promote)
715
+
716
+
717
+ def _parser_add_memories(sub: Any) -> None:
718
+ memories_parser = sub.add_parser("memories", help="list memories, newest first")
719
+ curate_parser = sub.add_parser(
720
+ "curate", help="list what needs a decision: pairs, expired, frequent, unconfirmed"
721
+ )
722
+ scope_group = memories_parser.add_mutually_exclusive_group()
723
+ scope_group.add_argument(
724
+ "--global", dest="is_global", action="store_true", help="the global memories only"
725
+ )
726
+ scope_group.add_argument("--all", action="store_true", help="project and global memories")
727
+ scope_group.add_argument(
728
+ "--project", metavar="NAME", help="the memories of this registered project"
729
+ )
730
+ curate_scope = curate_parser.add_mutually_exclusive_group()
731
+ curate_scope.add_argument(
732
+ "--project", dest="is_project", action="store_true", help="the project's memories only"
733
+ )
734
+ curate_scope.add_argument(
735
+ "--global", dest="is_global", action="store_true", help="the global memories only"
736
+ )
737
+ memory.add_memories_arguments(memories_parser)
738
+ memories_parser.set_defaults(func=memory.cmd_memories)
739
+ rules_parser = sub.add_parser(
740
+ "rules", help="print the rules that load at session start; --more lists the rest"
741
+ )
742
+ rules_parser.add_argument(
743
+ "--more",
744
+ nargs="?",
745
+ const=True,
746
+ default=None,
747
+ metavar="TOPIC",
748
+ help="the lessons left out, grouped by topic; with TOPIC only that group (other: no topic)",
749
+ )
750
+ rules_parser.add_argument(
751
+ "--layout",
752
+ choices=rules.LAYOUTS,
753
+ help="print the lessons flat or under a heading per topic (default: MEM_RULES_LAYOUT, else flat)",
754
+ )
755
+ rules_parser.add_argument(
756
+ "--unread",
757
+ action="store_true",
758
+ help="list the short forms a model wrote that nobody read, with their claims",
759
+ )
760
+ rules_parser.add_argument(
761
+ "--read",
762
+ nargs="+",
763
+ metavar="HANDLE",
764
+ help="mark short forms as read: the handles, or all of those --unread lists",
765
+ )
766
+ rules_parser.set_defaults(func=memory.cmd_rules)
767
+ curate_parser.add_argument(
768
+ "--notes",
769
+ action="store_true",
770
+ help="list notes to attach to a synthesis part, and notes older than their part",
771
+ )
772
+ curate_parser.add_argument(
773
+ "--done",
774
+ action="store_true",
775
+ help="record today as the date of the last pass over the scopes covered",
776
+ )
777
+ curate_parser.add_argument(
778
+ "--new-since",
779
+ type=float,
780
+ metavar="EPOCH",
781
+ help="print the number of global memories and notes written since EPOCH seconds (and since the last pass)",
782
+ )
783
+ curate_parser.add_argument(
784
+ "action",
785
+ nargs="?",
786
+ choices=["apply"],
787
+ help="apply: carry out the safe actions read from --from FILE or stdin (needs --safe)",
788
+ )
789
+ curate_parser.add_argument(
790
+ "--safe",
791
+ action="store_true",
792
+ help="with apply: only merges of equal claims and attaches the part's Sources line backs",
793
+ )
794
+ curate_parser.add_argument(
795
+ "--from",
796
+ dest="from_file",
797
+ metavar="FILE",
798
+ help="with apply: the action lines (default or -: stdin)",
799
+ )
800
+ curate_parser.set_defaults(func=curate.cmd_curate)
801
+
802
+
803
+ def _parser_add_settle(sub: Any) -> None:
804
+ settle_parser = sub.add_parser(
805
+ "settle", help="settle new global memories against their look-alikes (verdicts from a file)"
806
+ )
807
+ settle_sub = settle_parser.add_subparsers(dest="settle_command", required=True)
808
+ settle_pending = settle_sub.add_parser(
809
+ "pending", help="list the look-alike pairs with a not yet judged side"
810
+ )
811
+ settle_pending.add_argument(
812
+ "--json",
813
+ action="store_true",
814
+ help="a JSON list: pair, a, b, claim_a, claim_b, newer, flagged_words",
815
+ )
816
+ settle_apply = settle_sub.add_parser(
817
+ "apply", help="carry out the verdicts the rules allow; refused rows are printed"
818
+ )
819
+ settle_apply.add_argument(
820
+ "--verdicts",
821
+ required=True,
822
+ metavar="FILE",
823
+ help='JSON list of {"a", "b", "decision": merge|supersede|distinct|nothing, "reason"}',
824
+ )
825
+ settle_log = settle_sub.add_parser("log", help="list the settlings not yet acknowledged")
826
+ settle_log.add_argument(
827
+ "--all", action="store_true", help="every settling, acknowledged and undone ones too"
828
+ )
829
+ settle_sub.add_parser("ack", help="mark every settling acknowledged")
830
+ settle_undo = settle_sub.add_parser(
831
+ "undo", help="undo settling N: both records back as they were"
832
+ )
833
+ settle_undo.add_argument("number", type=int, metavar="N")
834
+ settle_due = settle_sub.add_parser(
835
+ "due",
836
+ help="exit 0 and print the count when new memories wait and the last apply is older than M minutes",
837
+ )
838
+ settle_due.add_argument("--minutes", type=float, required=True, metavar="M")
839
+ settle_parser.set_defaults(func=memory.cmd_settle)
840
+
841
+
842
+ def _parser_add_project_synthesis(sub: Any) -> None:
843
+ ps_parser = sub.add_parser(
844
+ "project-synthesis",
845
+ help="write, confirm and list the stamped parts of a project's syntheses",
846
+ )
847
+ ps_sub = ps_parser.add_subparsers(dest="ps_command", required=True)
848
+ ps_add = ps_sub.add_parser(
849
+ "add", help="write a part, or replace the one with the same heading; prints p:NAME#HANDLE"
850
+ )
851
+ ps_add.add_argument(
852
+ "name", metavar="NAME", help="one of: " + ", ".join(project_syntheses.NAMES)
853
+ )
854
+ ps_add.add_argument("heading")
855
+ ps_add.add_argument(
856
+ "--paths", required=True, metavar="A,B", help="the project files or folders the part covers"
857
+ )
858
+ ps_add.add_argument(
859
+ "--body-file", required=True, metavar="PATH", help="the text (or - for standard input)"
860
+ )
861
+ ps_confirm = ps_sub.add_parser("confirm", help="stamp a part as checked today, text unchanged")
862
+ ps_confirm.add_argument("part", metavar="p:NAME#HANDLE")
863
+ ps_sub.add_parser("list", help="one line per part: handle, freshness, heading")
864
+ ps_parser.set_defaults(func=synthesis.cmd_project_synthesis)
865
+
866
+
867
+ def _parser_synthesis_write(synthesis_sub: Any) -> None:
868
+ syn_new = synthesis_sub.add_parser("new", help="create syntheses/<slug>.md with its summary")
869
+ syn_new.add_argument("--title", required=True)
870
+ syn_new.add_argument("--topics", required=True, help="comma-separated topic ids")
871
+ syn_new.add_argument("--slug", required=True)
872
+ syn_new.add_argument(
873
+ "--summary-file", metavar="PATH", help="the summary (or - for standard input)"
874
+ )
875
+ syn_add = synthesis_sub.add_parser(
876
+ "add", help="append one section; its text must end with a `Sources:` line"
877
+ )
878
+ syn_add.add_argument("target", metavar="s:HANDLE")
879
+ syn_add.add_argument("--section", required=True, metavar="HEADING")
880
+ syn_add.add_argument(
881
+ "--body-file", required=True, metavar="PATH", help="the text (or - for standard input)"
882
+ )
883
+ syn_add.add_argument(
884
+ "--note-slug",
885
+ metavar="SLUG",
886
+ help="also write a knowledge note that summarizes the section",
887
+ )
888
+ syn_add.add_argument("--note-claim", metavar="TEXT")
889
+ syn_add.add_argument(
890
+ "--note-body-file", metavar="PATH", help="the note's body (or - for standard input)"
891
+ )
892
+ syn_add.add_argument("--confidence", choices=_CONFIDENCE)
893
+ syn_add.add_argument("--level", choices=LEVELS)
894
+ syn_add.add_argument(
895
+ "--origin", choices=_ORIGINS, help="default: taken from the section's Sources line"
896
+ )
897
+ syn_edit = synthesis_sub.add_parser(
898
+ "edit", help="replace the text of one section; the rest of the file stays"
899
+ )
900
+ syn_edit.add_argument("target", metavar="s:HANDLE#SECTION")
901
+ syn_edit.add_argument(
902
+ "--body-file", required=True, metavar="PATH", help="the text (or - for standard input)"
903
+ )
904
+ syn_edit.add_argument(
905
+ "--shrink", action="store_true", help="allow a text with fewer words or links than before"
906
+ )
907
+ syn_edit.add_argument(
908
+ "--drop-references",
909
+ action="store_true",
910
+ help="allow a sentence kept unchanged to lose a reference (a note link in its body)",
911
+ )
912
+ syn_new.add_argument("--owner-approved", action="store_true", help=_OWNER_APPROVED)
913
+ syn_add.add_argument("--owner-approved", action="store_true", help=_OWNER_APPROVED)
914
+ syn_edit.add_argument("--owner-approved", action="store_true", help=_OWNER_APPROVED)
915
+
916
+
917
+ def _parser_add_synthesis(sub: Any) -> None:
918
+ synthesis_parser = sub.add_parser(
919
+ "synthesis", help="create and extend syntheses, the long documents behind notes"
920
+ )
921
+ synthesis_sub = synthesis_parser.add_subparsers(dest="synthesis_command", required=True)
922
+ _parser_synthesis_write(synthesis_sub)
923
+ synthesis.parser_sections(synthesis_sub, _OWNER_APPROVED)
924
+ synthesis.parser_links(synthesis_sub)
925
+ integrate.register(synthesis_sub)
926
+ split.register(synthesis_sub)
927
+ synthesis_parser.set_defaults(func=synthesis.cmd_synthesis)
928
+
929
+
930
+ def _parser_add_registry(sub: Any) -> None:
931
+ terms_parser = sub.add_parser(
932
+ "terms", help="manage the terms that must not reach the global scope"
933
+ )
934
+ terms_sub = terms_parser.add_subparsers(dest="terms_command", required=True)
935
+ terms_sub.add_parser("list", help="print hard<TAB>term and soft<TAB>term lines")
936
+ terms_add = terms_sub.add_parser("add", help="add a term to the list")
937
+ terms_add.add_argument("term")
938
+ terms_add.add_argument(
939
+ "--soft",
940
+ action="store_true",
941
+ help="a soft term: the owner must approve a write that holds it",
942
+ )
943
+ terms_add.add_argument(
944
+ "--kind",
945
+ choices=records.TERM_KINDS,
946
+ help="with --soft: only for this kind of memory, or note or synthesis",
947
+ )
948
+ terms_remove = terms_sub.add_parser(
949
+ "remove", help="remove every line that holds exactly this term"
950
+ )
951
+ terms_remove.add_argument("term")
952
+ terms_parser.set_defaults(func=admin.cmd_terms)
953
+ projects_parser = sub.add_parser(
954
+ "projects", help="the local registry of projects whose memories can be searched"
955
+ )
956
+ projects_sub = projects_parser.add_subparsers(dest="projects_command", required=True)
957
+ projects_sub.add_parser("list", help="one line per project: name, live memories, path")
958
+ projects_add = projects_sub.add_parser("add", help="register a project by hand")
959
+ projects_add.add_argument("path")
960
+ projects_add.add_argument("--name")
961
+ projects_remove = projects_sub.add_parser(
962
+ "remove", help="forget a project; its files are not touched"
963
+ )
964
+ projects_remove.add_argument("name")
965
+ projects_parser.set_defaults(func=admin.cmd_projects)
966
+ init_parser = sub.add_parser(
967
+ "init", help="make a folder a writable store (default: the default store)"
968
+ )
969
+ init_parser.add_argument("folder", metavar="FOLDER", nargs="?")
970
+ init_parser.set_defaults(func=admin.cmd_init)
971
+
972
+
973
+ def _parser_add_history(sub: Any) -> None:
974
+ history_parser = sub.add_parser("history", help="the store's git history: list, init, commit")
975
+ history_parser.add_argument(
976
+ "-n", type=int, default=10, metavar="N", help="how many commits to list"
977
+ )
978
+ history_sub = history_parser.add_subparsers(dest="history_command")
979
+ history_init = history_sub.add_parser("init", help="make a writable store a git repository")
980
+ history_init.add_argument("folder", metavar="STORE", nargs="?")
981
+ history_commit = history_sub.add_parser("commit", help="commit what changed in the store")
982
+ history_commit.add_argument("-m", dest="message", metavar="TEXT", help="the commit message")
983
+ history_commit.add_argument(
984
+ "--hook",
985
+ action="store_true",
986
+ help="the SessionEnd hook: a `session end` message, silent, always exit 0, log the call",
987
+ )
988
+ history_commit.add_argument(
989
+ "--detached",
990
+ action="store_true",
991
+ help="with --hook: also log a `started` record before and a `done` one after, so a killed run shows",
992
+ )
993
+ history_parser.set_defaults(func=admin.cmd_history)
994
+
995
+
996
+ def _parser_add_memory_edit(sub: Any) -> None:
997
+ memory_parser = sub.add_parser(
998
+ "memory", help="change a memory through mem, never by editing its file"
999
+ )
1000
+ memory_sub = memory_parser.add_subparsers(dest="memory_command", required=True)
1001
+ memory_edit = memory_sub.add_parser(
1002
+ "edit", help="replace the claim, the context or the body of a memory"
1003
+ )
1004
+ memory_edit.add_argument("handle", metavar="m:HANDLE")
1005
+ memory_edit.add_argument("--claim", metavar="TEXT", help="the new claim (one sentence)")
1006
+ memory_edit.add_argument(
1007
+ "--context", metavar="TEXT", help="the new context; an empty text removes it"
1008
+ )
1009
+ memory_edit.add_argument(
1010
+ "--body-file", metavar="PATH", help="the new body; - reads standard input"
1011
+ )
1012
+ memory_edit.add_argument(
1013
+ "--short",
1014
+ metavar="TEXT",
1015
+ help="the one-line rule loaded at session start; an empty text removes it",
1016
+ )
1017
+ memory_edit.add_argument("--user-read", action="store_true", help=_USER_READ)
1018
+ memory_edit.add_argument(
1019
+ "--reworded",
1020
+ action="store_true",
1021
+ help="with --short: the automatic step wrote this text; marks the lesson as reworded",
1022
+ )
1023
+ memory_edit.add_argument(
1024
+ "--reword-failed",
1025
+ action="store_true",
1026
+ help="alone: note that the automatic rewording gave up on the last version",
1027
+ )
1028
+ memory_edit.add_argument(
1029
+ "--topic", metavar="TEXT", help="one or two lowercase words; an empty text removes it"
1030
+ )
1031
+ load_switch = memory_edit.add_mutually_exclusive_group()
1032
+ load_switch.add_argument(
1033
+ "--no-load", action="store_true", help="never load this lesson as a rule"
1034
+ )
1035
+ load_switch.add_argument(
1036
+ "--index-only",
1037
+ action="store_true",
1038
+ help="never load this lesson as a rule, but count it in the index line by topic",
1039
+ )
1040
+ load_switch.add_argument(
1041
+ "--load", action="store_true", help="remove --no-load and --index-only"
1042
+ )
1043
+ memory_edit.add_argument(
1044
+ "--shrink",
1045
+ action="store_true",
1046
+ help="accept a text that drops over 20%% of the words, a sentence or a link",
1047
+ )
1048
+ memory_edit.add_argument("--owner-approved", action="store_true", help=_OWNER_APPROVED)
1049
+ memory_edit.add_argument(
1050
+ "--global",
1051
+ dest="is_global",
1052
+ action="store_true",
1053
+ help="edit the global memory when the handle exists in both scopes",
1054
+ )
1055
+ memory_parser.set_defaults(func=memory.cmd_memory)
1056
+
1057
+
1058
+ def build_parser() -> argparse.ArgumentParser:
1059
+ parser = argparse.ArgumentParser(
1060
+ prog="mem", description="Memory engine: search and read a store of notes."
1061
+ )
1062
+ parser.add_argument(
1063
+ "--root", default=None, help="store folder (default: $MEM_STORE, then the config file)"
1064
+ )
1065
+ sub = parser.add_subparsers(dest="command", required=True)
1066
+ for add in (
1067
+ _parser_add_search,
1068
+ _parser_add_read,
1069
+ _parser_add_sources,
1070
+ _parser_add_note,
1071
+ _parser_add_import,
1072
+ _parser_add_new,
1073
+ _parser_add_remember,
1074
+ _parser_add_hooks,
1075
+ _parser_add_memory_marks,
1076
+ _parser_add_triage,
1077
+ _parser_add_memory_pairs,
1078
+ _parser_add_memories,
1079
+ _parser_add_settle,
1080
+ _parser_add_project_synthesis,
1081
+ _parser_add_synthesis,
1082
+ _parser_add_registry,
1083
+ _parser_add_history,
1084
+ _parser_add_memory_edit,
1085
+ _parser_add_install,
1086
+ _parser_add_diagnostics,
1087
+ ):
1088
+ add(sub)
1089
+ return parser
1090
+
1091
+
1092
+ def main(argv: list[str] | None = None) -> int:
1093
+ try:
1094
+ return _dispatch(argv)
1095
+ except safe_io.UnsafePath as exc: # a symlink where a command refuses one
1096
+ print(f"mem: refused: {exc}", file=sys.stderr)
1097
+ return 2
1098
+
1099
+
1100
+ def _no_store_folder(root: Path | None) -> bool:
1101
+ return root is None or not root.is_dir()
1102
+
1103
+
1104
+ def _memories_need_no_store(args: argparse.Namespace, root: Path | None) -> bool:
1105
+ """True for a search of memories only, or a show of memory handles, when no store folder exists."""
1106
+ if args.command == "search":
1107
+ return args.scope == "memories" and _no_store_folder(root)
1108
+ if args.command == "show":
1109
+ return all(
1110
+ a.startswith(("m:", "p:")) or common._find_memory(args, a) for a in args.paths
1111
+ ) and _no_store_folder(root)
1112
+ return False
1113
+
1114
+
1115
+ def _store_refusal(args: argparse.Namespace, root: Path | None) -> str | None:
1116
+ """The message that refuses `args.command` on this store, or None when the command may run."""
1117
+ if root is None:
1118
+ return common.no_store_message(os.environ)
1119
+ if root.exists() and not root.is_dir():
1120
+ return f"mem: the store is not a folder: {root}"
1121
+ if not root.is_dir():
1122
+ return f"mem: the store folder does not exist: {root}"
1123
+ writes = (
1124
+ args.command in _WRITE_COMMANDS
1125
+ or (args.command == "synthesis" and args.synthesis_command in _SYNTHESIS_WRITES)
1126
+ or (
1127
+ args.command == "synthesis"
1128
+ and args.synthesis_command == "split"
1129
+ and bool(args.apply or args.undo or args.recover)
1130
+ )
1131
+ )
1132
+ if writes and not records.store_is_writable(root):
1133
+ return (
1134
+ f"mem: {args.command} writes to the store, which is read-only: it has no mem-store.yaml "
1135
+ '(create a store with "mem init").'
1136
+ )
1137
+ return None
1138
+
1139
+
1140
+ def _dispatch_store(args: argparse.Namespace) -> int | None:
1141
+ """Resolve the store into `args.root`; the exit code of a refusal, or None to run the command."""
1142
+ if args.command in {"init", "diagnostics", "terms", "history"}:
1143
+ return None
1144
+ if (
1145
+ args.command in _NO_STORE_NEEDED
1146
+ ): # a project memory needs no store; a missing one is an error only where used
1147
+ args.root = common.resolve_root(args.root, os.environ)
1148
+ return None
1149
+ root = common.resolve_root(args.root, os.environ)
1150
+ if _memories_need_no_store(args, root):
1151
+ args.root = None # memories need no store; only a project or a global folder
1152
+ return None
1153
+ refusal = _store_refusal(args, root)
1154
+ if refusal:
1155
+ print(refusal, file=sys.stderr)
1156
+ return 2
1157
+ args.root_source = store_source(args.root, os.environ)
1158
+ args.root = root
1159
+ return None
1160
+
1161
+
1162
+ def _dispatch(argv: list[str] | None) -> int:
1163
+ parser = build_parser()
1164
+ args = parser.parse_args(argv)
1165
+ if args.command == "read":
1166
+ args.command = "show"
1167
+ if refusal := safe_io.sandbox_refusal(args.command, vars(args)):
1168
+ print(f"mem: {refusal}", file=sys.stderr)
1169
+ return 2
1170
+ try:
1171
+ code = _dispatch_store(args)
1172
+ return args.func(args) if code is None else code
1173
+ except (
1174
+ common.UsageError
1175
+ ) as exc: # the parser's usage line and exit code 2, as argparse prints them
1176
+ parser.error(str(exc))
1177
+
1178
+
1179
+ if __name__ == "__main__":
1180
+ sys.exit(main())