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,97 @@
1
+ """CLI for inspectable, recoverable synthesis splits."""
2
+
3
+ import datetime
4
+ import json
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import yaml
10
+
11
+ from memory_cli.commands import common, split_plan, split_transaction
12
+ from memory_cli.notes import note as note_files
13
+
14
+
15
+ def _proposal(path):
16
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
17
+ keys = {"part", "topic", "parent_text", "child_heading", "child_text", "expected"}
18
+ if not isinstance(data, dict) or set(data) != keys:
19
+ raise ValueError("proposal must contain exactly the candidate proposal fields")
20
+ if any(not isinstance(data[k], str) for k in keys - {"expected"}):
21
+ raise ValueError("proposal text fields must be strings")
22
+ expected = data["expected"]
23
+ if not isinstance(expected, dict) or any(
24
+ not isinstance(k, str) or (v is not None and not isinstance(v, str))
25
+ for k, v in expected.items()
26
+ ):
27
+ raise ValueError("expected must map paths to digests or null")
28
+ return split_plan.SplitProposal(**data)
29
+
30
+
31
+ def _run(args): # ruff: ignore[complex-structure]
32
+ root = args.root.resolve()
33
+ if args.group and not args.apply:
34
+ raise ValueError("--group goes with --apply")
35
+ if args.candidate:
36
+ print(json.dumps(split_plan.candidate_input(root, *args.candidate), ensure_ascii=False))
37
+ elif args.preview or args.apply:
38
+ proposal = _proposal(args.preview or args.apply)
39
+
40
+ def prepare():
41
+ return split_plan.prepare_split(root, proposal, datetime.date.today(), os.environ)
42
+
43
+ if args.apply:
44
+ print(split_transaction.apply_split(root, prepare, args.group))
45
+ else:
46
+ plan = prepare()
47
+ print(
48
+ json.dumps(
49
+ {
50
+ "original": plan.original,
51
+ "retained": plan.parent_text,
52
+ "moved": plan.child_text,
53
+ "destination": plan.destination,
54
+ "moves": plan.moves,
55
+ "conflicts": plan.conflicts,
56
+ },
57
+ ensure_ascii=False,
58
+ )
59
+ )
60
+ elif args.undo:
61
+ split_transaction.undo_split(root, args.undo)
62
+ print("undone")
63
+ elif args.recover:
64
+ print("recovered" if split_transaction.recover_split(root) else "nothing to recover")
65
+ else:
66
+ pending, groups = split_transaction.split_status(root)
67
+ print(json.dumps({"pending": pending, "groups": groups}))
68
+ return 0
69
+
70
+
71
+ def cmd_split(args):
72
+ try:
73
+ return _run(args)
74
+ except (
75
+ common.NewNoteError,
76
+ OSError,
77
+ UnicodeError,
78
+ ValueError,
79
+ TypeError,
80
+ note_files.FrontmatterError,
81
+ yaml.YAMLError,
82
+ ) as exc:
83
+ print(f"mem: {exc}", file=sys.stderr)
84
+ return 2
85
+
86
+
87
+ def register(sub):
88
+ parser = sub.add_parser("split", help="preview and manage a recoverable synthesis split")
89
+ choices = parser.add_mutually_exclusive_group(required=True)
90
+ choices.add_argument("--candidate", nargs=2, metavar=("PART", "TOPIC"))
91
+ choices.add_argument("--preview", metavar="FILE")
92
+ choices.add_argument("--apply", metavar="FILE")
93
+ choices.add_argument("--undo", metavar="GROUP")
94
+ choices.add_argument("--recover", action="store_true")
95
+ choices.add_argument("--status", action="store_true")
96
+ parser.add_argument("--group", metavar="ID", help="with --apply: a reserved group id (32 hex)")
97
+ parser.set_defaults(func=cmd_split)
@@ -0,0 +1,196 @@
1
+ """Prepare an inspectable synthesis split without changing the store."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from dataclasses import dataclass
7
+ from typing import TYPE_CHECKING
8
+
9
+ from memory_cli.commands import common, edit, synthesis
10
+ from memory_cli.core import safe_io
11
+ from memory_cli.memories import terms
12
+ from memory_cli.notes import note as note_files
13
+ from memory_cli.notes import split_candidates
14
+ from memory_cli.syntheses import document, units
15
+ from memory_cli.syntheses import edit as syn_edit
16
+ from memory_cli.syntheses.split_conservation import check_conservation
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import Mapping
20
+ from datetime import date
21
+ from pathlib import Path
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class SplitProposal:
26
+ part: str
27
+ topic: str
28
+ parent_text: str
29
+ child_heading: str
30
+ child_text: str
31
+ expected: Mapping[str, str | None]
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class SplitPlan:
36
+ original: str
37
+ parent_text: str
38
+ child_text: str
39
+ destination: str
40
+ moves: tuple[str, ...]
41
+ conflicts: tuple[str, ...]
42
+ changes: dict[Path, tuple[bytes | None, bytes | None]]
43
+
44
+
45
+ def _safe(root: Path, path: Path) -> Path:
46
+ safe_io.refuse_symlink_chain(root, path)
47
+ try:
48
+ path.resolve().relative_to(root.resolve())
49
+ except ValueError:
50
+ raise ValueError(f"path outside store: {path}") from None
51
+ return path
52
+
53
+
54
+ def _resolve(root: Path, part: str, topic: str): # ruff: ignore[complex-structure]
55
+ syn, sec = common._section_ref(root, part)
56
+ if sec.handle == document.SUMMARY or sum(s.handle == sec.handle for s in syn.sections) != 1:
57
+ raise ValueError("part must name a unique non-summary section")
58
+ topics = note_files.load_topics(root)
59
+ notes = note_files.discover_notes(root)
60
+ syntheses = document.load(root / document.SYNTHESES_DIR)
61
+ if any(s.error for s in syntheses):
62
+ raise ValueError("cannot resolve destinations with an invalid synthesis")
63
+ candidates = split_candidates.find_candidates(notes, syntheses, topics)
64
+ name = f"{syn.handle}#{sec.handle}"
65
+ candidate = next((c for c in candidates if c.part == name and c.topic == topic), None)
66
+ if candidate is None:
67
+ raise ValueError("no such split candidate")
68
+ conflicts = tuple(
69
+ sorted(
70
+ c.topic
71
+ for c in candidates
72
+ if c.part == name and c.topic != topic and set(c.notes) & set(candidate.notes)
73
+ )
74
+ )
75
+ destinations = [s for s in syntheses if topic in s.topics]
76
+ if len(destinations) > 1:
77
+ raise ValueError("multiple syntheses declare the destination topic")
78
+ path = (
79
+ destinations[0].path
80
+ if destinations
81
+ else document.path_of(root / document.SYNTHESES_DIR, topic)
82
+ )
83
+ if path is None or path == syn.path or (not destinations and path.exists()):
84
+ raise ValueError("invalid or occupied destination")
85
+ for p in (syn.path, path, root / "topics.yaml"):
86
+ _safe(root, p)
87
+ return syn, sec, candidate, conflicts, destinations[0] if destinations else None, path
88
+
89
+
90
+ def _snapshot(root: Path, path: Path, syn, sec) -> dict[str, str | None]:
91
+ # Recompute membership and destination before comparing this bounded snapshot.
92
+ members = synthesis._part_of_notes(root, f"{syn.handle}#{sec.handle}")
93
+ paths = {root / "topics.yaml", syn.path, path, *(p for p, _ in members)}
94
+ for p in paths:
95
+ _safe(root, p)
96
+ return {
97
+ p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest()
98
+ if p.exists()
99
+ else None
100
+ for p in sorted(paths)
101
+ }
102
+
103
+
104
+ def candidate_input(root: Path, part: str, topic: str) -> dict[str, object]:
105
+ safe_io.refuse_symlink_chain(root, root)
106
+ root = root.resolve()
107
+ syn, sec, candidate, conflicts, dest, path = _resolve(root, part, topic)
108
+ expected = _snapshot(root, path, syn, sec)
109
+ return {
110
+ "proposal": {
111
+ "part": part,
112
+ "topic": topic,
113
+ "parent_text": sec.text,
114
+ "child_heading": topic,
115
+ "child_text": "",
116
+ "expected": expected,
117
+ },
118
+ "original": sec.text,
119
+ "destination": dest.handle if dest else topic,
120
+ "moves": list(candidate.notes),
121
+ "conflicts": list(conflicts),
122
+ }
123
+
124
+
125
+ def _link(text: str, label: str, target: str) -> str:
126
+ line = document._sources_line(text)
127
+ link = f"See also: [{label}]({target})"
128
+ if line:
129
+ index = text.rfind(line)
130
+ return text[:index].rstrip() + "\n\n" + link + "\n\n" + text[index:]
131
+ return text.rstrip() + "\n\n" + link
132
+
133
+
134
+ def prepare_split( # ruff: ignore[complex-structure, too-many-locals]
135
+ root: Path, proposal: SplitProposal, today: date, env: Mapping[str, str]
136
+ ) -> SplitPlan:
137
+ safe_io.refuse_symlink_chain(root, root)
138
+ root = root.resolve()
139
+ syn, sec, candidate, conflicts, dest, path = _resolve(root, proposal.part, proposal.topic)
140
+ if dict(proposal.expected) != _snapshot(root, path, syn, sec):
141
+ raise ValueError("split snapshot changed")
142
+ heading = " ".join(proposal.child_heading.split())
143
+ handle = document.section_handle(heading)
144
+ if (
145
+ not handle
146
+ or handle == document.SUMMARY
147
+ or (dest and any(s.handle == handle for s in dest.sections))
148
+ ):
149
+ raise ValueError("invalid or colliding child section")
150
+ parent, child = proposal.parent_text.strip("\n"), proposal.child_text.strip("\n")
151
+ if not parent.strip() or not child.strip():
152
+ raise ValueError("both part bodies are required")
153
+ syn_edit._check_body(parent)
154
+ syn_edit._check_body(child)
155
+ if problems := document.validate_section(sec.text, root):
156
+ raise ValueError("invalid original part: " + "; ".join(problems))
157
+ texts = [heading, parent, child]
158
+ if terms.secret_in(texts) or terms.term_hits(texts, env, "synthesis"):
159
+ raise ValueError("secret or forbidden term in proposal")
160
+ if problems := check_conservation(root, sec.text, parent, child):
161
+ raise ValueError("; ".join(problems))
162
+ base = root / document.SYNTHESES_DIR
163
+ sources = {
164
+ document._resolved(base, t) for t in (document._links(document._sources_line(child) or ""))
165
+ }
166
+ if any((root / rel).resolve() not in sources for rel in candidate.notes):
167
+ raise ValueError("child sources must support every moved note")
168
+ destination = f"{path.stem}#{handle}"
169
+ parent = _link(parent, heading, f"{path.name}#{handle}")
170
+ child = _link(child, sec.heading, f"{syn.path.name}#{sec.handle}")
171
+ for body in (parent, child):
172
+ if problems := document.validate_section(body, root):
173
+ raise ValueError("; ".join(problems))
174
+ parent_old = syn.path.read_bytes()
175
+ parent_file = edit._lf(parent_old.decode("utf-8"), syn.path.name)
176
+ parent_new = syn_edit.bumped(syn_edit.apply_part_text(parent_file, sec.handle, parent), today)
177
+ if dest:
178
+ old = path.read_bytes()
179
+ edit._lf(old.decode("utf-8"), path.name)
180
+ _, child_new, _ = syn_edit.prepare_add(path, heading, child, today)
181
+ else:
182
+ old = None
183
+ template = (common._TEMPLATES / "synthesis.md").read_text(encoding="utf-8")
184
+ child_new = syn_edit.render_new(
185
+ template, title=heading, topics=[proposal.topic], summary=heading, today=today
186
+ )
187
+ child_new = child_new.rstrip() + f"\n\n## {heading}\n\n{child}\n"
188
+ changes = {syn.path: (parent_old, parent_new.encode()), path: (old, child_new.encode())}
189
+ changes.update(synthesis._refs_note_edits(root, syn.handle, sec.handle, (sec.text, parent)))
190
+ for rel in candidate.notes:
191
+ note_path = _safe(root, root / rel)
192
+ original = note_path.read_bytes()
193
+ text = edit._lf(original.decode("utf-8"), rel)
194
+ stamp = units.note_fingerprint(child, common._note_target(rel))
195
+ changes[note_path] = (original, edit._set_part_of(text, destination, stamp).encode())
196
+ return SplitPlan(sec.text, parent, child, destination, candidate.notes, conflicts, changes)
@@ -0,0 +1,230 @@
1
+ """Recoverable split groups and their private exact-undo receipts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import fcntl
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import re
11
+ import uuid
12
+ from pathlib import Path
13
+ from typing import TYPE_CHECKING
14
+
15
+ from memory_cli.core import jobs, safe_io
16
+ from memory_cli.core.file_journal import FileJournal
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import Callable
20
+
21
+ from memory_cli.commands.split_plan import SplitPlan
22
+
23
+
24
+ _ID = re.compile(r"[0-9a-f]{32}\Z")
25
+
26
+
27
+ def _receipt(root: Path, group: str) -> Path:
28
+ if not isinstance(group, str) or not _ID.fullmatch(group):
29
+ raise ValueError("invalid split group")
30
+ path = root / ".split-history" / f"{group}.json"
31
+ safe_io.refuse_symlink_chain(root, path)
32
+ return path
33
+
34
+
35
+ def _member(root: Path, name: str) -> Path:
36
+ p = Path(name)
37
+ parts = p.parts
38
+ allowed = (
39
+ len(parts) == 2 # ruff: ignore[magic-value-comparison]
40
+ and parts[0] == "syntheses"
41
+ and p.suffix == ".md"
42
+ ) or (
43
+ len(parts) == 3 # ruff: ignore[magic-value-comparison]
44
+ and parts[0] == "knowledge"
45
+ and p.suffix == ".md"
46
+ and p.name != "README.md"
47
+ )
48
+ if (
49
+ not allowed
50
+ or p.is_absolute()
51
+ or p.as_posix() != name
52
+ or any(x in {".", ".."} or x.startswith(".") for x in parts)
53
+ ):
54
+ raise ValueError("invalid split member path")
55
+ path = root / p
56
+ safe_io.refuse_symlink_chain(root, path)
57
+ return path
58
+
59
+
60
+ def _encode(data: bytes | None) -> str | None:
61
+ return None if data is None else base64.b64encode(data).decode("ascii")
62
+
63
+
64
+ def _decode(value: object) -> bytes | None:
65
+ if value is None:
66
+ return None
67
+ if not isinstance(value, str):
68
+ raise TypeError("invalid split contents")
69
+ try:
70
+ result = base64.b64decode(value, validate=True)
71
+ except (ValueError, TypeError) as exc:
72
+ raise ValueError("invalid split contents") from exc
73
+ if _encode(result) != value:
74
+ raise ValueError("invalid split contents")
75
+ return result
76
+
77
+
78
+ def _read_receipt( # ruff: ignore[complex-structure]
79
+ root: Path, group: str
80
+ ) -> tuple[dict, dict[Path, tuple[bytes | None, bytes | None]]]:
81
+ data = json.loads(_receipt(root, group).read_text(encoding="utf-8"))
82
+ if not isinstance(data, dict):
83
+ raise TypeError("invalid split receipt")
84
+ if (
85
+ data.get("version") != 1
86
+ or data.get("group") != group
87
+ or data.get("state") not in {"applied", "undone"}
88
+ or not isinstance(data.get("entries"), list)
89
+ or not data["entries"]
90
+ ):
91
+ raise ValueError("invalid split receipt")
92
+ changes = {}
93
+ for row in data["entries"]:
94
+ if (
95
+ not isinstance(row, dict)
96
+ or set(row) != {"path", "original", "after", "digest"}
97
+ or not isinstance(row["path"], str)
98
+ ):
99
+ raise ValueError("invalid split receipt entry")
100
+ path = _member(root, row["path"])
101
+ if path in changes:
102
+ raise ValueError("duplicate split member")
103
+ original, after = _decode(row["original"]), _decode(row["after"])
104
+ digest = None if after is None else hashlib.sha256(after).hexdigest()
105
+ if row["digest"] != digest:
106
+ raise ValueError("invalid split digest")
107
+ changes[path] = (original, after)
108
+ return data, changes
109
+
110
+
111
+ def _write(journal: FileJournal, changes: dict[Path, tuple[bytes | None, bytes | None]]) -> None:
112
+ journal.publish(changes)
113
+ try: # ruff: ignore[too-many-statements-in-try-clause]
114
+ for path, (_, after) in changes.items():
115
+ safe_io.refuse_symlink_chain(journal.root, path)
116
+ if after is None:
117
+ path.unlink()
118
+ else:
119
+ private = path.parent == journal.root / ".split-history"
120
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700 if private else 0o777)
121
+ if private:
122
+ os.chmod(path.parent, 0o700)
123
+ safe_io.replace_file(path, after, mode=0o600 if private else None)
124
+ except Exception:
125
+ try:
126
+ journal.rollback()
127
+ journal.clear()
128
+ except Exception as exc:
129
+ raise OSError("split recovery pending after rollback failure") from exc
130
+ raise
131
+ journal.clear()
132
+
133
+
134
+ def apply_split( # ruff: ignore[complex-structure]
135
+ root: Path, prepare: Callable[[], SplitPlan], group: str | None = None
136
+ ) -> str:
137
+ if group is not None:
138
+ _receipt(root, group)
139
+ journal = FileJournal(root, ".split-recovery")
140
+ with journal.locked():
141
+ if journal.pending():
142
+ raise FileExistsError("split recovery is pending")
143
+ plan = prepare()
144
+ if plan.conflicts:
145
+ raise ValueError("split has conflicts")
146
+ entries = []
147
+ for path, (original, after) in plan.changes.items():
148
+ relative = path.relative_to(root).as_posix()
149
+ if _member(root, relative) != path:
150
+ raise ValueError("invalid split member")
151
+ entries.append({
152
+ "path": relative,
153
+ "original": _encode(original),
154
+ "after": _encode(after),
155
+ "digest": None if after is None else hashlib.sha256(after).hexdigest(),
156
+ })
157
+ if not entries:
158
+ raise ValueError("empty split")
159
+ group = uuid.uuid4().hex if group is None else group
160
+ receipt = _receipt(root, group)
161
+ if receipt.exists():
162
+ raise FileExistsError(f"split group already used: {group}")
163
+ contents = json.dumps({
164
+ "version": 1,
165
+ "group": group,
166
+ "state": "applied",
167
+ "entries": entries,
168
+ }).encode()
169
+ _write(journal, {**plan.changes, receipt: (None, contents)})
170
+ return group
171
+
172
+
173
+ def undo_split(root: Path, group: str) -> None:
174
+ journal = FileJournal(root, ".split-recovery")
175
+ with journal.locked():
176
+ if journal.pending():
177
+ raise FileExistsError("split recovery is pending")
178
+ receipt = _receipt(root, group)
179
+ old = journal.read_original(receipt)
180
+ data, changes = _read_receipt(root, group)
181
+ if data["state"] != "applied":
182
+ raise ValueError("split already undone")
183
+ data["state"] = "undone"
184
+ new = json.dumps(data).encode()
185
+ _write(
186
+ journal,
187
+ {
188
+ **{path: (after, original) for path, (original, after) in changes.items()},
189
+ receipt: (old, new),
190
+ },
191
+ )
192
+
193
+
194
+ def recover_split(root: Path) -> bool:
195
+ journal = FileJournal(root, ".split-recovery")
196
+ with journal.locked():
197
+ if not journal.pending():
198
+ return False
199
+ journal.rollback()
200
+ journal.clear()
201
+ return True
202
+
203
+
204
+ def split_status(root: Path) -> tuple[bool, list[str]]: # ruff: ignore[complex-structure]
205
+ journal = FileJournal(root, ".split-recovery")
206
+ lock = journal.folder / jobs.LOCK_NAME
207
+ safe_io.refuse_symlink_chain(root, lock)
208
+ try:
209
+ fd = os.open(lock, os.O_RDONLY | os.O_NOFOLLOW)
210
+ except FileNotFoundError:
211
+ return False, []
212
+ try:
213
+ try:
214
+ fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
215
+ except BlockingIOError as exc:
216
+ raise BlockingIOError("another file operation or recovery is running") from exc
217
+ if journal.pending():
218
+ return True, []
219
+ folder = root / ".split-history"
220
+ safe_io.refuse_symlink_chain(root, folder)
221
+ groups = []
222
+ if folder.exists():
223
+ for path in sorted(folder.glob("*.json")):
224
+ group = path.stem
225
+ data, _ = _read_receipt(root, group)
226
+ if data["state"] == "applied":
227
+ groups.append(group)
228
+ return False, groups
229
+ finally:
230
+ os.close(fd)