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,45 @@
1
+ """Write-ahead rollback for imports; callers hold locked() during imports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ from memory_cli.core.file_journal import DivergedError, FileJournal
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import Mapping
11
+ from pathlib import Path
12
+
13
+ __all__ = ["DivergedError"]
14
+
15
+ DIRECTORY = ".import-recovery"
16
+ JOURNAL = "journal.json"
17
+
18
+
19
+ def _journal(root: Path) -> FileJournal:
20
+ return FileJournal(root, DIRECTORY, version=1)
21
+
22
+
23
+ def locked(root: Path):
24
+ return _journal(root).locked()
25
+
26
+
27
+ def pending(root: Path) -> bool:
28
+ return _journal(root).pending()
29
+
30
+
31
+ def publish(root: Path, intended: Mapping[Path, bytes]) -> None:
32
+ journal = _journal(root)
33
+ if journal.pending():
34
+ raise FileExistsError("an import recovery journal already exists")
35
+ journal.publish({
36
+ path: (journal.read_original(path), after) for path, after in intended.items()
37
+ })
38
+
39
+
40
+ def rollback(root: Path) -> None:
41
+ _journal(root).rollback()
42
+
43
+
44
+ def clear(root: Path) -> None:
45
+ _journal(root).clear()
@@ -0,0 +1,152 @@
1
+ """`mem install-command` (ADR 0036): put `mem` (and `mem-research`, `mem-synthesize`) on PATH for every tool, and the plugin-root record it follows.
2
+
3
+ The plugin lives in a versioned cache folder that moves with every update, so the launcher does not embed one path:
4
+ it reads `<state dir>/plugin-root`, which each session start refreshes (`record_root`), and falls back to the root
5
+ that ran `install-command`."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import os
11
+ import shlex
12
+ import shutil
13
+ import sys
14
+ from pathlib import Path
15
+ from typing import TYPE_CHECKING, Any
16
+
17
+ from memory_cli.core import jobs, resources, safe_io
18
+
19
+ if TYPE_CHECKING:
20
+ import argparse
21
+
22
+ MARKER = "# agent-memory launcher (mem install-command)"
23
+ RECORD_NAME = "plugin-root"
24
+ _EXEC_MODE = 0o755
25
+ # Commands the Codex roles and skills call by name; each launcher runs the plugin's `bin/<name>`.
26
+ LAUNCHERS = ("mem", "mem-research", "mem-synthesize")
27
+
28
+ # Bash twin of `jobs.state_dir()`: MEM_DATA, else $XDG_STATE_HOME/agent-memory (default ~/.local/state); empty is unset.
29
+ _LAUNCHER = """#!/usr/bin/env bash
30
+ {marker}
31
+ if [ -n "${{MEM_DATA:-}}" ]; then d="$MEM_DATA"; else d="${{XDG_STATE_HOME:-$HOME/.local/state}}/agent-memory"; fi
32
+ rec=""
33
+ [ -r "$d/{record}" ] && IFS= read -r rec < "$d/{record}"
34
+ rec="${{rec%$'\\r'}}"
35
+ emb={embedded}
36
+ marker={marker_q}
37
+ for cand in "$rec" "$emb"; do
38
+ [ -n "$cand" ] && [ -x "$cand/bin/{name}" ] || continue
39
+ [ "$cand/bin/{name}" -ef "$0" ] && continue
40
+ line=""
41
+ {{ IFS= read -r line; IFS= read -r line; }} < "$cand/bin/{name}" 2>/dev/null
42
+ [ "$line" = "$marker" ] && continue
43
+ exec "$cand/bin/{name}" "$@"
44
+ done
45
+ printf '{name}: no plugin copy found; start a Claude Code or Codex session once, or reinstall with %s/bin/mem install-command\n' "$emb" >&2
46
+ exit 127
47
+ """
48
+
49
+
50
+ def default_bin_dir() -> Path:
51
+ return Path.home() / ".local" / "bin"
52
+
53
+
54
+ def launcher_missing() -> bool:
55
+ """True when no `mem` resolves on PATH (the rule of hooks/subagent-start.sh: `command -v mem`)."""
56
+ return shutil.which("mem") is None
57
+
58
+
59
+ def _write_record() -> None:
60
+ root = resources.plugin_root()
61
+ if root is None: # standalone: no plugin copy for a launcher to follow
62
+ return
63
+ state = jobs.state_dir()
64
+ target = state / RECORD_NAME
65
+ data = str(root).encode()
66
+ safe_io.refuse_symlink_chain(state, target) # raises UnsafePathError: record_root suppresses it
67
+ with contextlib.suppress(OSError):
68
+ if target.read_bytes() == data:
69
+ return
70
+ jobs.private_dir(target.parent)
71
+ safe_io.replace_file(target, data, 0o600)
72
+
73
+
74
+ def record_root() -> None:
75
+ """Record this copy's root for the launcher; writes only when it differs, never raises or prints."""
76
+ with contextlib.suppress(OSError, RuntimeError): # a failing hook disturbs every session
77
+ _write_record()
78
+
79
+
80
+ def launcher_text(root: Path, name: str = "mem") -> str:
81
+ return _LAUNCHER.format(
82
+ name=name,
83
+ marker=MARKER,
84
+ marker_q=shlex.quote(MARKER),
85
+ record=RECORD_NAME,
86
+ embedded=shlex.quote(str(root)),
87
+ )
88
+
89
+
90
+ def _is_ours(path: Path) -> bool:
91
+ try:
92
+ if path.is_symlink():
93
+ return False
94
+ lines = path.read_text(encoding="utf-8").splitlines()
95
+ except (OSError, UnicodeDecodeError):
96
+ return False
97
+ return len(lines) > 1 and lines[1] == MARKER
98
+
99
+
100
+ def _one(bin_dir: Path, name: str, remove: bool, root: Path | None) -> int:
101
+ """Install (pointing at `root`, the plugin folder) or remove the launcher `name`; a file that is not ours stays
102
+ untouched (returns 1)."""
103
+ target = bin_dir / name
104
+ exists = target.exists() or target.is_symlink()
105
+ if exists and not _is_ours(target):
106
+ print(
107
+ f"mem: {target} exists and is not an agent-memory launcher; left untouched",
108
+ file=sys.stderr,
109
+ )
110
+ return 1
111
+ if remove:
112
+ if exists:
113
+ target.unlink()
114
+ print(f"removed {target}" if exists else f"nothing to remove at {target}")
115
+ return 0
116
+ assert root is not None # cmd_install_command refuses an install without the plugin
117
+ bin_dir.mkdir(parents=True, exist_ok=True)
118
+ safe_io.replace_file(target, launcher_text(root, name).encode(), _EXEC_MODE)
119
+ print(f"installed {target}")
120
+ return 0
121
+
122
+
123
+ def _warn_off_path(bin_dir: Path) -> None:
124
+ on_path = str(bin_dir.resolve()) in {
125
+ str(Path(p).resolve()) for p in os.environ.get("PATH", "").split(os.pathsep) if p
126
+ }
127
+ if not on_path:
128
+ print(f"warning: {bin_dir} is not on PATH; add it so `mem` resolves", file=sys.stderr)
129
+
130
+
131
+ def cmd_install_command(args: argparse.Namespace) -> int:
132
+ root = resources.plugin_root()
133
+ if not args.remove and (root is None or not (root / "bin").is_dir()):
134
+ print("mem: install-command requires the plugin launchers", file=sys.stderr)
135
+ return 2
136
+ bin_dir = Path(args.bin_dir).expanduser() if args.bin_dir else default_bin_dir()
137
+ failed = sum(_one(bin_dir, name, args.remove, root) for name in LAUNCHERS)
138
+ if not args.remove:
139
+ _warn_off_path(bin_dir)
140
+ return 1 if failed else 0
141
+
142
+
143
+ def add_parser(sub: Any) -> None:
144
+ cmd = sub.add_parser(
145
+ "install-command",
146
+ help="install `mem`, `mem-research` and `mem-synthesize` as commands on PATH (launchers that follow the plugin)",
147
+ )
148
+ cmd.add_argument(
149
+ "--remove", action="store_true", help="delete the launchers this command wrote"
150
+ )
151
+ cmd.add_argument("--bin-dir", metavar="DIR", help="where to put it (default: ~/.local/bin)")
152
+ cmd.set_defaults(func=cmd_install_command)
@@ -0,0 +1,480 @@
1
+ """`mem synthesis integrate` (A3, A4): join knowledge notes to a part of a synthesis, all the rows of a file as one
2
+ logged, undoable group. No model text reaches the store: an appended sentence is the note's own claim, word for word,
3
+ plus its reference, so the secret and forbidden-term checks cannot be bypassed here."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import datetime
8
+ import hashlib
9
+ import json
10
+ import os
11
+ import re
12
+ import sys
13
+ import uuid
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+ from typing import TYPE_CHECKING, Any
17
+
18
+ import yaml
19
+
20
+ from memory_cli.commands import common, edit
21
+ from memory_cli.commands import synthesis as synthesis_commands
22
+ from memory_cli.core import safe_io
23
+ from memory_cli.core.file_journal import FileJournal
24
+ from memory_cli.integrate.log import log_entries
25
+ from memory_cli.integrate.rows import check_claim, parse_rows
26
+ from memory_cli.memories import records
27
+ from memory_cli.notes import note as note_files
28
+ from memory_cli.syntheses import document, units
29
+ from memory_cli.syntheses import edit as synthesis_edit
30
+
31
+ if TYPE_CHECKING:
32
+ import argparse
33
+ from collections.abc import Mapping
34
+
35
+ from memory_cli.integrate.rows import Row
36
+
37
+ _STATE_REFUSALS = (
38
+ ("part_of", "already part of a synthesis"),
39
+ ("superseded_by", "superseded"),
40
+ ("disputed", "disputed"),
41
+ )
42
+ _DIGEST_LENGTH = 10
43
+
44
+
45
+ @dataclass
46
+ class IntegrateOutcome:
47
+ """What `integrate` will write (each file with its old and new bytes), its output lines and how many rows it applied."""
48
+
49
+ changes: dict[Path, tuple[bytes, bytes]]
50
+ lines: list[str]
51
+ applied: int
52
+
53
+
54
+ @dataclass
55
+ class _Part:
56
+ """A part as it was read, and as the rows applied so far leave it."""
57
+
58
+ path: Path
59
+ original: bytes
60
+ handle: str
61
+ section: str
62
+ old: str
63
+ text: str
64
+ count: int
65
+
66
+
67
+ @dataclass
68
+ class _Joined:
69
+ """A note that joins a part: its path and bytes as read, its reference, and the part it goes to."""
70
+
71
+ path: Path
72
+ original: bytes
73
+ rel: str
74
+ part: _Part
75
+
76
+
77
+ @dataclass
78
+ class _Counts:
79
+ appended: int = 0
80
+ referenced: int = 0
81
+ refused: int = 0
82
+
83
+
84
+ @dataclass
85
+ class _Build:
86
+ root: Path
87
+ env: Mapping[str, str]
88
+ parts: dict[str, _Part | str] = field(default_factory=dict)
89
+ joined: dict[Path, _Joined] = field(default_factory=dict)
90
+ named: set[Path] = field(default_factory=set)
91
+ counts: dict[str, _Counts] = field(default_factory=dict)
92
+ lines: list[str] = field(default_factory=list)
93
+
94
+
95
+ def _flat(text: object) -> str:
96
+ return " ".join(str(text).split())
97
+
98
+
99
+ def _claim_of(meta: Mapping[str, Any]) -> str:
100
+ """The note's claim on one line; empty when it is missing or not text."""
101
+ claim = meta.get("claim")
102
+ return _flat(claim) if isinstance(claim, str) else ""
103
+
104
+
105
+ def _state_refusal(meta: Mapping[str, Any]) -> str | None:
106
+ """Why a note in this state cannot join a part, or None."""
107
+ return next((reason for key, reason in _STATE_REFUSALS if meta.get(key) is not None), None)
108
+
109
+
110
+ def _is_knowledge_rel(rel: str) -> bool:
111
+ """Whether the store-relative `rel` has the shape `knowledge/<topic>/<name>.md` that candidates list."""
112
+ parts = rel.split("/")
113
+ return (
114
+ len(parts) == len(("knowledge", "topic", "name.md"))
115
+ and parts[0] == "knowledge"
116
+ and parts[2] != "README.md"
117
+ and not any(p.startswith(".") for p in parts)
118
+ )
119
+
120
+
121
+ def _target_of(rel: str) -> str:
122
+ return common._note_target(rel)
123
+
124
+
125
+ def _read_part(root: Path, target: str) -> _Part:
126
+ """The part `target` names as it was read; ValueError when it cannot take a note."""
127
+ syn, sec = common._section_ref(root, target)
128
+ original = syn.path.read_bytes()
129
+ edit._lf(original.decode("utf-8"), syn.path.name)
130
+ if sec.handle == document.SUMMARY or sum(s.handle == sec.handle for s in syn.sections) > 1:
131
+ raise ValueError(f"the part {sec.handle!r} cannot take a note")
132
+ count = len(units.units(sec.text)[0])
133
+ return _Part(syn.path, original, syn.handle, sec.handle, sec.text, sec.text, count)
134
+
135
+
136
+ def _part_of_row(build: _Build, row: Row) -> _Part | str:
137
+ """The part a row names as it was read, or why it cannot be read."""
138
+ if row.target not in build.parts:
139
+ try:
140
+ build.parts[row.target] = _read_part(build.root, row.target)
141
+ except (ValueError, OSError, UnicodeDecodeError) as exc:
142
+ build.parts[row.target] = str(exc)
143
+ return build.parts[row.target]
144
+
145
+
146
+ def _find_note(root: Path, name: str) -> tuple[Path, str] | str:
147
+ """(path, rel) of the knowledge note `name`, or why there is none."""
148
+ found = common.resolve_note(root, name, prefix=False)
149
+ if isinstance(found, list):
150
+ return "ambiguous note"
151
+ if found is None:
152
+ return "no such note"
153
+ rel = found.relative_to(root).as_posix()
154
+ return (found, rel) if _is_knowledge_rel(rel) else "not a knowledge note"
155
+
156
+
157
+ def _note_of_row(build: _Build, row: Row) -> tuple[Path, str, dict[str, Any]] | str:
158
+ """(path, rel, frontmatter) of the note a row names, or why it cannot join a part."""
159
+ found = _find_note(build.root, row.note)
160
+ if isinstance(found, str):
161
+ return found
162
+ path, rel = found
163
+ if path in build.named:
164
+ return "named twice in the file"
165
+ build.named.add(path)
166
+ meta = note_files.split_frontmatter(note_files._read_text(path))[0]
167
+ if not isinstance(meta, dict):
168
+ return "not a knowledge note"
169
+ return _state_refusal(meta) or (path, rel, meta)
170
+
171
+
172
+ def _new_text(build: _Build, row: Row, part: _Part, joined: tuple[str, str, str]) -> str:
173
+ """The part's text after the row; ValueError with the reason when the row cannot be applied."""
174
+ claim, stem, target = joined
175
+ # Listed by target: the same note under another label is not listed twice.
176
+ is_listed = f"({target})" in (synthesis_edit._sources_line(part.text) or "")
177
+ sources = "" if is_listed else f"\n\nSources: [{stem}]({target})"
178
+ if row.action == "append":
179
+ if reason := check_claim(claim, build.env):
180
+ raise ValueError(reason)
181
+ return synthesis_edit.append_text(
182
+ part.text, f"{claim} [{stem}]({target}){sources}", store=build.root
183
+ )
184
+ if row.unit is None or row.unit > part.count:
185
+ raise ValueError(f"no such unit {row.unit}")
186
+ # A reference can only name a note that the part's `Sources:` line lists: list it first.
187
+ listed = (
188
+ part.text if is_listed else synthesis_edit.append_text(part.text, sources, store=build.root)
189
+ )
190
+ new, why = synthesis_edit.change_references(
191
+ listed, build.root / document.SYNTHESES_DIR, [(row.unit, "add", target)]
192
+ )
193
+ if why[0] is not None:
194
+ raise ValueError(why[0])
195
+ if found := document.validate_section(new, build.root):
196
+ raise ValueError("; ".join(found))
197
+ return new
198
+
199
+
200
+ def _apply_row(build: _Build, row: Row) -> str | None:
201
+ """Apply one row to the working text of its part; the reason it is refused, or None."""
202
+ note = _note_of_row(build, row)
203
+ if isinstance(note, str):
204
+ return note
205
+ part = _part_of_row(build, row)
206
+ if isinstance(part, str):
207
+ return part
208
+ path, rel, meta = note
209
+ if not part.old or units.fingerprint(part.old) != row.fingerprint:
210
+ return "part changed since it was read"
211
+ if not (claim := _claim_of(meta)):
212
+ return "claim is empty"
213
+ try:
214
+ new = _new_text(build, row, part, (claim, path.stem, _target_of(rel)))
215
+ except ValueError as exc:
216
+ return str(exc)
217
+ part.text = new
218
+ build.joined[path] = _Joined(path, path.read_bytes(), rel, part)
219
+ return None
220
+
221
+
222
+ def _count(build: _Build, row: Row, reason: str | None) -> None:
223
+ counts = build.counts.setdefault(row.target.partition("#")[0], _Counts())
224
+ if reason is not None:
225
+ counts.refused += 1
226
+ build.lines.append(f"refused\t{row.note}\t{reason}")
227
+ return
228
+ if row.action == "append":
229
+ counts.appended += 1
230
+ label = "append"
231
+ else:
232
+ counts.referenced += 1
233
+ label = f"unit {row.unit}"
234
+ build.lines.append(f"applied\t{row.note}\t{row.target}\t{label}")
235
+
236
+
237
+ def _changes(build: _Build, today: datetime.date) -> dict[Path, tuple[bytes, bytes]]:
238
+ """The synthesis files, the joined notes and the members of the changed parts, each with old and new bytes."""
239
+ changes: dict[Path, tuple[bytes, bytes]] = {}
240
+ files: dict[Path, tuple[bytes, str]] = {}
241
+ changed = [p for p in build.parts.values() if isinstance(p, _Part) and p.text != p.old]
242
+ for part in changed:
243
+ _, text = files.get(part.path, (part.original, part.original.decode("utf-8")))
244
+ files[part.path] = (
245
+ part.original,
246
+ synthesis_edit.apply_part_text(text, part.section, part.text),
247
+ )
248
+ for path, (original, text) in files.items():
249
+ changes[path] = (original, synthesis_edit.bumped(text, today).encode("utf-8"))
250
+ for part in changed:
251
+ changes.update(
252
+ synthesis_commands._refs_note_edits(
253
+ build.root, part.handle, part.section, (part.old, part.text)
254
+ )
255
+ )
256
+ for item in build.joined.values():
257
+ text = edit._lf(item.original.decode("utf-8"), item.rel)
258
+ stamp = units.note_fingerprint(item.part.text, _target_of(item.rel))
259
+ part_of = f"{item.part.handle}#{item.part.section}"
260
+ changes[item.path] = (item.original, edit._set_part_of(text, part_of, stamp).encode())
261
+ return changes
262
+
263
+
264
+ def integrate_changes(
265
+ root: Path, rows: list[Row], env: Mapping[str, str], today: datetime.date
266
+ ) -> IntegrateOutcome:
267
+ """Build in memory every change the rows make: the synthesis files once, each joined note with `part_of` and a
268
+ `u:` stamp, and the members of a changed part re-stamped. Every row is judged against the part as it was read."""
269
+ build = _Build(root, env)
270
+ for row in rows:
271
+ _count(build, row, _apply_row(build, row))
272
+ for handle, c in build.counts.items():
273
+ build.lines.append(
274
+ f"{handle}: appended {c.appended}, referenced {c.referenced}, refused {c.refused}"
275
+ )
276
+ return IntegrateOutcome(_changes(build, today), build.lines, len(build.joined))
277
+
278
+
279
+ def _candidate_parts(syn: document.Synthesis) -> list[dict[str, Any]]:
280
+ return [
281
+ {
282
+ "section": s.handle,
283
+ "fingerprint": units.fingerprint(s.text),
284
+ "units": [{"n": u.n, "text": u.text} for u in units.units(s.text)[0]],
285
+ }
286
+ for s in syn.sections
287
+ if s.handle != document.SUMMARY and sum(x.handle == s.handle for x in syn.sections) == 1
288
+ ]
289
+
290
+
291
+ def _loose_notes(root: Path) -> list[tuple[note_files.Note, list[str]]]:
292
+ """Knowledge notes that are part of no synthesis, are not superseded or disputed, with their own topics."""
293
+ try:
294
+ known = note_files.load_topics(root)
295
+ except note_files.FrontmatterError:
296
+ known = {}
297
+ found = []
298
+ for note in note_files.discover_notes(root):
299
+ if note.type != "knowledge" or note.error is not None or not isinstance(note.meta, dict):
300
+ continue
301
+ if _state_refusal(note.meta) or not _claim_of(note.meta) or not _is_knowledge_rel(note.rel):
302
+ continue
303
+ topics = [t for t in note.meta.get("topics", []) if isinstance(t, str)]
304
+ found.append((note, edit._own_topics(known, topics)))
305
+ return sorted(found, key=lambda item: note_files._handle(item[0].rel))
306
+
307
+
308
+ def candidates(root: Path) -> list[dict[str, Any]]:
309
+ """Per synthesis, the loose notes its topics cover (a note only under the first synthesis) and its parts."""
310
+ loose = _loose_notes(root)
311
+ taken: set[str] = set()
312
+ out = []
313
+ for syn in document.load(root / document.SYNTHESES_DIR):
314
+ if syn.error is not None:
315
+ continue
316
+ mine = [note for note, own in loose if note.rel not in taken and set(own) & set(syn.topics)]
317
+ taken.update(note.rel for note in mine)
318
+ if mine:
319
+ out.append({
320
+ "synthesis": syn.handle,
321
+ "notes": [
322
+ {
323
+ "handle": note_files._handle(n.rel),
324
+ "claim": _claim_of(n.meta),
325
+ "digest": hashlib.sha256(n.path.read_bytes()).hexdigest()[:_DIGEST_LENGTH],
326
+ }
327
+ for n in mine
328
+ ],
329
+ "parts": _candidate_parts(syn),
330
+ })
331
+ return out
332
+
333
+
334
+ def _write(root: Path, changes: dict[Path, tuple[bytes, bytes]], group: str) -> str:
335
+ """Write files and their curation entries under the caller's journal lock."""
336
+ journal = FileJournal(root, ".integrate-recovery")
337
+ synthesis_commands._synthesis_require_writable(changes)
338
+ synthesis_commands._logged_changes_unchanged(changes)
339
+ log = root / records.CURATION_LOG
340
+ old_log = journal.read_original(log)
341
+ entries = common._group_entries(
342
+ root,
343
+ {path: (old, common._sha(new)) for path, (old, new) in changes.items()},
344
+ "integrate",
345
+ group=group,
346
+ ).encode("utf-8")
347
+ prefix = old_log or b""
348
+ if prefix and not prefix.endswith(b"\n"):
349
+ prefix += b"\n"
350
+ writes = {**changes, log: (old_log, prefix + entries)}
351
+ journal.publish(writes)
352
+ try:
353
+ for path, (_, after) in writes.items():
354
+ safe_io.refuse_symlink_chain(root, path)
355
+ safe_io.replace_file(path, after)
356
+ except Exception:
357
+ try:
358
+ journal.rollback()
359
+ journal.clear()
360
+ except Exception as exc:
361
+ raise OSError("integration recovery pending after rollback failure") from exc
362
+ raise
363
+ journal.clear()
364
+ return group
365
+
366
+
367
+ def _check_group(root: Path, group: str) -> None:
368
+ if not re.fullmatch(r"[0-9a-f]{32}", group):
369
+ raise ValueError("invalid integration group")
370
+ log = root / records.CURATION_LOG
371
+ safe_io.refuse_symlink_chain(root, log)
372
+ if any(entry.get("group") == group for _, entry in log_entries(root)):
373
+ raise ValueError("integration group already committed")
374
+
375
+
376
+ def _check_notes(root: Path, rows: list[Row], filename: str) -> None:
377
+ expected = json.loads(Path(filename).read_text(encoding="utf-8"))
378
+ if not isinstance(expected, dict):
379
+ raise TypeError("expected notes must be a JSON object")
380
+ for row in rows:
381
+ digest = expected.get(row.note)
382
+ found = _find_note(root, row.note)
383
+ if (
384
+ not isinstance(digest, str)
385
+ or not re.fullmatch(r"[0-9a-f]{10}", digest)
386
+ or isinstance(found, str)
387
+ or hashlib.sha256(found[0].read_bytes()).hexdigest()[:_DIGEST_LENGTH] != digest
388
+ ):
389
+ raise ValueError(f"note changed or missing expected digest: {row.note}")
390
+
391
+
392
+ def _run(args: argparse.Namespace, root: Path) -> int: # ruff: ignore[complex-structure]
393
+ if args.candidates:
394
+ print(json.dumps(candidates(root), ensure_ascii=False))
395
+ return 0
396
+ rows, bad = parse_rows(Path(args.file).read_text(encoding="utf-8"))
397
+ if bad:
398
+ print("\n".join(f"mem: {m}" for m in bad), file=sys.stderr)
399
+ return 2
400
+ journal = FileJournal(root, ".integrate-recovery")
401
+ with journal.locked():
402
+ if journal.pending():
403
+ raise FileExistsError("integration recovery is pending")
404
+ group_id = args.group or uuid.uuid4().hex
405
+ _check_group(root, group_id)
406
+ if not rows:
407
+ print("no rows")
408
+ return 0
409
+ if args.expect_notes:
410
+ _check_notes(root, rows, args.expect_notes)
411
+ outcome = integrate_changes(root, rows, os.environ, datetime.date.today())
412
+ group = _write(root, outcome.changes, group_id) if outcome.applied else None
413
+ print("\n".join(outcome.lines))
414
+ if group is not None:
415
+ print(f"group\t{group}")
416
+ common.log_usage(root, {"cmd": "synthesis", "action": "integrate"})
417
+ return 0
418
+
419
+
420
+ def _integrate(args: argparse.Namespace) -> int:
421
+ """`mem synthesis integrate FILE` or `--candidates`; 0 when the file parsed, 2 on a usage or store error."""
422
+ if sum(bool(x) for x in (args.file, args.candidates, args.recover)) != 1 or (
423
+ (args.group or args.expect_notes) and not args.file
424
+ ):
425
+ print("mem: give a rows file or --candidates, not both", file=sys.stderr)
426
+ return 2
427
+ try: # ruff: ignore[too-many-statements-in-try-clause]
428
+ if args.recover:
429
+ journal = FileJournal(args.root.resolve(), ".integrate-recovery")
430
+ with journal.locked():
431
+ if journal.pending():
432
+ journal.rollback()
433
+ journal.clear()
434
+ print("recovered")
435
+ else:
436
+ print("nothing to recover")
437
+ return 0
438
+ return _run(args, args.root.resolve())
439
+ except (
440
+ common.NewNoteError,
441
+ TypeError,
442
+ OSError,
443
+ UnicodeDecodeError,
444
+ ValueError,
445
+ note_files.FrontmatterError,
446
+ yaml.YAMLError,
447
+ ) as exc:
448
+ print(f"mem: {exc}", file=sys.stderr)
449
+ return 2
450
+
451
+
452
+ def register(synthesis_sub: Any) -> None:
453
+ """Add `integrate` to the `mem synthesis` subcommands. The handler is set on the subparser, not in the
454
+ synthesis dispatch table: that module cannot import this one, which imports it."""
455
+ parser = synthesis_sub.add_parser(
456
+ "integrate", help="join knowledge notes to parts of a synthesis from a file of rows"
457
+ )
458
+ parser.add_argument(
459
+ "file",
460
+ nargs="?",
461
+ metavar="FILE",
462
+ help="one row per line: NOTE | s:HANDLE#SECTION | append | FINGERPRINT or NOTE | s:HANDLE#SECTION | unit N | FINGERPRINT",
463
+ )
464
+ parser.add_argument(
465
+ "--candidates",
466
+ action="store_true",
467
+ help="print as JSON the notes each synthesis could take and its parts, instead of reading rows",
468
+ )
469
+ parser.add_argument(
470
+ "--recover", action="store_true", help="roll back an interrupted integration"
471
+ )
472
+ parser.add_argument(
473
+ "--group", help="use a preallocated 32-character lowercase hexadecimal group ID"
474
+ )
475
+ parser.add_argument(
476
+ "--expect-notes",
477
+ metavar="FILE",
478
+ help="check note digests from a JSON object before applying",
479
+ )
480
+ parser.set_defaults(func=_integrate)