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,384 @@
|
|
|
1
|
+
"""Project syntheses: long-lived documents in a project's `.memory/syntheses/`, each part stamped with the commit it
|
|
2
|
+
was written at, so a reader learns whether the files it covers changed since.
|
|
3
|
+
|
|
4
|
+
A project synthesis is a file named after one of `NAMES`; a part is a `## ` section whose last line is its stamp:
|
|
5
|
+
`Covers: <path>[, <path>...] | updated <YYYY-MM-DD> at <12 hex digits or no-commit>`. The tool writes the stamp.
|
|
6
|
+
`load` reads files only and never runs git; `freshness` is the only function that compares a stamp with the files.
|
|
7
|
+
Two roots: `.memory/` sits at the project root (the main worktree), git and the path checks use `worktree()`.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import datetime
|
|
13
|
+
import os
|
|
14
|
+
import posixpath
|
|
15
|
+
import re
|
|
16
|
+
import subprocess
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import TYPE_CHECKING, NamedTuple
|
|
19
|
+
|
|
20
|
+
import yaml
|
|
21
|
+
|
|
22
|
+
from memory_cli.core import safe_io
|
|
23
|
+
from memory_cli.core.yaml_load import safe_load
|
|
24
|
+
from memory_cli.memories.model import PROJECT_DIR
|
|
25
|
+
from memory_cli.syntheses import document, edit
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING:
|
|
28
|
+
from collections.abc import Mapping, Sequence
|
|
29
|
+
|
|
30
|
+
NAMES: tuple[str, ...] = ("organization", "plans", "pending", "conventions")
|
|
31
|
+
FRESH, CHANGED, UNKNOWN = "fresh", "changed", "unknown"
|
|
32
|
+
NO_COMMIT = "no-commit"
|
|
33
|
+
GIT_TIMEOUT = 2
|
|
34
|
+
MIN_STATUS_ENTRY = 3 # `XY ` status prefix plus at least one character of path
|
|
35
|
+
_STAMP = re.compile(
|
|
36
|
+
r"Covers: (?P<paths>[^|]+?) \| updated (?P<date>\d{4}-\d{2}-\d{2}) at (?P<commit>[0-9a-f]{12}|no-commit)"
|
|
37
|
+
)
|
|
38
|
+
_DESCRIPTIONS = {
|
|
39
|
+
FRESH: "fresh: its files are as they were when it was written",
|
|
40
|
+
CHANGED: "possibly stale: its files changed since it was written; check them before relying on it",
|
|
41
|
+
UNKNOWN: "unknown: not a git project or its commit is gone; check the files",
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Stamp(NamedTuple):
|
|
46
|
+
paths: tuple[str, ...]
|
|
47
|
+
date: datetime.date
|
|
48
|
+
commit: str | None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Part(NamedTuple):
|
|
52
|
+
handle: str
|
|
53
|
+
heading: str
|
|
54
|
+
body: str
|
|
55
|
+
stamp: Stamp
|
|
56
|
+
line: int
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class NewPart(NamedTuple):
|
|
60
|
+
"""What `write_part` writes: the synthesis `name`, the part's heading and text, and the paths it covers."""
|
|
61
|
+
|
|
62
|
+
name: str
|
|
63
|
+
heading: str
|
|
64
|
+
body: str
|
|
65
|
+
paths: Sequence[str]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class ProjectSynthesisError(ValueError):
|
|
69
|
+
pass
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class UnavailableError(ProjectSynthesisError):
|
|
73
|
+
"""A well-formed request for a name or part that does not exist or cannot be read (exit 1, like `show s:`)."""
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
Unavailable = UnavailableError # the name mem.py uses
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def folder(memory_dir: Path) -> Path:
|
|
80
|
+
return memory_dir / document.SYNTHESES_DIR
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _render_stamp(paths: Sequence[str], date: datetime.date, commit: str | None) -> str:
|
|
84
|
+
return f"Covers: {', '.join(paths)} | updated {date.isoformat()} at {commit or NO_COMMIT}"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _parse_stamp(line: str) -> Stamp | None:
|
|
88
|
+
m = _STAMP.fullmatch(line)
|
|
89
|
+
if not m:
|
|
90
|
+
return None
|
|
91
|
+
try:
|
|
92
|
+
date = datetime.date.fromisoformat(m["date"])
|
|
93
|
+
except ValueError:
|
|
94
|
+
return None
|
|
95
|
+
commit = None if m["commit"] == NO_COMMIT else m["commit"]
|
|
96
|
+
return Stamp(tuple(m["paths"].split(", ")), date, commit)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _check_frontmatter(path: Path) -> None:
|
|
100
|
+
def fail(why: str) -> ProjectSynthesisError:
|
|
101
|
+
return ProjectSynthesisError(f"{path.name}: {why}")
|
|
102
|
+
|
|
103
|
+
try:
|
|
104
|
+
text = document._read(path)
|
|
105
|
+
except (OSError, UnicodeDecodeError) as e:
|
|
106
|
+
raise fail(f"cannot be read ({type(e).__name__})") from None
|
|
107
|
+
m = document._FRONTMATTER.match(text)
|
|
108
|
+
try:
|
|
109
|
+
meta = safe_load(m.group(1)) if m else None
|
|
110
|
+
except yaml.YAMLError:
|
|
111
|
+
meta = None
|
|
112
|
+
if not isinstance(meta, dict) or not isinstance(meta.get("title"), str):
|
|
113
|
+
raise fail("no valid frontmatter with a title")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _parse_part(
|
|
117
|
+
name: str, lines: list[str], span: tuple[int, int], heading: str, seen: list[Part]
|
|
118
|
+
) -> Part:
|
|
119
|
+
def fail(why: str) -> ProjectSynthesisError:
|
|
120
|
+
return ProjectSynthesisError(f"{name}: {why}")
|
|
121
|
+
|
|
122
|
+
i, end = span
|
|
123
|
+
content = [ln.rstrip("\r") for ln in lines[i + 1 : end]]
|
|
124
|
+
while content and not content[-1].strip():
|
|
125
|
+
content.pop()
|
|
126
|
+
stamp = _parse_stamp(content[-1]) if content else None
|
|
127
|
+
if stamp is None:
|
|
128
|
+
raise fail(f"the part `{heading}` (line {i + 1}) does not end with a stamp")
|
|
129
|
+
handle = document.section_handle(heading)
|
|
130
|
+
if not handle or any(p.handle == handle for p in seen):
|
|
131
|
+
raise fail(f"the heading `{heading}` (line {i + 1}) has an empty or repeated handle")
|
|
132
|
+
return Part(handle, heading, "\n".join(content[:-1]).strip("\n"), stamp, i + 1)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _parse(path: Path) -> list[Part]:
|
|
136
|
+
_check_frontmatter(path)
|
|
137
|
+
lines, heads = document._scan(document._read(path))
|
|
138
|
+
parts: list[Part] = []
|
|
139
|
+
for n, (i, heading) in enumerate(heads):
|
|
140
|
+
end = heads[n + 1][0] if n + 1 < len(heads) else len(lines)
|
|
141
|
+
parts.append(_parse_part(path.name, lines, (i, end), heading, parts))
|
|
142
|
+
return parts
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def load(memory_dir: Path) -> dict[str, list[Part]]:
|
|
146
|
+
"""Name -> parts of every project synthesis that exists; the first broken file raises ProjectSynthesisError."""
|
|
147
|
+
found, broken = load_each(memory_dir)
|
|
148
|
+
if broken:
|
|
149
|
+
raise ProjectSynthesisError(broken[0][1])
|
|
150
|
+
return found
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def load_each(memory_dir: Path) -> tuple[dict[str, list[Part]], list[tuple[str, str]]]:
|
|
154
|
+
"""Name -> parts, but a broken file does not stop the rest: (name -> parts of the files that load,
|
|
155
|
+
[(path under memory_dir, error message)] of the ones that do not). No git."""
|
|
156
|
+
found: dict[str, list[Part]] = {}
|
|
157
|
+
broken: list[tuple[str, str]] = []
|
|
158
|
+
if folder(memory_dir).is_symlink():
|
|
159
|
+
return found, broken
|
|
160
|
+
for name in NAMES:
|
|
161
|
+
path = folder(memory_dir) / f"{name}.md"
|
|
162
|
+
if path.is_file() and not path.is_symlink():
|
|
163
|
+
try:
|
|
164
|
+
found[name] = _parse(path)
|
|
165
|
+
except ProjectSynthesisError as exc:
|
|
166
|
+
broken.append((path.relative_to(memory_dir).as_posix(), str(exc)))
|
|
167
|
+
return found, broken
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def worktree(cwd: Path, project_root: Path, env: Mapping[str, str]) -> Path:
|
|
171
|
+
"""The working tree the session is in: the project root when MEM_PROJECT names the project, else the
|
|
172
|
+
repository's top level at `cwd` (a linked worktree is its own), else the project root."""
|
|
173
|
+
if env.get("MEM_PROJECT"):
|
|
174
|
+
return project_root
|
|
175
|
+
out = _git(cwd, "rev-parse", "--show-toplevel")
|
|
176
|
+
top = out.stdout.strip() if out else ""
|
|
177
|
+
return Path(top) if top else project_root
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _git(tree: Path, *args: str) -> subprocess.CompletedProcess | None:
|
|
181
|
+
try:
|
|
182
|
+
out = subprocess.run(
|
|
183
|
+
["git", *args],
|
|
184
|
+
cwd=tree,
|
|
185
|
+
capture_output=True,
|
|
186
|
+
text=True,
|
|
187
|
+
check=False,
|
|
188
|
+
timeout=GIT_TIMEOUT,
|
|
189
|
+
env={**os.environ, "GIT_LITERAL_PATHSPECS": "1"},
|
|
190
|
+
)
|
|
191
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
192
|
+
return None
|
|
193
|
+
return out if out.returncode == 0 else None
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def head_commit(tree: Path) -> str | None:
|
|
197
|
+
out = _git(tree, "rev-parse", "HEAD")
|
|
198
|
+
sha = out.stdout.strip()[:12] if out else ""
|
|
199
|
+
return sha if re.fullmatch(r"[0-9a-f]{12}", sha) else None
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _bad_path(p: str) -> bool:
|
|
203
|
+
if not p or p != p.strip() or p.startswith("/") or "//" in p or ".." in p.split("/"):
|
|
204
|
+
return True
|
|
205
|
+
if any(c in p for c in (",", "|", "\\", "\n")):
|
|
206
|
+
return True
|
|
207
|
+
norm = posixpath.normpath(p)
|
|
208
|
+
return norm in {"..", PROJECT_DIR} or norm.startswith((
|
|
209
|
+
"../",
|
|
210
|
+
PROJECT_DIR + "/",
|
|
211
|
+
))
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _check_paths(tree: Path, paths: Sequence[str]) -> list[str]:
|
|
215
|
+
if not paths:
|
|
216
|
+
raise ProjectSynthesisError("a part must cover at least one path")
|
|
217
|
+
clean = []
|
|
218
|
+
for p in paths:
|
|
219
|
+
if _bad_path(p):
|
|
220
|
+
raise ProjectSynthesisError(
|
|
221
|
+
f"invalid path {p!r}: relative, `/`-separated, no `,` or `|`, not in .memory/"
|
|
222
|
+
)
|
|
223
|
+
if not (tree / p).exists():
|
|
224
|
+
raise ProjectSynthesisError(f"the path {p!r} does not exist in {tree.name}")
|
|
225
|
+
clean.append(p)
|
|
226
|
+
return list(dict.fromkeys(clean))
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _frontmatter(name: str, today: datetime.date) -> str:
|
|
230
|
+
meta = {"title": name.capitalize(), "created": today.isoformat(), "updated": today.isoformat()}
|
|
231
|
+
return (
|
|
232
|
+
"---\n" + yaml.safe_dump(meta, sort_keys=False, allow_unicode=True, width=10**6) + "---\n"
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _file(memory_dir: Path, name: str) -> Path:
|
|
237
|
+
if name not in NAMES:
|
|
238
|
+
raise ProjectSynthesisError(
|
|
239
|
+
f"unknown project synthesis {name!r}; use one of: {', '.join(NAMES)}"
|
|
240
|
+
)
|
|
241
|
+
return folder(memory_dir) / f"{name}.md"
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _clean_part(heading: str, body: str) -> tuple[str, str, str]:
|
|
245
|
+
"""(heading, handle, body) of a part to write, or ProjectSynthesisError."""
|
|
246
|
+
heading = " ".join(heading.split())
|
|
247
|
+
if heading.startswith("#"):
|
|
248
|
+
raise ProjectSynthesisError(
|
|
249
|
+
"the heading must not start with `#`: the tool writes the `## `"
|
|
250
|
+
)
|
|
251
|
+
handle = document.section_handle(heading)
|
|
252
|
+
if not handle:
|
|
253
|
+
raise ProjectSynthesisError("the heading has no letters or digits")
|
|
254
|
+
return heading, handle, _check_body(edit._clean(body))
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _check_body(body: str) -> str:
|
|
258
|
+
if not body:
|
|
259
|
+
raise ProjectSynthesisError("the text is empty")
|
|
260
|
+
if document._scan("---\nx: 1\n---\n" + body)[1]:
|
|
261
|
+
raise ProjectSynthesisError(
|
|
262
|
+
"the text contains a `## ` heading: a part is one heading and its text"
|
|
263
|
+
)
|
|
264
|
+
probe = document._scan("---\nx: 1\n---\n" + body + "\n## probe")[1]
|
|
265
|
+
if not probe or probe[-1][1] != "probe":
|
|
266
|
+
raise ProjectSynthesisError("the text leaves a code fence open: close it")
|
|
267
|
+
if any(_parse_stamp(ln.rstrip()) for ln in body.split("\n")):
|
|
268
|
+
raise ProjectSynthesisError("the text contains a stamp line: the tool writes the stamp")
|
|
269
|
+
return body
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _merged(path: Path, handle: str, block: list[str], today: datetime.date) -> str:
|
|
273
|
+
"""The file's text with `block` replacing the part of `handle`, or appended when there is none."""
|
|
274
|
+
old = _parse(path)
|
|
275
|
+
lines, heads = document._scan(document._read(path))
|
|
276
|
+
same = next((p for p in old if p.handle == handle), None)
|
|
277
|
+
if same:
|
|
278
|
+
n = next(k for k, (i, _) in enumerate(heads) if i + 1 == same.line)
|
|
279
|
+
end = heads[n + 1][0] if n + 1 < len(heads) else len(lines)
|
|
280
|
+
lines[heads[n][0] : end] = [*block, ""]
|
|
281
|
+
else:
|
|
282
|
+
while lines and not lines[-1].strip():
|
|
283
|
+
lines.pop()
|
|
284
|
+
lines += ["", *block, ""]
|
|
285
|
+
return edit._bump("\n".join(lines), today)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def write_part(memory_dir: Path, worktree: Path, part: NewPart, today: datetime.date) -> str:
|
|
289
|
+
"""Create the file or add a part to it; a heading whose handle exists replaces that part in place."""
|
|
290
|
+
path = _file(memory_dir, part.name)
|
|
291
|
+
safe_io.refuse_symlink_chain(memory_dir, path)
|
|
292
|
+
heading, handle, body = _clean_part(part.heading, part.body)
|
|
293
|
+
covered = _check_paths(worktree, part.paths)
|
|
294
|
+
block = [
|
|
295
|
+
f"## {heading}",
|
|
296
|
+
"",
|
|
297
|
+
*body.split("\n"),
|
|
298
|
+
"",
|
|
299
|
+
_render_stamp(covered, today, head_commit(worktree)),
|
|
300
|
+
]
|
|
301
|
+
if path.is_file():
|
|
302
|
+
new = _merged(path, handle, block, today)
|
|
303
|
+
else:
|
|
304
|
+
folder(memory_dir).mkdir(parents=True, exist_ok=True)
|
|
305
|
+
new = _frontmatter(part.name, today) + "\n" + "\n".join(block) + "\n"
|
|
306
|
+
document._write(path, new)
|
|
307
|
+
return handle
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def confirm_part(
|
|
311
|
+
memory_dir: Path, worktree: Path, name: str, handle: str, today: datetime.date
|
|
312
|
+
) -> None:
|
|
313
|
+
"""Give a part a new stamp (today, the current commit) and leave its text as it was."""
|
|
314
|
+
path = _file(memory_dir, name)
|
|
315
|
+
safe_io.refuse_symlink_chain(memory_dir, path)
|
|
316
|
+
if not path.is_file():
|
|
317
|
+
raise ProjectSynthesisError(f"there is no project synthesis {name!r}")
|
|
318
|
+
part = next((p for p in _parse(path) if p.handle == handle), None)
|
|
319
|
+
if part is None:
|
|
320
|
+
raise ProjectSynthesisError(f"no part {handle!r} in {name}")
|
|
321
|
+
try:
|
|
322
|
+
_check_paths(worktree, part.stamp.paths)
|
|
323
|
+
except ProjectSynthesisError as e:
|
|
324
|
+
raise ProjectSynthesisError(
|
|
325
|
+
f"{e}; confirming would stamp a false fresh: write the part again with new paths"
|
|
326
|
+
) from None
|
|
327
|
+
lines, heads = document._scan(document._read(path))
|
|
328
|
+
n = next(k for k, (i, _) in enumerate(heads) if i + 1 == part.line)
|
|
329
|
+
end = heads[n + 1][0] if n + 1 < len(heads) else len(lines)
|
|
330
|
+
last = max(k for k in range(heads[n][0] + 1, end) if lines[k].strip())
|
|
331
|
+
lines[last] = _render_stamp(part.stamp.paths, today, head_commit(worktree))
|
|
332
|
+
document._write(path, edit._bump("\n".join(lines), today))
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _names(out: subprocess.CompletedProcess, status: bool) -> list[str]:
|
|
336
|
+
entries = out.stdout.split("\0")
|
|
337
|
+
if not status:
|
|
338
|
+
return [e for e in entries if e]
|
|
339
|
+
names, skip = [], False
|
|
340
|
+
for e in entries:
|
|
341
|
+
if skip:
|
|
342
|
+
skip = False
|
|
343
|
+
elif len(e) > MIN_STATUS_ENTRY:
|
|
344
|
+
names.append(e[3:])
|
|
345
|
+
skip = e[0] in "RC" or e[1] in "RC"
|
|
346
|
+
return names
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def freshness(worktree: Path, stamp: Stamp) -> str:
|
|
350
|
+
if (
|
|
351
|
+
stamp.commit is None
|
|
352
|
+
or _git(worktree, "cat-file", "-e", f"{stamp.commit}^{{commit}}") is None
|
|
353
|
+
):
|
|
354
|
+
return UNKNOWN
|
|
355
|
+
# --no-relative: names relative to the toplevel, like status, even when the user sets diff.relative
|
|
356
|
+
diff = _git(
|
|
357
|
+
worktree, "diff", "--no-relative", "--name-only", "-z", stamp.commit, "--", *stamp.paths
|
|
358
|
+
)
|
|
359
|
+
status = _git(
|
|
360
|
+
worktree, "status", "--porcelain", "-z", "--untracked-files=all", "--", *stamp.paths
|
|
361
|
+
)
|
|
362
|
+
if diff is None or status is None:
|
|
363
|
+
return UNKNOWN
|
|
364
|
+
prefix = _git(worktree, "rev-parse", "--show-prefix")
|
|
365
|
+
if prefix is None:
|
|
366
|
+
return UNKNOWN
|
|
367
|
+
own = prefix.stdout.strip() + PROJECT_DIR + "/"
|
|
368
|
+
touched = [n for n in _names(diff, False) + _names(status, True) if not n.startswith(own)]
|
|
369
|
+
if touched or any(not (worktree / p).exists() for p in stamp.paths):
|
|
370
|
+
return CHANGED
|
|
371
|
+
return FRESH
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def covers_uncommitted(worktree: Path, paths: Sequence[str]) -> bool:
|
|
375
|
+
"""True when a covered path differs from HEAD in the working tree; False when git is unavailable."""
|
|
376
|
+
head = head_commit(worktree)
|
|
377
|
+
return (
|
|
378
|
+
head is not None
|
|
379
|
+
and freshness(worktree, Stamp(tuple(paths), datetime.date.today(), head)) == CHANGED
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def describe(state: str) -> str:
|
|
384
|
+
return _DESCRIPTIONS[state]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Check that a split keeps the original section's references and figures."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from collections import Counter
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from memory_cli.syntheses.document import _resolved, _sources_line, references
|
|
8
|
+
from memory_cli.syntheses.units import _REF_LINK, _inline, _is_ref, _parse, _relative, _remove
|
|
9
|
+
|
|
10
|
+
_FIGURE = re.compile(r"(?<![\w.])[+\u2212-]?\d+(?:[.,]\d+)*%?(?!\w)")
|
|
11
|
+
_URL = re.compile(r"https?://[^\s<>]+")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _references(base: Path, text: str) -> set[Path]:
|
|
15
|
+
sources = _sources_line(text) or ""
|
|
16
|
+
targets = references(text) + [
|
|
17
|
+
m.group(2)
|
|
18
|
+
for m in _REF_LINK.finditer(sources)
|
|
19
|
+
if _relative(m.group(2)) and _is_ref(m.group(2))
|
|
20
|
+
]
|
|
21
|
+
return {_resolved(base, target) for target in targets}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _figures(text: str) -> Counter[str]:
|
|
25
|
+
_, refs, _, body_end = _parse(text)
|
|
26
|
+
body = _remove(text, 0, body_end, refs)
|
|
27
|
+
lines = []
|
|
28
|
+
for line in body.splitlines():
|
|
29
|
+
pieces, pos = [], 0
|
|
30
|
+
for start, end, kind, match in _inline(line):
|
|
31
|
+
if kind == "link" and match is not None:
|
|
32
|
+
pieces.extend((line[pos:start], match.group(1)))
|
|
33
|
+
pos = end
|
|
34
|
+
pieces.append(line[pos:])
|
|
35
|
+
lines.append(_URL.sub("", "".join(pieces)))
|
|
36
|
+
return Counter(figure.replace("\u2212", "-") for figure in _FIGURE.findall("\n".join(lines)))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def check_conservation(root: Path, original: str, retained: str, moved: str) -> list[str]:
|
|
40
|
+
"""Return one problem per missing resolved note and missing figure occurrence."""
|
|
41
|
+
base = root / "syntheses"
|
|
42
|
+
missing_refs = (
|
|
43
|
+
_references(base, original) - _references(base, retained) - _references(base, moved)
|
|
44
|
+
)
|
|
45
|
+
missing_figures = _figures(original) - (_figures(retained) + _figures(moved))
|
|
46
|
+
return [f"missing reference: {path}" for path in sorted(missing_refs)] + [
|
|
47
|
+
f"missing figure: {figure}"
|
|
48
|
+
for figure, count in sorted(missing_figures.items())
|
|
49
|
+
for _ in range(count)
|
|
50
|
+
]
|