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,230 @@
|
|
|
1
|
+
"""The generated index READMEs: rendering and `apply_index`. Imports only notes and safe_io."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any, NamedTuple
|
|
6
|
+
|
|
7
|
+
from memory_cli.core import safe_io
|
|
8
|
+
from memory_cli.notes import note as notes_mod
|
|
9
|
+
from memory_cli.notes.note import (
|
|
10
|
+
FrontmatterError,
|
|
11
|
+
discover_notes,
|
|
12
|
+
leaf_topics,
|
|
13
|
+
load_topics,
|
|
14
|
+
root_of,
|
|
15
|
+
root_topics,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from memory_cli.notes.note import Note
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
INDEX_START = "<!-- hub:index:start -->"
|
|
25
|
+
INDEX_END = "<!-- hub:index:end -->"
|
|
26
|
+
INDEX_FOLDERS = ("literature", "knowledge", "research")
|
|
27
|
+
|
|
28
|
+
_INDEX_COLUMNS = {
|
|
29
|
+
"literature": ("Year", "Title", "Kind", "Level", "Topics"),
|
|
30
|
+
"knowledge": ("Claim", "Confidence", "Level", "Topics"),
|
|
31
|
+
"research": ("Started", "Title", "Status", "Topics"),
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _cell(value: Any) -> str:
|
|
36
|
+
return str(value).replace("|", "\\|").replace("\n", " ")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _index_row(note: Note, topics: dict) -> tuple[tuple, list[str]]:
|
|
40
|
+
key, cells = _index_cells(note, topics)
|
|
41
|
+
if note.meta.get("superseded_by") is not None:
|
|
42
|
+
cells[0 if note.type == "knowledge" else 1] += (
|
|
43
|
+
" (superseded)" # the cell holding the note's link
|
|
44
|
+
)
|
|
45
|
+
return key, cells
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _index_cells(note: Note, topics: dict) -> tuple[tuple, list[str]]:
|
|
49
|
+
meta = note.meta
|
|
50
|
+
listed = meta.get("topics")
|
|
51
|
+
leaves = (
|
|
52
|
+
leaf_topics(topics, [t for t in listed if isinstance(t, str)])
|
|
53
|
+
if isinstance(listed, list)
|
|
54
|
+
else []
|
|
55
|
+
)
|
|
56
|
+
topic_cell = _cell(", ".join(sorted(leaves)))
|
|
57
|
+
if note.type == "literature":
|
|
58
|
+
name = note.path.name
|
|
59
|
+
link = f"[{_cell(meta.get('title', name))}]({name})"
|
|
60
|
+
year = meta.get("year")
|
|
61
|
+
key = (-year if isinstance(year, int) else 0, name)
|
|
62
|
+
return key, [
|
|
63
|
+
_cell(year if year is not None else ""),
|
|
64
|
+
link,
|
|
65
|
+
_cell(meta.get("kind", "")),
|
|
66
|
+
_cell(meta.get("level", "")),
|
|
67
|
+
topic_cell,
|
|
68
|
+
]
|
|
69
|
+
if note.type == "knowledge":
|
|
70
|
+
name = note.path.name
|
|
71
|
+
link = f"[{_cell(meta.get('claim', name))}]({name})"
|
|
72
|
+
return (name,), [
|
|
73
|
+
link,
|
|
74
|
+
_cell(meta.get("confidence", "")),
|
|
75
|
+
_cell(meta.get("level", "")),
|
|
76
|
+
topic_cell,
|
|
77
|
+
]
|
|
78
|
+
folder = note.path.parent.name
|
|
79
|
+
link = f"[{_cell(meta.get('title', folder))}]({folder}/README.md)"
|
|
80
|
+
started = str(meta.get("started", ""))
|
|
81
|
+
return (started, folder), [_cell(started), link, _cell(meta.get("status", "")), topic_cell]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _rows_table(folder: str, rows: list[tuple[tuple, list[str]]]) -> list[str]:
|
|
85
|
+
if folder == "research":
|
|
86
|
+
# started descending, then id ascending
|
|
87
|
+
rows.sort(key=lambda r: r[0][1])
|
|
88
|
+
rows.sort(key=lambda r: r[0][0], reverse=True)
|
|
89
|
+
else:
|
|
90
|
+
rows.sort(key=lambda r: r[0])
|
|
91
|
+
cols = _INDEX_COLUMNS[folder]
|
|
92
|
+
lines = ["| " + " | ".join(cols) + " |", "| " + " | ".join("---" for _ in cols) + " |"]
|
|
93
|
+
return lines + ["| " + " | ".join(cells) + " |" for _, cells in rows]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _indexable(notes: list[Note], folder: str) -> list[Note]:
|
|
97
|
+
return [n for n in notes if n.type == folder and n.error is None and isinstance(n.meta, dict)]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _domain_notes(notes: list[Note], folder: str, domain: str) -> list[Note]:
|
|
101
|
+
return [n for n in _indexable(notes, folder) if n.path.parent.name == domain]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _subtopics(note: Note, domain: str, topics: dict) -> list[str]:
|
|
105
|
+
"""Headings of a note in its domain README: each most-specific topic under the domain, else `general`."""
|
|
106
|
+
listed = note.meta.get("topics")
|
|
107
|
+
leaves = (
|
|
108
|
+
leaf_topics(topics, [t for t in listed if isinstance(t, str) and t in topics])
|
|
109
|
+
if isinstance(listed, list)
|
|
110
|
+
else []
|
|
111
|
+
)
|
|
112
|
+
found = sorted(t for t in leaves if t != domain and root_of(topics, t) == domain)
|
|
113
|
+
return found or ["general"]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def render_index(root: Path, folder: str, notes: list[Note], topics: dict) -> str:
|
|
117
|
+
"""Block content between the markers of research/ or of a top-level literature/knowledge README."""
|
|
118
|
+
if folder == "research":
|
|
119
|
+
rows = [_index_row(n, topics) for n in _indexable(notes, folder)]
|
|
120
|
+
return (
|
|
121
|
+
"\n" + "\n".join(_rows_table(folder, rows)) + "\n" if rows else "\n_No entries yet._\n"
|
|
122
|
+
)
|
|
123
|
+
counts = {d: len(_domain_notes(notes, folder, d)) for d in sorted(root_topics(topics))}
|
|
124
|
+
counts = {d: c for d, c in counts.items() if c}
|
|
125
|
+
if not counts:
|
|
126
|
+
return "\n_No entries yet._\n"
|
|
127
|
+
lines = ["| Domain | Notes |", "| --- | --- |"]
|
|
128
|
+
lines += [f"| [{d}]({d}/README.md) | {c} |" for d, c in counts.items()]
|
|
129
|
+
return "\n" + "\n".join(lines) + "\n"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def render_domain_index(folder: str, domain: str, notes: list[Note], topics: dict) -> str:
|
|
133
|
+
"""Block content of <folder>/<domain>/README.md: one table per subtopic, `general` last."""
|
|
134
|
+
groups: dict[str, list[tuple[tuple, list[str]]]] = {}
|
|
135
|
+
for n in _domain_notes(notes, folder, domain):
|
|
136
|
+
for heading in _subtopics(n, domain, topics):
|
|
137
|
+
groups.setdefault(heading, []).append(_index_row(n, topics))
|
|
138
|
+
if not groups:
|
|
139
|
+
return "\n_No entries yet._\n"
|
|
140
|
+
out: list[str] = []
|
|
141
|
+
for name in sorted(groups, key=lambda g: (g == "general", g)):
|
|
142
|
+
out += ["", f"### {name}", "", *_rows_table(folder, groups[name])]
|
|
143
|
+
return "\n".join(out) + "\n"
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _with_index(text: str, block: str) -> str:
|
|
147
|
+
"""Replace the block between the markers, or append one when there are no markers at all."""
|
|
148
|
+
starts, ends = text.count(INDEX_START), text.count(INDEX_END)
|
|
149
|
+
start, end = text.find(INDEX_START), text.find(INDEX_END)
|
|
150
|
+
if (starts, ends) != (0, 0) and not (starts == ends == 1 and start < end):
|
|
151
|
+
raise FrontmatterError(
|
|
152
|
+
"index markers must be exactly one start marker followed by one "
|
|
153
|
+
"end marker: remove the stray or duplicated markers"
|
|
154
|
+
)
|
|
155
|
+
if starts:
|
|
156
|
+
return text[: start + len(INDEX_START)] + block + text[end:]
|
|
157
|
+
sep = "" if not text or text.endswith("\n\n") else ("\n" if text.endswith("\n") else "\n\n")
|
|
158
|
+
return text + sep + INDEX_START + block + INDEX_END + "\n"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
_DOMAIN_PURPOSE = {
|
|
162
|
+
"literature": "Our readings of external sources about {domain}.",
|
|
163
|
+
"knowledge": "Reusable conclusions about {domain}.",
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class IndexTarget(NamedTuple):
|
|
168
|
+
path: Path
|
|
169
|
+
block: str
|
|
170
|
+
default: str | None # initial text when the README is missing; None: do not create it
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def index_targets(root: Path, notes: list[Note], topics: dict) -> list[IndexTarget]:
|
|
174
|
+
"""Every README that carries a generated block."""
|
|
175
|
+
targets = []
|
|
176
|
+
for folder in INDEX_FOLDERS:
|
|
177
|
+
targets.append(
|
|
178
|
+
IndexTarget(
|
|
179
|
+
root / folder / "README.md", render_index(root, folder, notes, topics), None
|
|
180
|
+
)
|
|
181
|
+
)
|
|
182
|
+
if folder == "research":
|
|
183
|
+
continue
|
|
184
|
+
for domain in sorted(root_topics(topics)):
|
|
185
|
+
readme = root / folder / domain / "README.md"
|
|
186
|
+
if readme.is_file() and not _domain_notes(notes, folder, domain):
|
|
187
|
+
targets.append(
|
|
188
|
+
IndexTarget(readme, render_domain_index(folder, domain, notes, topics), None)
|
|
189
|
+
)
|
|
190
|
+
elif _domain_notes(notes, folder, domain):
|
|
191
|
+
default = (
|
|
192
|
+
f"# {folder.capitalize()}: {domain}\n\n"
|
|
193
|
+
f"{_DOMAIN_PURPOSE[folder].format(domain=domain)}\n"
|
|
194
|
+
)
|
|
195
|
+
targets.append(
|
|
196
|
+
IndexTarget(
|
|
197
|
+
root / folder / domain / "README.md",
|
|
198
|
+
render_domain_index(folder, domain, notes, topics),
|
|
199
|
+
default,
|
|
200
|
+
)
|
|
201
|
+
)
|
|
202
|
+
return targets
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _new_text(root: Path, target: IndexTarget) -> str | None:
|
|
206
|
+
"""The README text with its block rewritten; None when nothing is to be written."""
|
|
207
|
+
path, block, default = target
|
|
208
|
+
if not path.is_file():
|
|
209
|
+
return None if default is None else _with_index(default, block)
|
|
210
|
+
try:
|
|
211
|
+
text = notes_mod._read_text(path)
|
|
212
|
+
new = _with_index(text, block)
|
|
213
|
+
except FrontmatterError as exc:
|
|
214
|
+
raise FrontmatterError(f"{path.relative_to(root).as_posix()}: {exc}") from exc
|
|
215
|
+
return new if new != text else None
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def apply_index(root: Path) -> list[str]:
|
|
219
|
+
"""Rewrite every index block; return the hub-relative paths that changed."""
|
|
220
|
+
topics = load_topics(root)
|
|
221
|
+
notes = discover_notes(root)
|
|
222
|
+
pending: list[tuple[Path, str]] = []
|
|
223
|
+
for target in index_targets(root, notes, topics):
|
|
224
|
+
new = _new_text(root, target)
|
|
225
|
+
if new is not None:
|
|
226
|
+
pending.append((target.path, new))
|
|
227
|
+
for path, new in pending: # write only after every README was accepted
|
|
228
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
229
|
+
safe_io.replace_file(path, new.encode("utf-8"))
|
|
230
|
+
return [path.relative_to(root).as_posix() for path, _ in pending]
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""The link rules: relative links resolve, and `orphan_notes`. Pure."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import urllib.parse
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TYPE_CHECKING
|
|
10
|
+
|
|
11
|
+
from memory_cli.notes import note as notes_mod
|
|
12
|
+
from memory_cli.notes.fields import Problem
|
|
13
|
+
from memory_cli.notes.index import INDEX_FOLDERS
|
|
14
|
+
from memory_cli.notes.note import FrontmatterError, discover_notes
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from collections.abc import Iterator
|
|
18
|
+
|
|
19
|
+
from memory_cli.notes.note import Note
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
_FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})")
|
|
23
|
+
# A code span never crosses a blank line (paragraph boundary).
|
|
24
|
+
_CODE_SPAN = re.compile(r"(?<!`)(`+)(?!`)((?:(?!\n[ \t]*\n).)+?)(?<!`)\1(?!`)", re.DOTALL)
|
|
25
|
+
# Target: <...> (spaces allowed) or bare with one level of balanced parentheses; optional title.
|
|
26
|
+
_LINK = re.compile(
|
|
27
|
+
r"\[[^\]]*\]\(\s*(?:<([^<>\n]*)>|((?:[^()\s]|\([^()\s]*\))+))"
|
|
28
|
+
r"""(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*\)"""
|
|
29
|
+
)
|
|
30
|
+
# A reference definition, `[label]: target "title"`: a link to its target for `[text][label]` uses.
|
|
31
|
+
_REFDEF = re.compile(
|
|
32
|
+
r"""^ {0,3}\[[^\]]+\]:[ \t]*(?:<([^<>\n]*)>|(\S+))(?:[ \t]+(?:"[^"]*"|'[^']*'|\([^)]*\)))?[ \t]*$"""
|
|
33
|
+
)
|
|
34
|
+
_SCHEME = re.compile(r"[a-zA-Z][a-zA-Z0-9+.-]*:")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _target_spans(line: str, refs: bool) -> list[tuple[int, int]]:
|
|
38
|
+
"""(start, end) of the target of each inline link in `line`, and of its reference definition when `refs`."""
|
|
39
|
+
found = [m.span(1 if m.group(1) is not None else 2) for m in _LINK.finditer(line)]
|
|
40
|
+
if refs and (m := _REFDEF.match(line)):
|
|
41
|
+
found.append(m.span(1 if m.group(1) is not None else 2))
|
|
42
|
+
return found
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _blank(match: re.Match) -> str:
|
|
46
|
+
return "\n" * match.group(0).count("\n")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _in_fence(lines: list[str]) -> list[bool]:
|
|
50
|
+
"""Per line: True when it is a fence line or inside a fenced code block."""
|
|
51
|
+
flags: list[bool] = []
|
|
52
|
+
fence: str | None = None
|
|
53
|
+
for line in lines:
|
|
54
|
+
m = _FENCE.match(line)
|
|
55
|
+
if fence is None:
|
|
56
|
+
if m:
|
|
57
|
+
fence = m.group(1)
|
|
58
|
+
flags.append(fence is not None)
|
|
59
|
+
else:
|
|
60
|
+
if (
|
|
61
|
+
m
|
|
62
|
+
and m.group(1)[0] == fence[0]
|
|
63
|
+
and len(m.group(1)) >= len(fence)
|
|
64
|
+
and line.strip() == m.group(1)
|
|
65
|
+
):
|
|
66
|
+
fence = None
|
|
67
|
+
flags.append(True)
|
|
68
|
+
return flags
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _strip_code(text: str) -> str:
|
|
72
|
+
"""Blank out fenced blocks and inline code spans, keeping line numbers."""
|
|
73
|
+
lines = text.split("\n")
|
|
74
|
+
kept = ["" if fenced else line for line, fenced in zip(lines, _in_fence(lines), strict=True)]
|
|
75
|
+
return _CODE_SPAN.sub(_blank, "\n".join(kept))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# Path parts of a research/<id> folder (the depth at which its `code/` is skipped).
|
|
79
|
+
_RESEARCH_FOLDER_DEPTH = 2
|
|
80
|
+
# Path parts of an index README: <folder>/README.md and <literature|knowledge>/<domain>/README.md.
|
|
81
|
+
_FOLDER_README_PARTS = 2
|
|
82
|
+
_DOMAIN_README_PARTS = 3
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _markdown_files(root: Path) -> list[Path]:
|
|
86
|
+
found = []
|
|
87
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
88
|
+
rel = Path(dirpath).relative_to(root).parts
|
|
89
|
+
dirnames[:] = sorted(
|
|
90
|
+
d
|
|
91
|
+
for d in dirnames
|
|
92
|
+
if not d.startswith(".")
|
|
93
|
+
and not (len(rel) == _RESEARCH_FOLDER_DEPTH and rel[0] == "research" and d == "code")
|
|
94
|
+
and not (rel == ("tools", "tests") and d == "fixtures")
|
|
95
|
+
)
|
|
96
|
+
found += [
|
|
97
|
+
Path(dirpath) / f
|
|
98
|
+
for f in sorted(filenames)
|
|
99
|
+
if f.endswith(".md") and not f.startswith(".")
|
|
100
|
+
]
|
|
101
|
+
return found
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _relative_links(text: str, refs: bool = False) -> Iterator[tuple[int, str, str]]:
|
|
105
|
+
"""(line, target, decoded file part) of each relative link outside code; anchors and URLs are skipped.
|
|
106
|
+
|
|
107
|
+
Reference definitions count as links only with `refs` (`check` keeps its own scan)."""
|
|
108
|
+
for lineno, line in enumerate(_strip_code(text).split("\n"), 1):
|
|
109
|
+
for start, end in _target_spans(line, refs):
|
|
110
|
+
target = line[start:end]
|
|
111
|
+
if target.startswith(("#", "mailto:")) or _SCHEME.match(target):
|
|
112
|
+
continue
|
|
113
|
+
file_part = urllib.parse.unquote(target.split("#", 1)[0])
|
|
114
|
+
if file_part:
|
|
115
|
+
yield lineno, target, file_part
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def rule_links(root: Path, notes: list[Note], topics: dict | None) -> list[Problem]:
|
|
119
|
+
"""Rule 6: relative links resolve to existing files."""
|
|
120
|
+
problems = []
|
|
121
|
+
for path in _markdown_files(root):
|
|
122
|
+
try:
|
|
123
|
+
text = notes_mod._read_text(path)
|
|
124
|
+
except FrontmatterError:
|
|
125
|
+
continue
|
|
126
|
+
rel = path.relative_to(root).as_posix()
|
|
127
|
+
for lineno, target, file_part in _relative_links(text):
|
|
128
|
+
try:
|
|
129
|
+
exists = (path.parent / file_part).exists()
|
|
130
|
+
except (OSError, ValueError):
|
|
131
|
+
exists = False
|
|
132
|
+
if not exists:
|
|
133
|
+
problems.append(
|
|
134
|
+
Problem(rel, lineno, f"broken link {target}: fix the path or remove the link")
|
|
135
|
+
)
|
|
136
|
+
return problems
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _is_index_readme(rel: str) -> bool:
|
|
140
|
+
parts = rel.split("/")
|
|
141
|
+
return parts[-1] == "README.md" and (
|
|
142
|
+
(len(parts) == _FOLDER_README_PARTS and parts[0] in INDEX_FOLDERS)
|
|
143
|
+
or (len(parts) == _DOMAIN_README_PARTS and parts[0] in {"literature", "knowledge"})
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _link_targets(path: Path, text: str) -> Iterator[str]:
|
|
148
|
+
"""Normalized files that `path` links to, a folder standing for its README.md; self links are skipped."""
|
|
149
|
+
for _, _, file_part in _relative_links(text):
|
|
150
|
+
target = os.path.normpath(path.parent / file_part)
|
|
151
|
+
if Path(target).is_dir():
|
|
152
|
+
target = os.path.join(target, "README.md")
|
|
153
|
+
if target != os.path.normpath(path):
|
|
154
|
+
yield target
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def orphan_notes(root: Path) -> list[str]:
|
|
158
|
+
"""Typed notes no other Markdown file links to, not counting the generated index READMEs; sorted."""
|
|
159
|
+
linked: set[str] = set()
|
|
160
|
+
for path in _markdown_files(root):
|
|
161
|
+
if _is_index_readme(path.relative_to(root).as_posix()):
|
|
162
|
+
continue
|
|
163
|
+
try:
|
|
164
|
+
text = notes_mod._read_text(path)
|
|
165
|
+
except FrontmatterError:
|
|
166
|
+
continue
|
|
167
|
+
linked.update(_link_targets(path, text))
|
|
168
|
+
return sorted(
|
|
169
|
+
n.rel for n in discover_notes(root) if os.path.normpath(root / n.rel) not in linked
|
|
170
|
+
)
|
memory_cli/notes/note.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Notes: frontmatter, the YAML loaders, `Note`, topics and handles. From the engine, imports only `core.yaml_load`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import unicodedata
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import yaml
|
|
12
|
+
|
|
13
|
+
from memory_cli.core.yaml_load import BaseLoader
|
|
14
|
+
|
|
15
|
+
_DROPPED_TAGS = {"tag:yaml.org,2002:timestamp", "tag:yaml.org,2002:bool"}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class HubLoader(BaseLoader):
|
|
19
|
+
"""SafeLoader that keeps dates and on/off/yes/no as strings."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# Copy, never mutate: SafeLoader's table is shared with every other user of PyYAML.
|
|
23
|
+
HubLoader.yaml_implicit_resolvers = {
|
|
24
|
+
first: [(tag, rx) for tag, rx in resolvers if tag not in _DROPPED_TAGS]
|
|
25
|
+
for first, resolvers in yaml.SafeLoader.yaml_implicit_resolvers.items()
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _no_duplicate_keys(loader: HubLoader, node: yaml.MappingNode, deep: bool = False) -> dict:
|
|
30
|
+
loader.flatten_mapping(node)
|
|
31
|
+
seen: set = set()
|
|
32
|
+
for key_node, _ in node.value:
|
|
33
|
+
key = loader.construct_object(key_node, deep=True)
|
|
34
|
+
try:
|
|
35
|
+
duplicate = key in seen
|
|
36
|
+
seen.add(key)
|
|
37
|
+
except TypeError: # unhashable key: the default constructor reports it
|
|
38
|
+
continue
|
|
39
|
+
if duplicate:
|
|
40
|
+
raise yaml.constructor.ConstructorError(
|
|
41
|
+
"while constructing a mapping",
|
|
42
|
+
node.start_mark,
|
|
43
|
+
f"found duplicate key {key!r}",
|
|
44
|
+
key_node.start_mark,
|
|
45
|
+
)
|
|
46
|
+
return yaml.constructor.SafeConstructor.construct_mapping(loader, node, deep=deep)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
HubLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _no_duplicate_keys)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def load_yaml(text: str) -> Any:
|
|
53
|
+
return yaml.load(text, Loader=HubLoader)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class FrontmatterError(Exception):
|
|
57
|
+
def __init__(self, message: str, line: int = 1) -> None:
|
|
58
|
+
super().__init__(message)
|
|
59
|
+
self.line = line
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _yaml_problem(exc: yaml.YAMLError, first_line: int) -> tuple[str, int]:
|
|
63
|
+
"""One-line description and file line of a YAML error; first_line is where the YAML text starts."""
|
|
64
|
+
mark = getattr(exc, "problem_mark", None)
|
|
65
|
+
problem = getattr(exc, "problem", None) or str(exc).splitlines()[0]
|
|
66
|
+
return problem, (mark.line + first_line if mark is not None else first_line)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _read_text(path: Path) -> str:
|
|
70
|
+
"""UTF-8 text without BOM and with LF newlines; FrontmatterError when unreadable."""
|
|
71
|
+
try:
|
|
72
|
+
text = path.read_text(encoding="utf-8")
|
|
73
|
+
except UnicodeDecodeError as exc:
|
|
74
|
+
raise FrontmatterError("file is not valid UTF-8") from exc
|
|
75
|
+
except OSError as exc:
|
|
76
|
+
raise FrontmatterError(f"file cannot be read ({exc.strerror or exc})") from exc
|
|
77
|
+
return text.removeprefix("\ufeff").replace("\r\n", "\n")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def split_frontmatter(text: str) -> tuple[Any, str, int]:
|
|
81
|
+
"""Return (data, body, 1-based line where the body starts)."""
|
|
82
|
+
text = text.removeprefix("\ufeff").replace("\r\n", "\n")
|
|
83
|
+
if not text.startswith("---\n"):
|
|
84
|
+
raise FrontmatterError("missing frontmatter block (file must start with '---')")
|
|
85
|
+
lines = text.split("\n")
|
|
86
|
+
for i in range(1, len(lines)):
|
|
87
|
+
if lines[i] == "---":
|
|
88
|
+
try:
|
|
89
|
+
data = load_yaml("\n".join(lines[1:i]))
|
|
90
|
+
except yaml.YAMLError as exc:
|
|
91
|
+
problem, line = _yaml_problem(exc, 2)
|
|
92
|
+
raise FrontmatterError(f"invalid YAML in frontmatter: {problem}", line) from exc
|
|
93
|
+
return data, "\n".join(lines[i + 1 :]), i + 2
|
|
94
|
+
raise FrontmatterError("frontmatter block is not closed with '---'")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass
|
|
98
|
+
class Note:
|
|
99
|
+
type: str
|
|
100
|
+
path: Path
|
|
101
|
+
rel: str
|
|
102
|
+
meta: Any
|
|
103
|
+
body: str
|
|
104
|
+
body_line: int
|
|
105
|
+
text: str
|
|
106
|
+
error: str | None
|
|
107
|
+
error_line: int = 1
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _is_hidden(path: Path, root: Path) -> bool:
|
|
111
|
+
return any(part.startswith(".") for part in path.relative_to(root).parts)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _read_note(note_type: str, path: Path, root: Path) -> Note:
|
|
115
|
+
rel = path.relative_to(root).as_posix()
|
|
116
|
+
try:
|
|
117
|
+
text = _read_text(path)
|
|
118
|
+
except FrontmatterError as exc:
|
|
119
|
+
return Note(note_type, path, rel, None, "", 1, "", str(exc))
|
|
120
|
+
try:
|
|
121
|
+
meta, body, body_line = split_frontmatter(text)
|
|
122
|
+
return Note(note_type, path, rel, meta, body, body_line, text, None)
|
|
123
|
+
except FrontmatterError as exc:
|
|
124
|
+
return Note(note_type, path, rel, None, text, 1, text, str(exc), exc.line)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _note_files(root: Path) -> list[tuple[str, Path]]:
|
|
128
|
+
"""(type, path) of the typed notes: literature/*/*.md and knowledge/*/*.md (not README.md), research/*/README.md."""
|
|
129
|
+
found = [
|
|
130
|
+
(kind, path)
|
|
131
|
+
for kind in ("literature", "knowledge")
|
|
132
|
+
for path in (root / kind).glob("*/*.md")
|
|
133
|
+
if path.name != "README.md"
|
|
134
|
+
]
|
|
135
|
+
found += [("research", path) for path in (root / "research").glob("*/README.md")]
|
|
136
|
+
return [(kind, path) for kind, path in found if path.is_file() and not _is_hidden(path, root)]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def discover_notes(root: Path) -> list[Note]:
|
|
140
|
+
"""Typed notes (see `_note_files`), sorted by path."""
|
|
141
|
+
return sorted(
|
|
142
|
+
(_read_note(kind, path, root) for kind, path in _note_files(root)), key=lambda n: n.rel
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def load_topics(root: Path) -> dict[str, dict]:
|
|
147
|
+
path = root / "topics.yaml"
|
|
148
|
+
if not path.is_file():
|
|
149
|
+
raise FrontmatterError("topics.yaml is missing")
|
|
150
|
+
try:
|
|
151
|
+
data = load_yaml(_read_text(path))
|
|
152
|
+
except yaml.YAMLError as exc:
|
|
153
|
+
problem, line = _yaml_problem(exc, 1)
|
|
154
|
+
raise FrontmatterError(f"invalid YAML in topics.yaml: {problem}", line) from exc
|
|
155
|
+
if not isinstance(data, dict):
|
|
156
|
+
raise FrontmatterError("topics.yaml must be a mapping of topic ids")
|
|
157
|
+
return data
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _parent(topics: dict, tid: str) -> str | None:
|
|
161
|
+
entry = topics.get(tid)
|
|
162
|
+
parent = entry.get("parent") if isinstance(entry, dict) else None
|
|
163
|
+
return parent if isinstance(parent, str) else None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def ancestors(topics: dict, tid: str) -> list[str]:
|
|
167
|
+
"""Known parents of tid, nearest first; an unknown or non-string parent and a cycle end the walk and are not included."""
|
|
168
|
+
result: list[str] = []
|
|
169
|
+
seen = {tid}
|
|
170
|
+
current = _parent(topics, tid)
|
|
171
|
+
while current is not None and current in topics and current not in seen:
|
|
172
|
+
result.append(current)
|
|
173
|
+
seen.add(current)
|
|
174
|
+
current = _parent(topics, current)
|
|
175
|
+
return result
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def descendants(topics: dict, tid: str) -> set[str]:
|
|
179
|
+
"""tid plus every topic that has it as an ancestor."""
|
|
180
|
+
return {tid} | {t for t in topics if tid in ancestors(topics, t)}
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def root_topics(topics: dict) -> list[str]:
|
|
184
|
+
"""Topic ids with no parent: the domains."""
|
|
185
|
+
return [
|
|
186
|
+
t
|
|
187
|
+
for t, e in topics.items()
|
|
188
|
+
if isinstance(t, str) and isinstance(e, dict) and "parent" not in e
|
|
189
|
+
]
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def root_of(topics: dict, tid: str) -> str:
|
|
193
|
+
"""The domain of a known topic: its last ancestor, or itself when it has no parent."""
|
|
194
|
+
return (ancestors(topics, tid) or [tid])[-1]
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def leaf_topics(topics: dict, listed: list[str]) -> list[str]:
|
|
198
|
+
return [t for t in listed if not any(o != t and t in ancestors(topics, o) for o in listed)]
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def slugify(s: str) -> str:
|
|
202
|
+
ascii_text = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode()
|
|
203
|
+
return re.sub(r"[^a-z0-9]", "", ascii_text.lower())
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def key_line(text: str, key: str) -> int:
|
|
207
|
+
"""1-based line of a top-level `key:` inside the frontmatter, else 1."""
|
|
208
|
+
lines = text.split("\n")
|
|
209
|
+
if not lines or lines[0] != "---":
|
|
210
|
+
return 1
|
|
211
|
+
for i in range(1, len(lines)):
|
|
212
|
+
if lines[i] == "---":
|
|
213
|
+
break
|
|
214
|
+
if re.match(rf"{re.escape(key)}[ \t]*:", lines[i]):
|
|
215
|
+
return i + 1
|
|
216
|
+
return 1
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _handle(rel: str) -> str:
|
|
220
|
+
"""What names a note: the file stem of a literature or knowledge note, the folder id of an investigation."""
|
|
221
|
+
p = Path(rel)
|
|
222
|
+
return p.parent.name if rel.startswith("research/") else p.stem
|