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,203 @@
1
+ """`mem-integrate --self-check`: no model, no cost. The briefs fill, the answer parser takes canned input, and the whole
2
+ flow (a run against a fake `claude`) works on a small store built in a temp folder, so it never touches the owner's data.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import io
8
+ import json
9
+ import logging
10
+ import os
11
+ import re
12
+ import subprocess
13
+ import tempfile
14
+ from contextlib import redirect_stdout
15
+ from pathlib import Path
16
+ from typing import TYPE_CHECKING
17
+ from unittest import mock
18
+
19
+ from memory_cli.core import resources
20
+ from memory_cli.integrate import answers
21
+ from memory_cli.integrate import state as run_state
22
+ from memory_cli.synthesize import pipeline as sp
23
+ from memory_cli.synthesize import run as synth_run
24
+
25
+ if TYPE_CHECKING:
26
+ from types import ModuleType
27
+
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ class SelfCheckError(Exception):
33
+ """A self-check step failed; the message says which."""
34
+
35
+
36
+ def _require(ok: object, reason: str) -> None:
37
+ if not ok:
38
+ raise SelfCheckError(reason)
39
+
40
+
41
+ FAKE_CLAUDE = """#!/usr/bin/env python3
42
+ import json
43
+ plan_file, count_file = {plan!r}, {count!r}
44
+ plan = json.load(open(plan_file))
45
+ try:
46
+ n = int(open(count_file).read())
47
+ except OSError:
48
+ n = 0
49
+ open(count_file, "w").write(str(n + 1))
50
+ answer = plan[n] if n < len(plan) else "none"
51
+ print(json.dumps({{"type": "result", "is_error": False, "result": answer,
52
+ "total_cost_usd": 0.0, "modelUsage": {{}}}}))
53
+ """
54
+ CHECK_PART = "Values have exactly one owner.[old-note](../knowledge/notes/old-note.md)"
55
+ NOTE_BODY = (
56
+ "## Claim\n\n{claim}\n\n## Evidence\n\nObserved.\n\n## Applies when\n\nAlways.\n\n"
57
+ "## Does not apply when\n\nNever.\n"
58
+ )
59
+
60
+
61
+ def _check_briefs(runner: ModuleType) -> None:
62
+ for name in ("place", "check"):
63
+ try:
64
+ text = sp.brief(name, briefs=runner.INTEGRATE_BRIEFS, INPUT_FILE="/tmp/input.json")
65
+ except AssertionError as exc:
66
+ raise SelfCheckError(f"the {name} brief: {exc}") from exc
67
+ _require("/tmp/input.json" in text, f"the {name} brief does not name its input file")
68
+
69
+
70
+ def _check_parser() -> None:
71
+ row = "n | s:a#b | append | ab12cd34ef"
72
+ _require(answers.answer_lines(f"```\n{row}\n```") == [row], "a good answer was refused")
73
+ _require(answers.answer_lines("none") == ["none"], "`none` was refused")
74
+ _require(answers.answer_lines("I think n fits.") is None, "a malformed answer was accepted")
75
+ _require(answers.answer_lines(f"none\n{row}") is None, "`none` with a row was accepted")
76
+
77
+
78
+ def _mem(store: Path, env: dict, *args: str) -> str:
79
+ found = sp.mem(store, env, *args)
80
+ _require(
81
+ found.returncode == 0, f"mem {' '.join(args[:2])} failed: {found.stderr.strip()[:200]}"
82
+ )
83
+ return found.stdout
84
+
85
+
86
+ def _build_store(tmp: Path) -> tuple[Path, dict]:
87
+ """A store with synthesis `alpha` (part `basics`, member `old-note`) and one loose note, `new-note`."""
88
+ store = tmp / "store"
89
+ env = synth_run.session_env(store) # as `run_env`: the check clears every MEM_ variable first
90
+ found = subprocess.run(
91
+ [*sp.MEM, "init", str(store)],
92
+ env=resources.child_env(env),
93
+ cwd=tmp,
94
+ capture_output=True,
95
+ text=True,
96
+ check=False,
97
+ )
98
+ _require(found.returncode == 0, f"mem init failed: {found.stderr.strip()[:200]}")
99
+ for slug, claim in (("old-note", "Ownership is tracked."), ("new-note", "Moves are default.")):
100
+ body = tmp / f"{slug}.md"
101
+ body.write_text(NOTE_BODY.format(claim=claim), encoding="utf-8")
102
+ _mem(
103
+ store, env, "new", "knowledge", "--slug", slug, "--claim", claim, "--topics", "notes",
104
+ "--confidence", "low", "--level", "basic", "--origin", "experience",
105
+ "--body-file", str(body),
106
+ ) # fmt: skip
107
+ summary, part = tmp / "summary.md", tmp / "part.md"
108
+ summary.write_text("Rust ownership.\n", encoding="utf-8")
109
+ part.write_text(
110
+ f"{CHECK_PART}\n\nSources: [old-note](../knowledge/notes/old-note.md)\n",
111
+ encoding="utf-8",
112
+ )
113
+ _mem(
114
+ store, env, "synthesis", "new", "--title", "Alpha", "--topics", "notes", "--slug", "alpha",
115
+ "--summary-file", str(summary),
116
+ ) # fmt: skip
117
+ _mem(
118
+ store, env, "synthesis", "add", "s:alpha", "--section", "Basics", "--body-file", str(part)
119
+ ) # fmt: skip
120
+ _mem(store, env, "synthesis", "attach", "old-note", "s:alpha#basics")
121
+ return store, env
122
+
123
+
124
+ def _fake_claude(tmp: Path, replies: list[str]) -> Path:
125
+ (tmp / "plan.json").write_text(json.dumps(replies), encoding="utf-8")
126
+ script = tmp / "fake-claude"
127
+ script.write_text(
128
+ FAKE_CLAUDE.format(plan=str(tmp / "plan.json"), count=str(tmp / "count")), encoding="utf-8"
129
+ )
130
+ script.chmod(0o755)
131
+ return script
132
+
133
+
134
+ def _isolate(tmp: Path) -> None:
135
+ """Point every state folder at `tmp`, so the check never touches the owner's data. Changes `os.environ`:
136
+ call it inside `mock.patch.dict(os.environ)`."""
137
+ for name in [k for k in os.environ if k.startswith("MEM_")]:
138
+ os.environ.pop(name) # every one the check does not set below
139
+ for name, folder in (
140
+ ("MEM_DATA", "data"),
141
+ ("XDG_DATA_HOME", "share"),
142
+ ("MEM_PROJECT", "project"),
143
+ ("XDG_CONFIG_HOME", "cfg"),
144
+ ):
145
+ os.environ[name] = str(tmp / folder)
146
+
147
+
148
+ def _check_flow(runner: ModuleType, place_check: tuple[str, str] | None) -> None:
149
+ with (
150
+ tempfile.TemporaryDirectory(prefix="mem-integrate-check-") as tmp_name,
151
+ mock.patch.dict(os.environ),
152
+ ):
153
+ _isolate(Path(tmp_name))
154
+ _flow(runner, Path(tmp_name), place_check)
155
+
156
+
157
+ def _flow(runner: ModuleType, tmp: Path, place_check: tuple[str, str] | None) -> None:
158
+ store, env = _build_store(tmp)
159
+ cands = json.loads(_mem(store, env, "synthesis", "integrate", "--candidates"))
160
+ _require(cands and cands[0]["parts"], "the fixture store offers no candidate")
161
+ row = f"new-note | s:alpha#basics | append | {cands[0]['parts'][0]['fingerprint']}"
162
+ replies = list(place_check or (row, row))
163
+ claude = _fake_claude(tmp, replies)
164
+ captured = io.StringIO()
165
+ with redirect_stdout(captured):
166
+ code = runner.cmd_run(store, str(claude), None)
167
+ _require(code == 0, f"the run exited {code}")
168
+ folder = runner.state_folder(store)
169
+ run_id = max(p.name for p in folder.iterdir() if p.is_dir())
170
+ record = run_state.read_record(folder, run_id)
171
+ _require(record is not None, "the run left no record")
172
+ failures = record.failures if record else []
173
+ _require(
174
+ not any(runner.UNREADABLE_FAILURE in f for f in failures),
175
+ f"a session could not read its input file: {failures}",
176
+ )
177
+ _require(not failures, f"the run failed: {failures}")
178
+ attached = next(iter(store.glob("knowledge/*/new-note.md"))).read_text(encoding="utf-8")
179
+ _require(
180
+ re.search(r"(?m)^part_of: \"?alpha#basics", attached), "the agreed row was not applied"
181
+ )
182
+ _require(
183
+ record is not None and [g.kind for g in record.groups] == ["integrate"],
184
+ "the run did not record one integrate group",
185
+ )
186
+
187
+
188
+ def self_check(runner: ModuleType, answers_given: tuple[str, str] | None = None) -> int:
189
+ """No cost: the briefs fill, the answer parser on canned input, then the whole flow (a run against a fake
190
+ `claude`) on a small store built in a temp folder. `runner` is the `entry.integrate` module (it imports this one, so this one cannot import it); `answers_given` replaces the fake's place and check answers."""
191
+ try:
192
+ _check_briefs(runner)
193
+ _check_parser()
194
+ _check_flow(runner, answers_given)
195
+ except SelfCheckError as exc:
196
+ print(f"self-check failed: {exc}")
197
+ return 1
198
+ except Exception as exc: # any broken step ends as a line, not a traceback
199
+ logger.debug("self-check failed", exc_info=True)
200
+ print(f"self-check failed: {type(exc).__name__}: {exc}")
201
+ return 1
202
+ print("self-check passed")
203
+ return 0
@@ -0,0 +1,9 @@
1
+ """Entry of `bin/mem-research`: the command line lives in `research.pipeline`."""
2
+
3
+ import sys
4
+
5
+ from memory_cli.research import pipeline
6
+
7
+
8
+ def main(argv: list[str] | None = None) -> int:
9
+ return pipeline.main(sys.argv[1:] if argv is None else argv)