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,148 @@
|
|
|
1
|
+
"""The forbidden-terms list, the secret patterns and the checks on a store folder that keep them out of the global scope."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import unicodedata
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import TYPE_CHECKING, NamedTuple
|
|
9
|
+
|
|
10
|
+
from memory_cli.core import config
|
|
11
|
+
from memory_cli.memories.model import KINDS, STORE_MARKER
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from collections.abc import Iterable, Mapping
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def forbidden_file(env: Mapping[str, str]) -> Path | None:
|
|
18
|
+
base = config.config_dir(env)
|
|
19
|
+
return base / "forbidden-terms" if base is not None else None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ForbiddenListError(ValueError):
|
|
23
|
+
"""The forbidden-terms file exists but cannot be read or decoded."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
TERMS_HEADER = (
|
|
27
|
+
"# Terms that must not reach the global scope, one per line; matching ignores case and accents.\n"
|
|
28
|
+
'# A plain line is a hard term: the write is refused. "soft: <term>" or "soft[<kind>]: <term>" '
|
|
29
|
+
"is a soft term: the owner must approve the write.\n"
|
|
30
|
+
"# Manage the list with: mem terms list | add | remove.\n"
|
|
31
|
+
)
|
|
32
|
+
TERM_KINDS = (*KINDS, "note", "synthesis")
|
|
33
|
+
_SOFT_LINE = re.compile(r"^soft(?:\[([a-z]+)\])?:(.*)$")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Term(NamedTuple):
|
|
37
|
+
line: int # line number in the file
|
|
38
|
+
text: str
|
|
39
|
+
soft: bool
|
|
40
|
+
kind: str | None # a soft term that applies to one kind only
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def parse_term(raw: str, line: int = 0) -> Term | None:
|
|
44
|
+
"""A term of the list, or None for a blank line or a comment."""
|
|
45
|
+
raw = raw.strip()
|
|
46
|
+
if not raw or raw.startswith("#"):
|
|
47
|
+
return None
|
|
48
|
+
m = _SOFT_LINE.match(raw)
|
|
49
|
+
if m:
|
|
50
|
+
return Term(line, m.group(2).strip(), True, m.group(1))
|
|
51
|
+
return Term(line, raw, False, None)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def read_terms(env: Mapping[str, str]) -> list[Term]:
|
|
55
|
+
"""The terms of the list; empty when there is no file. Raises ForbiddenListError when it cannot be read."""
|
|
56
|
+
path = forbidden_file(env)
|
|
57
|
+
if path is None or not path.exists():
|
|
58
|
+
return []
|
|
59
|
+
try:
|
|
60
|
+
lines = path.read_text(encoding="utf-8-sig").splitlines()
|
|
61
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
62
|
+
raise ForbiddenListError(str(path)) from exc
|
|
63
|
+
return [t for i, raw in enumerate(lines, 1) if (t := parse_term(raw, i)) is not None]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def ensure_terms_file(env: Mapping[str, str]) -> Path | None:
|
|
67
|
+
"""Create the list with its comment header when it does not exist; the path, or None when no folder locates it."""
|
|
68
|
+
path = forbidden_file(env)
|
|
69
|
+
if path is not None and not path.exists():
|
|
70
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
71
|
+
with path.open("x", encoding="utf-8") as f:
|
|
72
|
+
f.write(TERMS_HEADER)
|
|
73
|
+
return path
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _fold(text: str) -> str:
|
|
77
|
+
decomposed = unicodedata.normalize("NFKD", text)
|
|
78
|
+
bare = "".join(c for c in decomposed if not unicodedata.combining(c)).casefold()
|
|
79
|
+
return " ".join(bare.split()) # a line break between two words must not hide a term
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def term_hits(texts: Iterable[str], env: Mapping[str, str], kind: str | None = None) -> list[Term]:
|
|
83
|
+
"""The terms found in any text, or in all of them joined, in file order; a soft term with a kind counts only
|
|
84
|
+
for that kind.
|
|
85
|
+
|
|
86
|
+
Raises ForbiddenListError when the file exists but cannot be read: the check must fail closed.
|
|
87
|
+
"""
|
|
88
|
+
terms = read_terms(env)
|
|
89
|
+
texts = list(texts)
|
|
90
|
+
items = [_fold(t) for t in texts] + [_fold("\n".join(texts))]
|
|
91
|
+
hits = []
|
|
92
|
+
for term in terms:
|
|
93
|
+
if term.kind is not None and term.kind != kind:
|
|
94
|
+
continue
|
|
95
|
+
folded = _fold(term.text)
|
|
96
|
+
if folded and any(folded in item for item in items):
|
|
97
|
+
hits.append(term)
|
|
98
|
+
return hits
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def forbidden_line(texts: Iterable[str], env: Mapping[str, str]) -> int | None:
|
|
102
|
+
"""Line number of the first hard term found in any text; None when clean or no file."""
|
|
103
|
+
return next((t.line for t in term_hits(texts, env) if not t.soft), None)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
_PLACEHOLDER = re.compile(r"^[\"']?(<[^>]*>|\u2026|\.{3}|x{3,}|changeme|example)", re.IGNORECASE)
|
|
107
|
+
_ASSIGNMENT = re.compile(
|
|
108
|
+
r"(?i)(?:password|passwd|secret|api[_-]?key|token)\b[\"']?\s*[:=]\s*[\"']?(\S{8,})"
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
# Deliberately conservative: a false refusal costs one rewrite, a stored secret may be synced elsewhere.
|
|
112
|
+
SECRET_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
|
|
113
|
+
("private key", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----")),
|
|
114
|
+
("AWS access key id", re.compile(r"AKIA[0-9A-Z]{16}")),
|
|
115
|
+
("GitHub token", re.compile(r"(?:gh[pousr]_|github_pat_)[A-Za-z0-9_]{20,}")),
|
|
116
|
+
(
|
|
117
|
+
"API key",
|
|
118
|
+
re.compile(r"(?<![A-Za-z0-9])sk-[A-Za-z0-9_-]{20,}"),
|
|
119
|
+
), # not the "sk-" inside "risk-parity-…"
|
|
120
|
+
("Slack token", re.compile(r"xox[bpars]-\S{10,}")),
|
|
121
|
+
("credential in a URL", re.compile(r"://[^/\s:@]+:[^/\s@]+@")),
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def secret_in(texts: Iterable[str]) -> str | None:
|
|
126
|
+
"""Name of the first secret pattern found in any text, or None. The texts are checked one by one and joined."""
|
|
127
|
+
texts = list(texts)
|
|
128
|
+
for text in [*texts, "\n".join(texts)]:
|
|
129
|
+
for name, pattern in SECRET_PATTERNS:
|
|
130
|
+
if pattern.search(text):
|
|
131
|
+
return name
|
|
132
|
+
for match in _ASSIGNMENT.finditer(text):
|
|
133
|
+
if not _PLACEHOLDER.match(match.group(1)):
|
|
134
|
+
return "secret assignment"
|
|
135
|
+
return None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def inside(path: Path, folder: Path) -> bool:
|
|
139
|
+
"""True when path is folder or lies inside it (symlinks resolved)."""
|
|
140
|
+
try:
|
|
141
|
+
Path(path).resolve().relative_to(Path(folder).resolve())
|
|
142
|
+
return True
|
|
143
|
+
except (OSError, ValueError):
|
|
144
|
+
return False
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def store_is_writable(store: Path) -> bool:
|
|
148
|
+
return (store / STORE_MARKER).is_file()
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
"""Writing a memory: rendering the file, new memories, field updates, cases and sightings."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime
|
|
6
|
+
from dataclasses import replace
|
|
7
|
+
from typing import TYPE_CHECKING, Required, TypedDict, Unpack
|
|
8
|
+
|
|
9
|
+
import yaml
|
|
10
|
+
|
|
11
|
+
from memory_cli.core import safe_io
|
|
12
|
+
from memory_cli.memories.model import (
|
|
13
|
+
KINDS,
|
|
14
|
+
ORIGINS,
|
|
15
|
+
OUTCOMES,
|
|
16
|
+
REACHES,
|
|
17
|
+
SHORT_LIMIT,
|
|
18
|
+
TOPIC_LIMIT,
|
|
19
|
+
WEIGHTS,
|
|
20
|
+
Memory,
|
|
21
|
+
slug_of,
|
|
22
|
+
valid_short,
|
|
23
|
+
valid_topic,
|
|
24
|
+
)
|
|
25
|
+
from memory_cli.memories.parse import _parse, _split
|
|
26
|
+
from memory_cli.memories.sightings import (
|
|
27
|
+
case_entry,
|
|
28
|
+
counted,
|
|
29
|
+
has_case,
|
|
30
|
+
normalized_sources,
|
|
31
|
+
session_key,
|
|
32
|
+
sessions,
|
|
33
|
+
sighting,
|
|
34
|
+
sighting_entry,
|
|
35
|
+
standing_changes,
|
|
36
|
+
version_entry,
|
|
37
|
+
version_list,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
if TYPE_CHECKING:
|
|
41
|
+
from collections.abc import Mapping, Sequence
|
|
42
|
+
from pathlib import Path
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# The frontmatter keys of a memory in file order; one is written when its value is set, `observed` and `status` always.
|
|
46
|
+
_RENDER_ORDER = (
|
|
47
|
+
"created",
|
|
48
|
+
"observed",
|
|
49
|
+
"status",
|
|
50
|
+
"context",
|
|
51
|
+
"valid_until",
|
|
52
|
+
"sources",
|
|
53
|
+
"origin",
|
|
54
|
+
"reach",
|
|
55
|
+
"weight",
|
|
56
|
+
"owner_confirmed",
|
|
57
|
+
"triage",
|
|
58
|
+
"triage_reason",
|
|
59
|
+
"released",
|
|
60
|
+
"general",
|
|
61
|
+
"short",
|
|
62
|
+
"short_by",
|
|
63
|
+
"topic",
|
|
64
|
+
"load",
|
|
65
|
+
"log",
|
|
66
|
+
"versions",
|
|
67
|
+
"reviewed",
|
|
68
|
+
"reworded",
|
|
69
|
+
"reword_failed",
|
|
70
|
+
)
|
|
71
|
+
_RENDER_ALWAYS = ("observed", "status")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _frontmatter_value(value: object) -> object:
|
|
75
|
+
if isinstance(value, datetime.date):
|
|
76
|
+
return value.isoformat()
|
|
77
|
+
if isinstance(value, list):
|
|
78
|
+
return list(value)
|
|
79
|
+
return value
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _render(m: Memory, extra: Mapping[str, str] | None = None) -> str:
|
|
83
|
+
meta: dict = {"kind": m.kind, "claim": m.claim}
|
|
84
|
+
for key in _RENDER_ORDER:
|
|
85
|
+
value = getattr(m, key)
|
|
86
|
+
if value or key in _RENDER_ALWAYS:
|
|
87
|
+
meta[key] = _frontmatter_value(value)
|
|
88
|
+
meta.update(extra or {})
|
|
89
|
+
head = yaml.safe_dump(
|
|
90
|
+
meta, sort_keys=False, allow_unicode=True, default_flow_style=False, width=10**6
|
|
91
|
+
)
|
|
92
|
+
return f"---\n{head}---\n{m.body}"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class WriteOptions(TypedDict, total=False):
|
|
96
|
+
"""The keyword options of `write_memory`; an omitted one is None, except `sources` (empty)."""
|
|
97
|
+
|
|
98
|
+
kind: Required[str]
|
|
99
|
+
claim: Required[str]
|
|
100
|
+
body: Required[str]
|
|
101
|
+
today: Required[datetime.date]
|
|
102
|
+
context: str | None
|
|
103
|
+
valid_until: datetime.date | None
|
|
104
|
+
sources: Sequence[str]
|
|
105
|
+
origin: str | None
|
|
106
|
+
reach: str | None
|
|
107
|
+
weight: str | None
|
|
108
|
+
short: str | None
|
|
109
|
+
topic: str | None
|
|
110
|
+
short_by: str | None
|
|
111
|
+
outcome: str | None
|
|
112
|
+
on: datetime.date | None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _check_choice(label: str, value: str | None, allowed: Sequence[str]) -> None:
|
|
116
|
+
if value is not None and value not in allowed:
|
|
117
|
+
raise ValueError(f"unknown {label} {value!r}")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _check_write(options: WriteOptions) -> None:
|
|
121
|
+
"""The first invalid option of a `write_memory` call raises ValueError."""
|
|
122
|
+
kind, sources = options["kind"], options.get("sources", ())
|
|
123
|
+
_check_choice("outcome", options.get("outcome"), OUTCOMES)
|
|
124
|
+
short, topic = options.get("short"), options.get("topic")
|
|
125
|
+
if short is not None and not valid_short(short):
|
|
126
|
+
raise ValueError(f"the short form must be one line of at most {SHORT_LIMIT} characters")
|
|
127
|
+
if topic is not None and not valid_topic(topic):
|
|
128
|
+
raise ValueError(
|
|
129
|
+
f"the topic must be one or two lowercase words of at most {TOPIC_LIMIT} characters"
|
|
130
|
+
)
|
|
131
|
+
if kind not in KINDS:
|
|
132
|
+
raise ValueError(f"unknown kind {kind!r}")
|
|
133
|
+
_check_choice("origin", options.get("origin"), ORIGINS)
|
|
134
|
+
_check_choice("reach", options.get("reach"), REACHES)
|
|
135
|
+
_check_choice("weight", options.get("weight"), WEIGHTS)
|
|
136
|
+
if not options["claim"].strip():
|
|
137
|
+
raise ValueError("claim is empty")
|
|
138
|
+
if kind in {"finding", "document"} and not sources:
|
|
139
|
+
raise ValueError(f"a {kind} needs at least one source")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
_DEFAULT_DAYS = {"finding": 90, "state": 30} # how long a kind lasts when the caller names no end
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _standing_fields(
|
|
146
|
+
template: Memory, today: datetime.date, valid_until: datetime.date | None
|
|
147
|
+
) -> tuple[datetime.date | None, datetime.date | None, str | None]:
|
|
148
|
+
"""(valid_until, released, triage) of a new memory: a transcript memory's standing decides them, before the
|
|
149
|
+
per-kind defaults."""
|
|
150
|
+
if template.origin == "transcript":
|
|
151
|
+
changes = standing_changes(None, template, today)
|
|
152
|
+
return (
|
|
153
|
+
changes["valid_until"] if valid_until is None else valid_until,
|
|
154
|
+
changes.get("released"),
|
|
155
|
+
changes.get("triage"),
|
|
156
|
+
)
|
|
157
|
+
days = _DEFAULT_DAYS.get(template.kind)
|
|
158
|
+
if valid_until is None and days is not None:
|
|
159
|
+
valid_until = today + datetime.timedelta(days=days)
|
|
160
|
+
return valid_until, None, None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _write_new(folder: Path, template: Memory) -> Memory:
|
|
164
|
+
"""Write the memory to a new file named after its claim, -2, -3 ... when the name is taken."""
|
|
165
|
+
base = slug_of(template.claim)
|
|
166
|
+
handle, n = base, 1
|
|
167
|
+
while True:
|
|
168
|
+
m = replace(template, handle=handle, path=folder / f"{handle}.md")
|
|
169
|
+
try:
|
|
170
|
+
with m.path.open("x", encoding="utf-8") as f: # exclusive: never overwrite
|
|
171
|
+
f.write(_render(m))
|
|
172
|
+
return m
|
|
173
|
+
except FileExistsError:
|
|
174
|
+
n += 1
|
|
175
|
+
handle = f"{base}-{n}"
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def write_memory(folder: Path, scope: str, **options: Unpack[WriteOptions]) -> Memory:
|
|
179
|
+
_check_write(options)
|
|
180
|
+
kind, today, short = options["kind"], options["today"], options.get("short")
|
|
181
|
+
claim, body = options["claim"].strip(), options["body"]
|
|
182
|
+
sources = normalized_sources(options.get("sources", ()))
|
|
183
|
+
origin, weight = options.get("origin"), options.get("weight")
|
|
184
|
+
draft = Memory(
|
|
185
|
+
scope,
|
|
186
|
+
folder,
|
|
187
|
+
"",
|
|
188
|
+
kind,
|
|
189
|
+
claim,
|
|
190
|
+
today,
|
|
191
|
+
1,
|
|
192
|
+
"active",
|
|
193
|
+
None,
|
|
194
|
+
None,
|
|
195
|
+
sources,
|
|
196
|
+
"",
|
|
197
|
+
None,
|
|
198
|
+
origin=origin,
|
|
199
|
+
weight=weight,
|
|
200
|
+
)
|
|
201
|
+
valid_until, released, triage = _standing_fields(draft, today, options.get("valid_until"))
|
|
202
|
+
if scope == "project":
|
|
203
|
+
safe_io.refuse_symlink_chain(folder, folder)
|
|
204
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
205
|
+
outcome = options.get("outcome")
|
|
206
|
+
log = (
|
|
207
|
+
[
|
|
208
|
+
case_entry(options.get("on") or today, key, outcome)
|
|
209
|
+
for key in dict.fromkeys(filter(None, map(session_key, sources)))
|
|
210
|
+
]
|
|
211
|
+
if outcome
|
|
212
|
+
else []
|
|
213
|
+
)
|
|
214
|
+
template = Memory(
|
|
215
|
+
scope,
|
|
216
|
+
folder,
|
|
217
|
+
"",
|
|
218
|
+
kind,
|
|
219
|
+
claim,
|
|
220
|
+
today,
|
|
221
|
+
1,
|
|
222
|
+
"active",
|
|
223
|
+
options.get("context"),
|
|
224
|
+
valid_until,
|
|
225
|
+
list(sources),
|
|
226
|
+
body if body.endswith("\n") or not body else body + "\n",
|
|
227
|
+
None,
|
|
228
|
+
origin=origin,
|
|
229
|
+
reach=options.get("reach"),
|
|
230
|
+
weight=weight,
|
|
231
|
+
triage=triage,
|
|
232
|
+
released=released,
|
|
233
|
+
short=short,
|
|
234
|
+
short_by=options.get("short_by") if short else None,
|
|
235
|
+
topic=options.get("topic"),
|
|
236
|
+
log=log,
|
|
237
|
+
versions=[version_entry(today, short)] if short else [],
|
|
238
|
+
)
|
|
239
|
+
return _write_new(folder, template)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def update(memory: Memory, today: datetime.date, **changes) -> Memory:
|
|
243
|
+
"""Rewrite the memory's file with the given frontmatter keys changed or added; a value of None removes the key.
|
|
244
|
+
|
|
245
|
+
The reserved name `body` replaces the body instead. Keys this module does not know and the rest of the body
|
|
246
|
+
survive; the file is replaced through a temporary one. `today` is the date of the action: callers put it into
|
|
247
|
+
the keys they change, as dates are written as ISO strings. Returns the memory read back from the file."""
|
|
248
|
+
meta, body = _split(memory.path.read_text(encoding="utf-8"))
|
|
249
|
+
body = changes.pop("body", body)
|
|
250
|
+
new_short = changes.get("short")
|
|
251
|
+
if new_short is not None:
|
|
252
|
+
current = _parse(memory.path, memory.scope)
|
|
253
|
+
if new_short != current.short:
|
|
254
|
+
kept = [(on, text) for on, text in version_list(current) if on != today]
|
|
255
|
+
meta["versions"] = [
|
|
256
|
+
version_entry(on, text)
|
|
257
|
+
for on, text in sorted([*kept, (today, new_short)], key=lambda v: v[0])
|
|
258
|
+
]
|
|
259
|
+
for key, value in changes.items():
|
|
260
|
+
if value is None:
|
|
261
|
+
meta.pop(key, None)
|
|
262
|
+
else:
|
|
263
|
+
meta[key] = value.isoformat() if isinstance(value, datetime.date) else value
|
|
264
|
+
head = yaml.safe_dump(
|
|
265
|
+
meta, sort_keys=False, allow_unicode=True, default_flow_style=False, width=10**6
|
|
266
|
+
)
|
|
267
|
+
safe_io.replace_file(memory.path, f"---\n{head}---\n{body}".encode())
|
|
268
|
+
return _parse(memory.path, memory.scope)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def observe(memory: Memory, today: datetime.date) -> Memory:
|
|
272
|
+
return update(memory, today, observed=memory.observed + 1, last_observed=today)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _log_with(memory: Memory, key: str, on: datetime.date, outcome: str) -> list[str] | None:
|
|
276
|
+
"""The log after adding the case of session `key`, or None when it adds nothing (see `has_case`)."""
|
|
277
|
+
if has_case(memory, key, outcome):
|
|
278
|
+
return None
|
|
279
|
+
return [*memory.log, case_entry(on, key, outcome)]
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def add_case(
|
|
283
|
+
memory: Memory, session: str, on: datetime.date, outcome: str, today: datetime.date
|
|
284
|
+
) -> tuple[Memory, bool]:
|
|
285
|
+
"""Add the case of `session` (any spelling of a session source) to the log; False and no write when it adds
|
|
286
|
+
nothing. Not a session or an unknown outcome: ValueError."""
|
|
287
|
+
key = session_key(session)
|
|
288
|
+
if key is None:
|
|
289
|
+
raise ValueError(f"{session!r} is not a session source: write it as 'session <id>'")
|
|
290
|
+
if outcome not in OUTCOMES:
|
|
291
|
+
raise ValueError(f"unknown outcome {outcome!r}")
|
|
292
|
+
log = _log_with(memory, key, on, outcome)
|
|
293
|
+
if log is None:
|
|
294
|
+
return memory, False
|
|
295
|
+
return update(memory, today, log=log), True
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
class SightingOptions(TypedDict, total=False):
|
|
299
|
+
"""The keyword options of `add_sighting`."""
|
|
300
|
+
|
|
301
|
+
outcome: str # "seen"
|
|
302
|
+
on: datetime.date | None # None: today
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _checked_sighting(session: str, outcome: str) -> tuple[str, str | None]:
|
|
306
|
+
"""(key, project) of the session entry; ValueError when it is no session source or the outcome is unknown."""
|
|
307
|
+
found = sighting(session)
|
|
308
|
+
if found is None:
|
|
309
|
+
raise ValueError(f"{session!r} is not a session source: write it as 'session <id>'")
|
|
310
|
+
if outcome not in OUTCOMES:
|
|
311
|
+
raise ValueError(f"unknown outcome {outcome!r}")
|
|
312
|
+
return found
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _noted_body(memory: Memory, note: str | None) -> dict:
|
|
316
|
+
"""The `body` change that appends `note`, empty without a note."""
|
|
317
|
+
if not (note and note.strip()):
|
|
318
|
+
return {}
|
|
319
|
+
head = memory.body if memory.body.endswith("\n") or not memory.body else memory.body + "\n"
|
|
320
|
+
return {"body": f"{head}{' '.join(note.split())}\n"}
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def add_sighting(
|
|
324
|
+
memory: Memory,
|
|
325
|
+
session: str,
|
|
326
|
+
today: datetime.date,
|
|
327
|
+
note: str | None = None,
|
|
328
|
+
**options: Unpack[SightingOptions],
|
|
329
|
+
) -> tuple[Memory, bool]:
|
|
330
|
+
"""Record that another session shows the memory: `session` is a full source entry ("session <id>", with
|
|
331
|
+
" project <key>" when known).
|
|
332
|
+
|
|
333
|
+
Not a session entry: ValueError. Already counted (under any spelling, with its project when given): the memory
|
|
334
|
+
unchanged and False, with no write. A session counted without a project that now comes with one gains the
|
|
335
|
+
project (True, `observed` unchanged). Else the normalized entry is added, `observed` raised as `observe`
|
|
336
|
+
does and the note appended to the body; a transcript memory also gets `standing_changes`.
|
|
337
|
+
|
|
338
|
+
The case (`outcome`, dated `on` or today) goes to the log in the same write, unless the log already holds it;
|
|
339
|
+
a counted session whose case is new still writes, and the flag stays False."""
|
|
340
|
+
outcome = options.get("outcome", "seen")
|
|
341
|
+
key, project = _checked_sighting(session, outcome)
|
|
342
|
+
log = _log_with(memory, key, options.get("on") or today, outcome)
|
|
343
|
+
changes: dict = {} if log is None else {"log": log}
|
|
344
|
+
if key in sessions(memory):
|
|
345
|
+
if counted(memory, session):
|
|
346
|
+
return (memory, False) if log is None else (update(memory, today, **changes), False)
|
|
347
|
+
sources = normalized_sources([
|
|
348
|
+
sighting_entry(key, project) if (f := sighting(s)) and f[0] == key else s
|
|
349
|
+
for s in memory.sources
|
|
350
|
+
])
|
|
351
|
+
else:
|
|
352
|
+
sources = [*memory.sources, sighting_entry(key, project)]
|
|
353
|
+
changes.update({"observed": memory.observed + 1, "last_observed": today})
|
|
354
|
+
changes.update(_noted_body(memory, note))
|
|
355
|
+
changes["sources"] = sources
|
|
356
|
+
if memory.origin == "transcript":
|
|
357
|
+
changes.update(standing_changes(memory, replace(memory, sources=sources), today))
|
|
358
|
+
return update(memory, today, **changes), True
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Notes: frontmatter and the `Note` model, the index and the validators.
|
|
2
|
+
|
|
3
|
+
`check`: check rule catalog and `check()`; pure
|
|
4
|
+
`due`: requirement rows and due queries; pure
|
|
5
|
+
`fields`: field rules of a note's frontmatter; pure
|
|
6
|
+
`index`: generated index READMEs and `apply_index`
|
|
7
|
+
`links`: link rules: relative links resolve, `orphan_notes`; pure
|
|
8
|
+
`note`: frontmatter, YAML loaders, `Note`, topics, handles
|
|
9
|
+
`search`: BM25F ranking, filters, `find`/`search`, links, mentions and the search-eval table; pure
|
|
10
|
+
`split_candidates`: synthesis split candidate detection
|
|
11
|
+
|
|
12
|
+
A base layer like `core`: imports stdlib, `core`, `memories`, `syntheses` and `notes` only.
|
|
13
|
+
"""
|