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.
- memory_cli/__init__.py +1 -0
- memory_cli/__main__.py +49 -0
- memory_cli/capture/__init__.py +7 -0
- memory_cli/capture/codex_rollout.py +164 -0
- memory_cli/capture/event_lines.py +66 -0
- memory_cli/capture/extract.py +458 -0
- memory_cli/capture/state.py +183 -0
- memory_cli/commands/__init__.py +21 -0
- memory_cli/commands/admin.py +363 -0
- memory_cli/commands/common.py +609 -0
- memory_cli/commands/curate.py +1189 -0
- memory_cli/commands/diagnostics.py +126 -0
- memory_cli/commands/edit.py +1282 -0
- memory_cli/commands/hooks.py +730 -0
- memory_cli/commands/import_recovery.py +45 -0
- memory_cli/commands/install.py +152 -0
- memory_cli/commands/integrate.py +480 -0
- memory_cli/commands/memory.py +2152 -0
- memory_cli/commands/read.py +1290 -0
- memory_cli/commands/sources.py +766 -0
- memory_cli/commands/split.py +97 -0
- memory_cli/commands/split_plan.py +196 -0
- memory_cli/commands/split_transaction.py +230 -0
- memory_cli/commands/synthesis.py +1122 -0
- memory_cli/core/__init__.py +16 -0
- memory_cli/core/auto_state.py +30 -0
- memory_cli/core/codex_pass.py +109 -0
- memory_cli/core/config.py +87 -0
- memory_cli/core/file_journal.py +163 -0
- memory_cli/core/headless.py +130 -0
- memory_cli/core/jobs.py +130 -0
- memory_cli/core/resources.py +57 -0
- memory_cli/core/runner.py +398 -0
- memory_cli/core/safe_io.py +155 -0
- memory_cli/core/store_git.py +407 -0
- memory_cli/core/yaml_load.py +14 -0
- memory_cli/corroborate/__init__.py +11 -0
- memory_cli/corroborate/cli.py +267 -0
- memory_cli/corroborate/decide.py +893 -0
- memory_cli/corroborate/digest.py +425 -0
- memory_cli/corroborate/fill.py +744 -0
- memory_cli/corroborate/job.py +15 -0
- memory_cli/corroborate/reword.py +446 -0
- memory_cli/corroborate/run.py +1142 -0
- memory_cli/corroborate/state.py +300 -0
- memory_cli/digest/__init__.py +4 -0
- memory_cli/digest/lessons.py +483 -0
- memory_cli/entry/__init__.py +12 -0
- memory_cli/entry/auto.py +660 -0
- memory_cli/entry/capture.py +1403 -0
- memory_cli/entry/corroborate.py +214 -0
- memory_cli/entry/integrate.py +684 -0
- memory_cli/entry/integrate_self_check.py +203 -0
- memory_cli/entry/research.py +9 -0
- memory_cli/entry/settle.py +614 -0
- memory_cli/entry/split_auto.py +460 -0
- memory_cli/entry/synthesize.py +22 -0
- memory_cli/integrate/__init__.py +9 -0
- memory_cli/integrate/answers.py +42 -0
- memory_cli/integrate/briefs/check-brief.md +16 -0
- memory_cli/integrate/briefs/place-brief.md +26 -0
- memory_cli/integrate/log.py +43 -0
- memory_cli/integrate/plan.py +125 -0
- memory_cli/integrate/rows.py +99 -0
- memory_cli/integrate/state.py +158 -0
- memory_cli/integrate/undo.py +143 -0
- memory_cli/mem.py +1180 -0
- memory_cli/memories/__init__.py +16 -0
- memory_cli/memories/fingerprints.py +51 -0
- memory_cli/memories/journal.py +93 -0
- memory_cli/memories/locations.py +282 -0
- memory_cli/memories/matching.py +451 -0
- memory_cli/memories/model.py +205 -0
- memory_cli/memories/parse.py +237 -0
- memory_cli/memories/records.py +266 -0
- memory_cli/memories/rules.py +291 -0
- memory_cli/memories/sightings.py +314 -0
- memory_cli/memories/terms.py +148 -0
- memory_cli/memories/write.py +358 -0
- memory_cli/notes/__init__.py +13 -0
- memory_cli/notes/check.py +806 -0
- memory_cli/notes/due.py +260 -0
- memory_cli/notes/fields.py +217 -0
- memory_cli/notes/index.py +230 -0
- memory_cli/notes/links.py +170 -0
- memory_cli/notes/note.py +222 -0
- memory_cli/notes/search.py +391 -0
- memory_cli/notes/split_candidates.py +72 -0
- memory_cli/research/__init__.py +5 -0
- memory_cli/research/checks.py +1065 -0
- memory_cli/research/pipeline.py +952 -0
- memory_cli/session/__init__.py +5 -0
- memory_cli/session/handoff.py +139 -0
- memory_cli/session/notices.py +111 -0
- memory_cli/settle/__init__.py +5 -0
- memory_cli/settle/state.py +111 -0
- memory_cli/settle/verdicts.py +693 -0
- memory_cli/split/briefs/checker-brief.md +5 -0
- memory_cli/split/briefs/editor-brief.md +20 -0
- memory_cli/syntheses/__init__.py +8 -0
- memory_cli/syntheses/document.py +400 -0
- memory_cli/syntheses/edit.py +581 -0
- memory_cli/syntheses/project.py +384 -0
- memory_cli/syntheses/split_conservation.py +50 -0
- memory_cli/syntheses/units.py +427 -0
- memory_cli/synthesize/__init__.py +9 -0
- memory_cli/synthesize/backfill.py +431 -0
- memory_cli/synthesize/briefs/backfill-brief.md +26 -0
- memory_cli/synthesize/briefs/checker-brief.md +13 -0
- memory_cli/synthesize/briefs/fixer-brief.md +19 -0
- memory_cli/synthesize/briefs/memory-brief.md +30 -0
- memory_cli/synthesize/briefs/settle-brief.md +32 -0
- memory_cli/synthesize/briefs/verdict-brief.md +50 -0
- memory_cli/synthesize/briefs/web-brief.md +33 -0
- memory_cli/synthesize/cli.py +311 -0
- memory_cli/synthesize/pipeline.py +764 -0
- memory_cli/synthesize/references.py +164 -0
- memory_cli/synthesize/run.py +150 -0
- memory_cli/synthesize/topics.py +528 -0
- memory_cli/templates/knowledge.md +23 -0
- memory_cli/templates/literature.md +25 -0
- memory_cli/templates/research.md +23 -0
- memory_cli/templates/synthesis.md +6 -0
- memory_cli-0.1.0.dist-info/METADATA +102 -0
- memory_cli-0.1.0.dist-info/RECORD +128 -0
- memory_cli-0.1.0.dist-info/WHEEL +4 -0
- memory_cli-0.1.0.dist-info/entry_points.txt +9 -0
- memory_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Placement rows a model session proposed, checked against what the session was offered.
|
|
2
|
+
|
|
3
|
+
The answer is data: a row is kept only when every field matches an offered note, part and fingerprint.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
from typing import TYPE_CHECKING, NamedTuple
|
|
10
|
+
|
|
11
|
+
from memory_cli.integrate.rows import row_of
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from collections.abc import Mapping, Sequence
|
|
15
|
+
|
|
16
|
+
from memory_cli.integrate.rows import Row
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class PartInfo(NamedTuple):
|
|
20
|
+
fingerprint: str
|
|
21
|
+
units: int
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Offered(NamedTuple):
|
|
25
|
+
"""What the session saw: note handles, and parts keyed `s:HANDLE#SECTION`."""
|
|
26
|
+
|
|
27
|
+
notes: frozenset[str]
|
|
28
|
+
parts: Mapping[str, PartInfo]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _refusal(row: Row, offered: Offered, placed: set[str]) -> str | None:
|
|
32
|
+
if row.note not in offered.notes:
|
|
33
|
+
return f"{row.note}: not offered"
|
|
34
|
+
part = offered.parts.get(row.target)
|
|
35
|
+
if part is None:
|
|
36
|
+
return f"{row.note}: part not offered"
|
|
37
|
+
if row.fingerprint != part.fingerprint:
|
|
38
|
+
return f"{row.note}: part changed since it was read"
|
|
39
|
+
if row.unit is not None and not 1 <= row.unit <= part.units:
|
|
40
|
+
return f"{row.note}: no such unit {row.unit}"
|
|
41
|
+
if row.note in placed:
|
|
42
|
+
return f"{row.note}: placed twice"
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def placement_rows(lines: Sequence[str], offered: Offered) -> tuple[list[Row], list[str]]:
|
|
47
|
+
"""(kept rows, one refusal line per dropped row); `none` and `#` lines produce nothing."""
|
|
48
|
+
kept: list[Row] = []
|
|
49
|
+
refused: list[str] = []
|
|
50
|
+
placed: set[str] = set()
|
|
51
|
+
for line in lines:
|
|
52
|
+
text = line.strip()
|
|
53
|
+
if text == "none" or text.startswith("#"):
|
|
54
|
+
continue
|
|
55
|
+
row = row_of(text)
|
|
56
|
+
if row is None:
|
|
57
|
+
refused.append("malformed row")
|
|
58
|
+
continue
|
|
59
|
+
if reason := _refusal(row, offered, placed):
|
|
60
|
+
refused.append(reason)
|
|
61
|
+
continue
|
|
62
|
+
placed.add(row.note)
|
|
63
|
+
kept.append(row)
|
|
64
|
+
return kept, refused
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def offered_of(cand: dict) -> Offered:
|
|
68
|
+
"""What a candidate of `mem synthesis integrate --candidates` offered the session: its notes and parts."""
|
|
69
|
+
syn = cand["synthesis"]
|
|
70
|
+
return Offered(
|
|
71
|
+
frozenset(n["handle"] for n in cand["notes"]),
|
|
72
|
+
{
|
|
73
|
+
f"s:{syn}#{p['section']}": PartInfo(p["fingerprint"], len(p["units"]))
|
|
74
|
+
for p in cand["parts"]
|
|
75
|
+
},
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
_LABEL = re.compile(r"\s*row:\s*", re.IGNORECASE)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class _Scan(NamedTuple):
|
|
83
|
+
accepted: list[Row]
|
|
84
|
+
none: bool # a `none` line came
|
|
85
|
+
prose: bool # a line that is not row-shaped (no ` | `): a header or a sentence
|
|
86
|
+
ignored: list[str]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _scan(rows: list[Row], check_answer: str) -> _Scan:
|
|
90
|
+
"""The check answer read line by line: a row-shaped stray line (a cut row, a row not proposed) is ignored; a
|
|
91
|
+
prose line (no ` | `, or a `#` heading) is recorded, because a heading such as "Rejected:" may sit above rows the
|
|
92
|
+
session refused. Limit: a heading that holds ` | ` is not caught; it matters only if a refused row is repeated
|
|
93
|
+
exactly under it."""
|
|
94
|
+
accepted: list[Row] = []
|
|
95
|
+
none = prose = False
|
|
96
|
+
ignored: list[str] = []
|
|
97
|
+
for raw in check_answer.splitlines():
|
|
98
|
+
text = raw.strip()
|
|
99
|
+
if not text or text.startswith("```"):
|
|
100
|
+
continue
|
|
101
|
+
if text == "none":
|
|
102
|
+
none = True
|
|
103
|
+
continue
|
|
104
|
+
row = row_of(_LABEL.sub("", text, count=1) if _LABEL.match(text) else text)
|
|
105
|
+
if row is not None and row in rows:
|
|
106
|
+
accepted.append(row)
|
|
107
|
+
else:
|
|
108
|
+
ignored.append(text)
|
|
109
|
+
prose = prose or " | " not in text
|
|
110
|
+
return _Scan(accepted, none, prose, ignored)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def agreed(rows: list[Row], check_answer: str) -> list[Row] | None:
|
|
114
|
+
"""The rows the check answer lists too; stray lines (a `row:` label is stripped first) are ignored, so only a
|
|
115
|
+
row that was proposed can be kept. None when the answer decided nothing (no row and no `none`), `none` comes
|
|
116
|
+
with a row, or a line is prose rather than a row."""
|
|
117
|
+
scan = _scan(rows, check_answer)
|
|
118
|
+
if scan.prose or (scan.none and scan.accepted) or not (scan.none or scan.accepted):
|
|
119
|
+
return None
|
|
120
|
+
return [row for row in rows if row in scan.accepted]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def ignored_lines(rows: list[Row], check_answer: str) -> list[str]:
|
|
124
|
+
"""The lines of the check answer `agreed` ignored, for the log."""
|
|
125
|
+
return _scan(rows, check_answer).ignored
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""The integrate rows: one line says which note joins which part of a synthesis, and how."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import TYPE_CHECKING, NamedTuple
|
|
7
|
+
|
|
8
|
+
from memory_cli.memories.terms import forbidden_line, secret_in
|
|
9
|
+
from memory_cli.syntheses.units import units
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
|
|
14
|
+
_FIELDS = 4
|
|
15
|
+
_NOTE = re.compile(r"[^\s|]+")
|
|
16
|
+
_TARGET = re.compile(r"s:[a-z0-9-]+#[a-z0-9-]+")
|
|
17
|
+
_ACTION = re.compile(r"append|unit ([1-9][0-9]*)")
|
|
18
|
+
_FINGERPRINT = re.compile(r"[0-9a-f]{10}")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Row(NamedTuple):
|
|
22
|
+
note: str
|
|
23
|
+
target: str
|
|
24
|
+
action: str
|
|
25
|
+
unit: int | None
|
|
26
|
+
fingerprint: str
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _parse_line(line: str) -> Row | None:
|
|
30
|
+
parts = [p.strip() for p in line.split("|")]
|
|
31
|
+
if len(parts) != _FIELDS:
|
|
32
|
+
return None
|
|
33
|
+
note, target, action, fingerprint = parts
|
|
34
|
+
act = _ACTION.fullmatch(action)
|
|
35
|
+
if note.startswith("-"): # it becomes a command argument; the target always starts with `s:`
|
|
36
|
+
return None
|
|
37
|
+
if not (
|
|
38
|
+
_NOTE.fullmatch(note)
|
|
39
|
+
and _TARGET.fullmatch(target)
|
|
40
|
+
and act
|
|
41
|
+
and _FINGERPRINT.fullmatch(fingerprint)
|
|
42
|
+
):
|
|
43
|
+
return None
|
|
44
|
+
number = int(act.group(1)) if act.group(1) else None
|
|
45
|
+
return Row(note, target, "unit" if number else "append", number, fingerprint)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def parse_rows(raw: str) -> tuple[list[Row], list[str]]:
|
|
49
|
+
"""(rows, messages for the malformed lines); blank lines and `#` lines are ignored."""
|
|
50
|
+
rows: list[Row] = []
|
|
51
|
+
bad: list[str] = []
|
|
52
|
+
for n, line in enumerate(raw.splitlines(), 1):
|
|
53
|
+
text = line.strip()
|
|
54
|
+
if not text or text.startswith("#"):
|
|
55
|
+
continue
|
|
56
|
+
row = _parse_line(text)
|
|
57
|
+
if row is None:
|
|
58
|
+
bad.append(
|
|
59
|
+
f"line {n}: not `NOTE | s:HANDLE#SECTION | append | FINGERPRINT` or `... | unit N | ...`: {text}"
|
|
60
|
+
)
|
|
61
|
+
else:
|
|
62
|
+
rows.append(row)
|
|
63
|
+
return rows, bad
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def row_of(line: str) -> Row | None:
|
|
67
|
+
"""The row when the line is exactly one well-formed row, else None."""
|
|
68
|
+
rows, bad = parse_rows(line)
|
|
69
|
+
return rows[0] if len(rows) == 1 and not bad else None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def row_line(row: Row) -> str:
|
|
73
|
+
"""The row as a line of a rows file, built from its parsed fields (the inverse of `row_of`)."""
|
|
74
|
+
action = "append" if row.unit is None else f"unit {row.unit}"
|
|
75
|
+
return f"{row.note} | {row.target} | {action} | {row.fingerprint}"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _refusal(text: str, env: Mapping[str, str]) -> str | None:
|
|
79
|
+
if secret_in([text]):
|
|
80
|
+
return "secret in the claim"
|
|
81
|
+
if forbidden_line([text], env) is not None:
|
|
82
|
+
return "forbidden term in the claim"
|
|
83
|
+
if text.endswith(":"):
|
|
84
|
+
return "claim ends with a colon"
|
|
85
|
+
if "[" in text or "]" in text:
|
|
86
|
+
return "claim holds brackets"
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def check_claim(claim: str, env: Mapping[str, str]) -> str | None:
|
|
91
|
+
"""Why a claim cannot be joined to a synthesis, or None."""
|
|
92
|
+
text = claim.strip()
|
|
93
|
+
if not text:
|
|
94
|
+
return "claim is empty"
|
|
95
|
+
if reason := _refusal(text, env):
|
|
96
|
+
return reason
|
|
97
|
+
if len(units(text)[0]) != 1:
|
|
98
|
+
return "claim is not one sentence"
|
|
99
|
+
return None
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""What `mem-integrate` remembers between and within runs: the done list and the record of each run.
|
|
2
|
+
|
|
3
|
+
Both live in a state folder: `done.json` (`{note handle: digest}`) and `<run id>/record.json`. A file that is
|
|
4
|
+
missing or unreadable reads as empty, so a damaged state costs a repeated check, never a failed run.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from dataclasses import asdict, dataclass, field, fields
|
|
11
|
+
from typing import TYPE_CHECKING
|
|
12
|
+
|
|
13
|
+
from memory_cli.core import safe_io
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
type Done = dict[str, str]
|
|
19
|
+
|
|
20
|
+
DONE_FILE = "done.json"
|
|
21
|
+
RECORD_FILE = "record.json"
|
|
22
|
+
INTENT_FILE = "intent.json"
|
|
23
|
+
STATE_MODE = 0o600
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class GroupRecord:
|
|
28
|
+
"""One group a command wrote: the files it changed (`s:<handle>` for a synthesis, a note handle for a note)."""
|
|
29
|
+
|
|
30
|
+
handles: list[str]
|
|
31
|
+
group_id: str
|
|
32
|
+
kind: str # `integrate` today
|
|
33
|
+
undone: bool = False
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class RunRecord:
|
|
38
|
+
run_id: str
|
|
39
|
+
started: str
|
|
40
|
+
groups: list[GroupRecord] = field(default_factory=list)
|
|
41
|
+
cost: float = 0.0
|
|
42
|
+
failures: list[str] = field(default_factory=list)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Intent:
|
|
47
|
+
"""An apply about to run: its reserved group, the synthesis, the notes (handle, digest) and the run."""
|
|
48
|
+
|
|
49
|
+
group: str
|
|
50
|
+
synthesis: str
|
|
51
|
+
notes: list[dict[str, str]]
|
|
52
|
+
run_id: str
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class IntentError(Exception):
|
|
56
|
+
"""The intent file exists but is not a valid intent."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _write_json(path: Path, data: object) -> None:
|
|
60
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
61
|
+
safe_io.replace_file(path, json.dumps(data, indent=2).encode("utf-8"), mode=STATE_MODE)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _read_json(path: Path) -> object:
|
|
65
|
+
try:
|
|
66
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
67
|
+
except (OSError, ValueError):
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def read_done(folder: Path) -> Done:
|
|
72
|
+
data = _read_json(folder / DONE_FILE)
|
|
73
|
+
if not isinstance(data, dict):
|
|
74
|
+
return {}
|
|
75
|
+
return {k: v for k, v in data.items() if isinstance(k, str) and isinstance(v, str)}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def write_done(folder: Path, done: Done) -> None:
|
|
79
|
+
_write_json(folder / DONE_FILE, done)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def is_done(done: Done, handle: str, digest: str) -> bool:
|
|
83
|
+
"""True when the note was handled at exactly this digest; an edited note is offered again."""
|
|
84
|
+
return done.get(handle) == digest
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def mark_done(folder: Path, handle: str, digest: str) -> None:
|
|
88
|
+
done = read_done(folder)
|
|
89
|
+
done[handle] = digest
|
|
90
|
+
write_done(folder, done)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def write_record(folder: Path, record: RunRecord) -> None:
|
|
94
|
+
"""Rewrite the run's record; the runner calls it after every applied command."""
|
|
95
|
+
_write_json(folder / record.run_id / RECORD_FILE, asdict(record))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _known[T](cls: type[T], data: dict) -> dict:
|
|
99
|
+
"""`data` without the keys `cls` does not have: a record written by a newer version still reads."""
|
|
100
|
+
names = {f.name for f in fields(cls)} # type: ignore[arg-type]
|
|
101
|
+
return {k: v for k, v in data.items() if k in names}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def read_record(folder: Path, run_id: str) -> RunRecord | None:
|
|
105
|
+
data = _read_json(folder / run_id / RECORD_FILE)
|
|
106
|
+
if not isinstance(data, dict):
|
|
107
|
+
return None
|
|
108
|
+
try:
|
|
109
|
+
groups = [GroupRecord(**_known(GroupRecord, g)) for g in data.pop("groups", [])]
|
|
110
|
+
return RunRecord(**_known(RunRecord, data), groups=groups)
|
|
111
|
+
except (TypeError, AttributeError):
|
|
112
|
+
return None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def last_run_id(folder: Path) -> str | None:
|
|
116
|
+
"""The newest run in the state folder that has a record (run ids start with their start time)."""
|
|
117
|
+
try:
|
|
118
|
+
runs = [p.name for p in folder.iterdir() if (p / RECORD_FILE).is_file()]
|
|
119
|
+
except OSError:
|
|
120
|
+
return None
|
|
121
|
+
return max(runs, default=None)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def write_intent(folder: Path, intent: Intent) -> None:
|
|
125
|
+
"""Writes the intent; an existing one is never overwritten (`IntentError`): it is the only record of its apply."""
|
|
126
|
+
if (folder / INTENT_FILE).exists():
|
|
127
|
+
raise IntentError("an unresolved intent file exists")
|
|
128
|
+
_write_json(folder / INTENT_FILE, asdict(intent))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def read_intent(folder: Path) -> Intent | None:
|
|
132
|
+
"""The pending intent; None when there is none, `IntentError` when the file is not a valid intent."""
|
|
133
|
+
path = folder / INTENT_FILE
|
|
134
|
+
if not path.exists():
|
|
135
|
+
return None
|
|
136
|
+
try:
|
|
137
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
138
|
+
notes = data["notes"]
|
|
139
|
+
ok = (
|
|
140
|
+
isinstance(data, dict)
|
|
141
|
+
and all(isinstance(data[k], str) for k in ("group", "synthesis", "run_id"))
|
|
142
|
+
and isinstance(notes, list)
|
|
143
|
+
and all(
|
|
144
|
+
isinstance(n, dict)
|
|
145
|
+
and isinstance(n.get("handle"), str)
|
|
146
|
+
and isinstance(n.get("digest"), str)
|
|
147
|
+
for n in notes
|
|
148
|
+
)
|
|
149
|
+
)
|
|
150
|
+
except (OSError, ValueError, KeyError, TypeError) as exc:
|
|
151
|
+
raise IntentError(str(exc)) from exc
|
|
152
|
+
if not ok:
|
|
153
|
+
raise IntentError("unexpected shape")
|
|
154
|
+
return Intent(data["group"], data["synthesis"], notes, data["run_id"])
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def delete_intent(folder: Path) -> None:
|
|
158
|
+
(folder / INTENT_FILE).unlink(missing_ok=True)
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Undoing a `mem-integrate` run: a group is undone only while it is still the newest change of every file it wrote.
|
|
2
|
+
|
|
3
|
+
`mem restore <handle>` undoes the newest logged change of a file, not a named group, so `undo` first proves from the
|
|
4
|
+
curation log that the group is that newest change everywhere (`newest_is_group`) and only then calls it; with a later
|
|
5
|
+
change anywhere, nothing is restored. Groups go newest first; the first refusal stops the undo.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import re
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import TYPE_CHECKING, Any
|
|
14
|
+
|
|
15
|
+
from memory_cli.integrate import state as run_state
|
|
16
|
+
from memory_cli.integrate.log import log_entries
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from collections.abc import Callable
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from subprocess import CompletedProcess
|
|
22
|
+
|
|
23
|
+
from memory_cli.integrate.state import GroupRecord
|
|
24
|
+
|
|
25
|
+
type Mem = Callable[..., CompletedProcess[str]]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class UndoResult:
|
|
30
|
+
"""What an undo did: groups undone now, groups still to undo, and why it stopped (None when it did not)."""
|
|
31
|
+
|
|
32
|
+
undone: int = 0
|
|
33
|
+
remaining: int = 0
|
|
34
|
+
refusal: str | None = None
|
|
35
|
+
already_restored: list[str] = field(
|
|
36
|
+
default_factory=list
|
|
37
|
+
) # group ids a hand `mem restore` had undone
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _entries(store: Path) -> list[tuple[bool, dict[str, Any]]]:
|
|
41
|
+
"""The log entries that hold a text (`before`), oldest first, with whether a restore marker has cancelled them."""
|
|
42
|
+
return [(gone, e) for gone, e in log_entries(store) if isinstance(e.get("before"), str)]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _live_entries(store: Path) -> list[dict[str, Any]]:
|
|
46
|
+
"""The log as a stack: the entries no restore marker has cancelled, oldest first."""
|
|
47
|
+
return [e for gone, e in _entries(store) if not gone]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _written(store: Path, group: GroupRecord) -> list[dict[str, Any]]:
|
|
51
|
+
"""The group's live log entries, one per file change."""
|
|
52
|
+
return [e for e in _live_entries(store) if e.get("group") == group.group_id]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def newest_is_group(store: Path, group: GroupRecord) -> str | None:
|
|
56
|
+
"""None when every file the group wrote (found in the log by its id) has that group's entry as its newest live
|
|
57
|
+
log entry (restore markers cancel the entry they undid) and is still the text that entry left; otherwise the
|
|
58
|
+
refusal, naming the file."""
|
|
59
|
+
entries = _live_entries(store)
|
|
60
|
+
newest = {e["handle"]: e for e in entries} # the last live entry of a file wins
|
|
61
|
+
written = [e for e in entries if e.get("group") == group.group_id]
|
|
62
|
+
if not written:
|
|
63
|
+
return f"the curation log has no entry of group {group.group_id}"
|
|
64
|
+
for entry in written:
|
|
65
|
+
handle = entry["handle"]
|
|
66
|
+
if newest[handle].get("group") != group.group_id:
|
|
67
|
+
return f"{handle} has a newer logged change than group {group.group_id}"
|
|
68
|
+
try:
|
|
69
|
+
current = hashlib.sha256((store / handle).read_bytes()).hexdigest()
|
|
70
|
+
except OSError:
|
|
71
|
+
return f"{handle} is missing, so group {group.group_id} cannot be undone"
|
|
72
|
+
if current != entry.get("after"):
|
|
73
|
+
return f"{handle} changed since group {group.group_id}"
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
RESTORED = re.compile(r"restored to before (\S+) of \S+ \((\d+) files\)")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _restore(store: Path, group: GroupRecord, mem: Mem) -> str | None:
|
|
81
|
+
"""`mem restore` of the group's synthesis (it undoes the whole group); the refusal text when it fails or when its
|
|
82
|
+
output shows it undid something other than this group (a `mem` command run in between), with nothing marked."""
|
|
83
|
+
handle = group.handles[0]
|
|
84
|
+
expected = len(_written(store, group))
|
|
85
|
+
done = mem("restore", handle)
|
|
86
|
+
if done.returncode:
|
|
87
|
+
return (
|
|
88
|
+
f"mem restore {handle} failed, so group {group.group_id} may be partly restored: "
|
|
89
|
+
f"{(done.stderr or done.stdout).strip()}"
|
|
90
|
+
)
|
|
91
|
+
found = RESTORED.search(done.stdout)
|
|
92
|
+
if found is None or found[1] != group.kind or int(found[2]) != expected:
|
|
93
|
+
return (
|
|
94
|
+
f"mem restore {handle} undid another change instead of group {group.group_id} "
|
|
95
|
+
f"(a mem command changed it in between; it printed: {done.stdout.strip()!r}): "
|
|
96
|
+
"check the log and restore by hand"
|
|
97
|
+
)
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _already_or_partial(store: Path, group: GroupRecord) -> tuple[bool, str | None]:
|
|
102
|
+
"""(True, None) when every log entry of the group is cancelled by a restore marker (it is restored already);
|
|
103
|
+
(False, refusal) when only some are (restoring now would undo an older change of the synthesis); (False, None)
|
|
104
|
+
when none is, or the log has no entry of the group (`newest_is_group` then decides)."""
|
|
105
|
+
mine = [(gone, e) for gone, e in _entries(store) if e.get("group") == group.group_id]
|
|
106
|
+
live = [e["handle"] for gone, e in mine if not gone]
|
|
107
|
+
if not mine or len(live) == len(mine):
|
|
108
|
+
return False, None
|
|
109
|
+
if not live:
|
|
110
|
+
return True, None
|
|
111
|
+
return False, (
|
|
112
|
+
f"group {group.group_id} is partly restored (a restore stopped half way); "
|
|
113
|
+
f"still live: {', '.join(live)}; finish by hand with mem restore <handle> for each, "
|
|
114
|
+
"then run --undo again"
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _undo_group(store: Path, group: GroupRecord, mem: Mem, result: UndoResult) -> str | None:
|
|
119
|
+
"""Undoes or recognizes as restored one group and marks nothing; the refusal text or None."""
|
|
120
|
+
restored, refusal = _already_or_partial(store, group)
|
|
121
|
+
if restored:
|
|
122
|
+
result.already_restored.append(group.group_id)
|
|
123
|
+
return None
|
|
124
|
+
return refusal or newest_is_group(store, group) or _restore(store, group, mem)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def undo(store: Path, folder: Path, run_id: str, mem: Mem) -> UndoResult:
|
|
128
|
+
"""Undoes the run's groups newest first, marking each in the record; a second call continues with the rest."""
|
|
129
|
+
record = run_state.read_record(folder, run_id)
|
|
130
|
+
if record is None:
|
|
131
|
+
return UndoResult(refusal=f"no record of run {run_id}")
|
|
132
|
+
todo = [g for g in reversed(record.groups) if not g.undone]
|
|
133
|
+
result = UndoResult(remaining=len(todo))
|
|
134
|
+
for group in todo:
|
|
135
|
+
refusal = _undo_group(store, group, mem, result)
|
|
136
|
+
if refusal:
|
|
137
|
+
result.refusal = refusal
|
|
138
|
+
return result
|
|
139
|
+
group.undone = True
|
|
140
|
+
run_state.write_record(folder, record)
|
|
141
|
+
result.undone += 1
|
|
142
|
+
result.remaining -= 1
|
|
143
|
+
return result
|