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,5 @@
1
+ """Session start and compaction: the handoff block of a compaction summary and the notices printed at session start.
2
+
3
+ `handoff`: parse the handoff block of a compaction summary
4
+ `notices`: store lines of the session index: held-back and due notes
5
+ """
@@ -0,0 +1,139 @@
1
+ """Parse the handoff block an agent writes at the end of a compaction summary.
2
+
3
+ Pure and standard-library only. Lenient on Markdown around the marker and the
4
+ field names, so a compliant model is never reported as non-compliant.
5
+ """
6
+
7
+ import os
8
+ import re
9
+ from pathlib import Path
10
+
11
+ FIELDS: tuple[str, ...] = ("task", "state", "next", "verified", "unverified", "plan")
12
+
13
+ INSTRUCTION = """End the summary with this block, one line per field, so the next context resumes from it:
14
+ HANDOFF
15
+ task: <the task in progress, in one sentence>
16
+ state: <what is done>
17
+ next: <the next step>
18
+ verified: <what a check or the owner confirmed>
19
+ unverified: <what is claimed but not checked>
20
+ plan: <path of the active plan file, or "no plan">
21
+ Before the block, list every decision, constraint, pitfall or finding of this session that was not yet recorded with mem remember, one per line, each line starting with "not yet recorded:", so that the next context can record them."""
22
+
23
+ _MARKER_STRIP = "#*->`: \t"
24
+ _FIELD = re.compile(
25
+ r"^[\s\-*>]*(?:\*\*)?(" + "|".join(FIELDS) + r")(?:\*\*)?\s*:(?:\*\*)?\s*(.*)$", re.IGNORECASE
26
+ )
27
+ _UNRECORDED = "not yet recorded:"
28
+ _PLAN_TOKEN = re.compile(r"[^\s'\"`\[\]()<>,;*]+\.md(?!\w)", re.IGNORECASE)
29
+ _NO_BLOCK = "The summary has no handoff block: state the task, its state and the next step before you continue."
30
+ _MAX_VALUE = 500 # bounds the regex work on hostile text
31
+ _NONE = {"none", "nothing"}
32
+ _MARKER_LINE = 40
33
+ _MAX_TOKEN = 60 # keeps the whole line under 150 characters
34
+
35
+
36
+ def has_marker(summary: str) -> bool:
37
+ """True when a short line (a heading or label) names the handoff; the word inside a sentence does not count."""
38
+ return any(
39
+ "handoff" in line.lower() and len(line.strip()) <= _MARKER_LINE
40
+ for line in summary.splitlines()
41
+ )
42
+
43
+
44
+ def _marker_index(lines: list[str]) -> int | None:
45
+ marker = None
46
+ for i, line in enumerate(lines):
47
+ if line.strip(_MARKER_STRIP).lower() == "handoff":
48
+ marker = i
49
+ return marker
50
+
51
+
52
+ def _field_of(line: str) -> tuple[str, str] | None:
53
+ if line.lstrip().startswith("```"):
54
+ return None
55
+ m = _FIELD.match(line)
56
+ if not m:
57
+ return None
58
+ value = m.group(2).strip()
59
+ if value.startswith("<") and value.endswith(">") and " " in value:
60
+ return None # an echoed template placeholder is a phrase; <docs/p.md> is a path
61
+ return m.group(1).lower(), value[:_MAX_VALUE]
62
+
63
+
64
+ def parse(summary: str) -> dict[str, str]:
65
+ lines = summary.splitlines()
66
+ marker = _marker_index(lines)
67
+ if marker is None:
68
+ return {}
69
+ found: dict[str, str] = {}
70
+ for line in lines[marker + 1 :]:
71
+ field = _field_of(line)
72
+ if field:
73
+ found.setdefault(*field)
74
+ return found
75
+
76
+
77
+ def unrecorded(summary: str) -> int:
78
+ count = 0
79
+ in_list = False
80
+ for line in summary.splitlines():
81
+ stripped = line.strip()
82
+ head = stripped.lstrip("-* \t")
83
+ if head.lower().startswith(_UNRECORDED):
84
+ rest = head[len(_UNRECORDED) :].strip("*` \t")
85
+ none = rest.rstrip(".").strip("*` \t").lower() in _NONE
86
+ if rest and not none:
87
+ count += 1
88
+ in_list = not rest # only a bare header opens a list; "none" closes it
89
+ elif in_list and stripped[:1] in {"-", "*"}:
90
+ count += 1
91
+ else:
92
+ in_list = False
93
+ return count
94
+
95
+
96
+ def _project_root(cwd: Path) -> Path:
97
+ cwd = Path(os.path.realpath(cwd))
98
+ for d in (cwd, *cwd.parents):
99
+ if os.path.lexists(d / ".git"):
100
+ return d
101
+ return cwd
102
+
103
+
104
+ def _plan_token(value: str) -> str | None:
105
+ value = value[:_MAX_VALUE]
106
+ if "://" in value:
107
+ return None
108
+ m = _PLAN_TOKEN.search(value)
109
+ return m.group(0) if m else None
110
+
111
+
112
+ def names_plan(value: str) -> bool:
113
+ return _plan_token(value) is not None
114
+
115
+
116
+ def _accepts(root: Path, candidate: str, token: str) -> bool:
117
+ """True when this candidate ends the search with no mismatch to report."""
118
+ try:
119
+ target = Path(os.path.realpath(root / candidate)) # an absolute path replaces root
120
+ if root != target and root not in target.parents:
121
+ return candidate == token
122
+ return os.path.isfile(target)
123
+ except (OSError, ValueError):
124
+ return True
125
+
126
+
127
+ def mismatches(found: dict[str, str], cwd: Path) -> list[str]:
128
+ if not found:
129
+ return [_NO_BLOCK]
130
+ plan = found.get("plan", "")[:_MAX_VALUE]
131
+ token = _plan_token(plan)
132
+ if token is None:
133
+ return []
134
+ root = _project_root(Path(cwd))
135
+ if any(_accepts(root, candidate, token) for candidate in (token, plan.strip("'\"`* \t"))):
136
+ return []
137
+ return [
138
+ f"The handoff names a plan file that does not exist: {token[:_MAX_TOKEN]}. Find the plan before you continue."
139
+ ]
@@ -0,0 +1,111 @@
1
+ """The store lines of the session index: notes held back from history commits and notes due for re-reading.
2
+
3
+ Keeps the day's due count in the data folder. Imports notes.due and store_git, never mem."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import contextlib
8
+ import json
9
+ import logging
10
+ import os
11
+ import tempfile
12
+ from pathlib import Path
13
+ from typing import TYPE_CHECKING
14
+
15
+ from memory_cli.core import store_git
16
+ from memory_cli.notes import due
17
+
18
+ if TYPE_CHECKING:
19
+ import datetime
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ DUE_CACHE_NAME = "due-counts.json"
24
+
25
+
26
+ def _cached(cache: Path, key: str, today: str) -> tuple[int, int] | None:
27
+ try:
28
+ hit = json.loads(cache.read_text(encoding="utf-8")).get(key)
29
+ except (OSError, ValueError, AttributeError):
30
+ return None
31
+ if (
32
+ isinstance(hit, dict)
33
+ and hit.get("date") == today
34
+ and all(type(hit.get(k)) is int for k in ("retests", "rereads"))
35
+ ):
36
+ return hit["retests"], hit["rereads"]
37
+ return None
38
+
39
+
40
+ def _store(cache: Path, key: str, today: str, counts: tuple[int, int]) -> None:
41
+ """Keep only today's entries; a unique temp name in the folder lets two session starts write at once."""
42
+ try:
43
+ known = json.loads(cache.read_text(encoding="utf-8"))
44
+ known = {k: v for k, v in known.items() if isinstance(v, dict) and v.get("date") == today}
45
+ except (OSError, ValueError, AttributeError):
46
+ known = {}
47
+ known[key] = {"date": today, "retests": counts[0], "rereads": counts[1]}
48
+ cache.parent.mkdir(parents=True, exist_ok=True)
49
+ with tempfile.NamedTemporaryFile(
50
+ "w",
51
+ encoding="utf-8",
52
+ dir=cache.parent,
53
+ prefix=cache.name + ".",
54
+ suffix=".tmp",
55
+ delete=False,
56
+ ) as handle:
57
+ tmp = handle.name
58
+ try:
59
+ Path(tmp).write_text(json.dumps(known, indent=2, sort_keys=True) + "\n", encoding="utf-8")
60
+ os.replace(tmp, cache)
61
+ except OSError:
62
+ Path(tmp).unlink(missing_ok=True) # a failed write leaves no temp file behind
63
+ raise
64
+
65
+
66
+ def cached_due_counts(
67
+ root: Path, today: datetime.date, cache_dir: Path | None = None
68
+ ) -> tuple[int, int]:
69
+ """`due.due_counts`, kept per store and day in `cache_dir` when given.
70
+
71
+ The count refreshes once a day: a note edited or re-read later the same day shows from the next day."""
72
+ if cache_dir is None:
73
+ return due.due_counts(root, today)
74
+ cache = cache_dir / DUE_CACHE_NAME
75
+ key, day = str(root.resolve()), today.isoformat()
76
+ counts = _cached(cache, key, day)
77
+ if counts is None:
78
+ counts = due.due_counts(root, today)
79
+ with contextlib.suppress(OSError):
80
+ _store(cache, key, day, counts)
81
+ return counts
82
+
83
+
84
+ def store_due_lines(store: Path, today: datetime.date, cache_dir: Path | None) -> list[str]:
85
+ """Lines for notes held back from the last history commit and for notes past their review date; none at zero.
86
+
87
+ Never raises: a failing count leaves its line out so the session start goes on."""
88
+ lines = []
89
+ # Broad on purpose: one unreadable note or file must cost only its line, never the whole session index.
90
+ try:
91
+ held = len(store_git.held_back(store))
92
+ except Exception:
93
+ logger.debug("held-back count failed", exc_info=True)
94
+ held = 0
95
+ if held:
96
+ lines.append(
97
+ f"History: {held} changed {'note' if held == 1 else 'notes'} held back from the last "
98
+ "commit: run mem check."
99
+ )
100
+ try:
101
+ retests, rereads = cached_due_counts(store, today, cache_dir)
102
+ except Exception:
103
+ logger.debug("due count failed", exc_info=True)
104
+ return lines
105
+ n = retests + rereads
106
+ if n:
107
+ lines.append(
108
+ f"Re-read due: {n} {'note is' if n == 1 else 'notes are'} past "
109
+ f"{'its' if n == 1 else 'their'} review date: mem review."
110
+ )
111
+ return lines
@@ -0,0 +1,5 @@
1
+ """Settling new global memories against their look-alikes: the verdicts and the log, and the state of the background runs.
2
+
3
+ `state`: state of background settling, session start lines, trigger
4
+ `verdicts`: pairs a model judges, verdict enforcement, log
5
+ """
@@ -0,0 +1,111 @@
1
+ """Background settling (`bin/mem-settle`): where its state lives, the lines of the session start text, and the trigger
2
+ the write path calls. Standard library plus `settle.verdicts` and `jobs`; every function that runs in a write or at
3
+ session start swallows its errors, because it must never fail what it rides on."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import hashlib
8
+ import logging
9
+ import subprocess
10
+ from pathlib import Path
11
+ from typing import TYPE_CHECKING, SupportsFloat, SupportsIndex
12
+
13
+ from memory_cli.core import jobs, resources
14
+ from memory_cli.settle import verdicts as settle_verdicts
15
+
16
+ if TYPE_CHECKING:
17
+ import datetime
18
+ from collections.abc import Mapping
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ BIN = resources.mem_command("mem-settle")
23
+ DEFAULT_MINUTES = 30.0
24
+ # Set by the SessionStart hook for the session's shell commands: without them nothing here starts a run (trials, tests).
25
+ ENV_FLAG, ENV_MINUTES, ENV_CLAUDE = "MEM_SETTLE_AUTO", "MEM_SETTLE_MINUTES", "MEM_SETTLE_CLAUDE"
26
+
27
+
28
+ def settle_dir(data: Path, store: Path) -> Path:
29
+ """State of one store's settling runs: lock, status.json and runs/<stamp>/ (mode 0700), apart from mem-auto's."""
30
+ return (
31
+ Path(data) / "settle" / hashlib.sha1(str(Path(store).resolve()).encode()).hexdigest()[:12]
32
+ )
33
+
34
+
35
+ def minutes_of(value: object) -> float:
36
+ if not isinstance(value, SupportsFloat | SupportsIndex | str | bytes | bytearray | memoryview):
37
+ return DEFAULT_MINUTES
38
+ try:
39
+ number = float(value)
40
+ except (TypeError, ValueError):
41
+ return DEFAULT_MINUTES
42
+ return number if number >= 0 else DEFAULT_MINUTES
43
+
44
+
45
+ def failure_line(data: Path | None, store: Path | None, now: float) -> str | None:
46
+ if data is None or store is None:
47
+ return None
48
+ return jobs.failure_line(settle_dir(data, store), "settling", "mem-settle", now)
49
+
50
+
51
+ _WORDS = {"merge": "merged", "supersede": "superseded", "distinct": "kept distinct", "left": "left"}
52
+
53
+
54
+ def settled_line(folder: Path | None) -> str | None:
55
+ """One line while settlings the owner has not acknowledged (and not undone) exist. Reads only: it never creates
56
+ the state file, so a store that never settled stays untouched."""
57
+ if folder is None or not (folder / settle_verdicts.LOG_NAME).is_file():
58
+ return None
59
+ acked = jobs.read_json(folder / settle_verdicts.STATE_NAME).get("acked", 0)
60
+ fresh = [
61
+ s
62
+ for s in settle_verdicts.settlings(folder)
63
+ if s["seq"] > (acked if isinstance(acked, int) else 0) and not s["undone"]
64
+ ]
65
+ if not fresh:
66
+ return None
67
+ counts: dict[str, int] = {}
68
+ for s in fresh:
69
+ counts[s.get("decision", "")] = counts.get(s.get("decision", ""), 0) + 1
70
+ parts = [f"{counts[d]} {word}" for d, word in _WORDS.items() if counts.get(d)]
71
+ since = min(str(s.get("date", "")) for s in fresh)
72
+ return (
73
+ f"memory: settled since {since}: {', '.join(parts)}; see `mem settle log`, undo with "
74
+ "`mem settle undo <n>`, hide with `mem settle ack`."
75
+ )
76
+
77
+
78
+ def maybe_start(
79
+ folder: Path, store: Path | None, environ: Mapping[str, str], now: float, today: datetime.date
80
+ ) -> bool:
81
+ """After a write to the global scope: when the hook enabled settling and a run is due, start `mem-settle run`
82
+ detached. Returns whether it started one. Never raises."""
83
+ try:
84
+ return _start(folder, store, environ, now, today)
85
+ except Exception:
86
+ logger.debug("settle: could not start a run", exc_info=True)
87
+ return False
88
+
89
+
90
+ def _start(
91
+ folder: Path, store: Path | None, environ: Mapping[str, str], now: float, today: datetime.date
92
+ ) -> bool:
93
+ if environ.get(ENV_FLAG) != "1":
94
+ return False
95
+ minutes = minutes_of(environ.get(ENV_MINUTES))
96
+ if settle_verdicts.due(folder, minutes, now, today) is None:
97
+ return False
98
+ cmd = [*BIN, "run", "--minutes", str(minutes)]
99
+ if store is not None:
100
+ cmd += ["--store", str(store)]
101
+ if environ.get(ENV_CLAUDE):
102
+ cmd += ["--claude", environ[ENV_CLAUDE]]
103
+ subprocess.Popen(
104
+ cmd,
105
+ stdin=subprocess.DEVNULL,
106
+ stdout=subprocess.DEVNULL,
107
+ stderr=subprocess.DEVNULL,
108
+ start_new_session=True,
109
+ env=resources.child_env(environ),
110
+ )
111
+ return True