keepfold 0.6.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. keepfold/__init__.py +1 -0
  2. keepfold/_proc.py +102 -0
  3. keepfold/access.py +154 -0
  4. keepfold/agent_eval.py +162 -0
  5. keepfold/agent_text.py +56 -0
  6. keepfold/anki.py +285 -0
  7. keepfold/app/__init__.py +5 -0
  8. keepfold/app/actions.py +690 -0
  9. keepfold/app/desktop.py +677 -0
  10. keepfold/app/exports.py +254 -0
  11. keepfold/app/hello.py +79 -0
  12. keepfold/app/launch.py +114 -0
  13. keepfold/app/news.py +60 -0
  14. keepfold/app/server.py +3142 -0
  15. keepfold/app/status.py +811 -0
  16. keepfold/app/targets.py +1374 -0
  17. keepfold/app/winpath.py +54 -0
  18. keepfold/app/wizard.py +506 -0
  19. keepfold/ask.py +475 -0
  20. keepfold/askfile.py +322 -0
  21. keepfold/assets/LICENSE-d3.txt +13 -0
  22. keepfold/assets/agent_eval.json +235 -0
  23. keepfold/assets/app/app.css +611 -0
  24. keepfold/assets/app/app.js +2712 -0
  25. keepfold/assets/app/capture.html +16 -0
  26. keepfold/assets/app/capture.js +91 -0
  27. keepfold/assets/app/index.html +149 -0
  28. keepfold/assets/brain3d.js +3730 -0
  29. keepfold/assets/chat_eval.json +454 -0
  30. keepfold/assets/d3.v7.min.js +2 -0
  31. keepfold/assets/dashboard.css +774 -0
  32. keepfold/assets/dashboard.html.tmpl +170 -0
  33. keepfold/assets/dashboard.js +4262 -0
  34. keepfold/assets/help/GUIDE.md +544 -0
  35. keepfold/assets/help/help.md +83 -0
  36. keepfold/assets/keepfold.ico +0 -0
  37. keepfold/assets/whats_new.json +162 -0
  38. keepfold/backup.py +100 -0
  39. keepfold/brainmap.py +1382 -0
  40. keepfold/browse/__init__.py +10 -0
  41. keepfold/browse/build.py +1320 -0
  42. keepfold/browse/forget.py +510 -0
  43. keepfold/browse/legacy.py +95 -0
  44. keepfold/browse/lists.py +285 -0
  45. keepfold/browse/privacy.py +391 -0
  46. keepfold/browse/selftest.py +166 -0
  47. keepfold/browse/sites.py +1068 -0
  48. keepfold/browse/sources.py +329 -0
  49. keepfold/browse/store.py +991 -0
  50. keepfold/browse/takeout.py +312 -0
  51. keepfold/browse/titles.py +127 -0
  52. keepfold/browse/vectors.py +326 -0
  53. keepfold/browse_serve.py +332 -0
  54. keepfold/catalog.py +564 -0
  55. keepfold/chat.py +1464 -0
  56. keepfold/chat_archive.py +165 -0
  57. keepfold/chat_eval.py +583 -0
  58. keepfold/chat_facts.py +721 -0
  59. keepfold/chat_import.py +1045 -0
  60. keepfold/chat_pages.py +291 -0
  61. keepfold/chat_study.py +371 -0
  62. keepfold/chats.py +669 -0
  63. keepfold/claims.py +650 -0
  64. keepfold/cli.py +3254 -0
  65. keepfold/clients.py +96 -0
  66. keepfold/cloudllm.py +135 -0
  67. keepfold/contract.py +43 -0
  68. keepfold/corrections.py +134 -0
  69. keepfold/dashboard.py +959 -0
  70. keepfold/dates.py +202 -0
  71. keepfold/delta.py +146 -0
  72. keepfold/digest.py +72 -0
  73. keepfold/doctor.py +565 -0
  74. keepfold/duplicates.py +145 -0
  75. keepfold/egress.py +68 -0
  76. keepfold/eval_history.py +109 -0
  77. keepfold/events.py +554 -0
  78. keepfold/export_context.py +109 -0
  79. keepfold/fact_harvest.py +578 -0
  80. keepfold/forget.py +720 -0
  81. keepfold/harvest.py +334 -0
  82. keepfold/home.py +714 -0
  83. keepfold/importers.py +627 -0
  84. keepfold/index.py +733 -0
  85. keepfold/know.py +40 -0
  86. keepfold/learning_eval.py +261 -0
  87. keepfold/levels.py +595 -0
  88. keepfold/life_sources.py +747 -0
  89. keepfold/lint.py +241 -0
  90. keepfold/localllm.py +699 -0
  91. keepfold/loops.py +316 -0
  92. keepfold/mcp_server.py +4464 -0
  93. keepfold/migrate.py +552 -0
  94. keepfold/more_sources.py +709 -0
  95. keepfold/packs.py +148 -0
  96. keepfold/people.py +99 -0
  97. keepfold/planner.py +819 -0
  98. keepfold/prime.py +630 -0
  99. keepfold/prime_hook.py +265 -0
  100. keepfold/profiles.py +118 -0
  101. keepfold/quarantine.py +123 -0
  102. keepfold/recall_log.py +93 -0
  103. keepfold/redteam.py +393 -0
  104. keepfold/reflect.py +164 -0
  105. keepfold/relink.py +477 -0
  106. keepfold/render.py +406 -0
  107. keepfold/review.py +1181 -0
  108. keepfold/rollups.py +412 -0
  109. keepfold/safety_net.py +571 -0
  110. keepfold/sample.py +103 -0
  111. keepfold/sample_vault/areas/programming.algorithms.md +11 -0
  112. keepfold/sample_vault/areas/programming.basics.md +11 -0
  113. keepfold/sample_vault/concepts/big-o-notation.md +13 -0
  114. keepfold/sample_vault/concepts/functions.md +13 -0
  115. keepfold/sample_vault/concepts/loops.md +14 -0
  116. keepfold/sample_vault/concepts/recursion.md +13 -0
  117. keepfold/sample_vault/domains/programming.md +10 -0
  118. keepfold/sample_vault/journal/2026-01-12.md +9 -0
  119. keepfold/sample_vault/me/goals.md +17 -0
  120. keepfold/sample_vault/me/profile.md +19 -0
  121. keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
  122. keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
  123. keepfold/sample_vault/problems/fizzbuzz.md +12 -0
  124. keepfold/sample_vault/projects/text-adventure.md +15 -0
  125. keepfold/sample_vault/resources/python-tutorial.md +16 -0
  126. keepfold/semantic.py +1254 -0
  127. keepfold/session.py +764 -0
  128. keepfold/share.py +69 -0
  129. keepfold/sources.py +612 -0
  130. keepfold/sync_copies.py +83 -0
  131. keepfold/tags.py +230 -0
  132. keepfold/taint.py +301 -0
  133. keepfold/tonight.py +195 -0
  134. keepfold/topics.py +1072 -0
  135. keepfold/update.py +300 -0
  136. keepfold/vault.py +942 -0
  137. keepfold/vecstore.py +218 -0
  138. keepfold/voice.py +260 -0
  139. keepfold/voice_memos.py +280 -0
  140. keepfold/watch.py +303 -0
  141. keepfold/where.py +119 -0
  142. keepfold/xray.py +516 -0
  143. keepfold/zotero.py +303 -0
  144. keepfold-0.6.4.dist-info/METADATA +644 -0
  145. keepfold-0.6.4.dist-info/RECORD +148 -0
  146. keepfold-0.6.4.dist-info/WHEEL +4 -0
  147. keepfold-0.6.4.dist-info/entry_points.txt +6 -0
  148. keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
keepfold/sources.py ADDED
@@ -0,0 +1,612 @@
1
+ """The one shape every `keepfold import` source plugs into (v9 item 13).
2
+
3
+ A `Source` says what it is (id, label, what it reads, its default tier) and yields `Item`s, or a
4
+ reason string for each entry it skips. `run` does the rest, the same for every source: the
5
+ never-capture filter (`scrub`), secret redaction, the quality gate (`unreadable`: garbled,
6
+ symbol, link-list and repeated text is kept out), the tier, dedupe, the page write through the
7
+ vault, the dry run and the report counts (`importers.report_line` prints them).
8
+
9
+ Two page shapes. `page="item"`: one `resource` page per item, `<prefix>-<title slug>`, deduped by
10
+ a sha of the item's text (notes; PDFs, highlights and mail fit here). `page="month"`: one page per
11
+ month, `<prefix>-YYYY-MM` (`<prefix>-private-YYYY-MM` when private, so private items never join a
12
+ public page), a line per item, deduped by the line (calendars; location, photo dates and Spotify
13
+ fit here). Both carry a `Source: <label> · Date: …` line (see importers' docstring). An item
14
+ source that sets `updates` dedupes by `key` (a repo's path, a book) and rewrites that page when
15
+ a re-import brings a changed text (the header's `body:` sha), keeping the owner's frontmatter,
16
+ instead of adding a second page; an unchanged text leaves the page alone.
17
+
18
+ Tiers reuse `access.Audience`: `--tier private|normal|skip` is LOCAL (pages `private: true`),
19
+ CLOUD (normal pages) or SKIP (nothing imported). The last choice per source is kept in TIERS_FILE.
20
+
21
+ What Keepfold never captures (docs/PRIVACY.md), and where each line is enforced:
22
+ - secrets, keys, passwords: `scrub` here for every source (chats.redact), and
23
+ vault.scan_secrets on every write;
24
+ - sign-in, payment and bank pages: browse.privacy.drop_reason (browse.lists AUTH/PAY/BANK);
25
+ - adult browsing: browse.privacy.Settings.adult defaults to "skip";
26
+ - AI replies in chat imports: chat_import keeps the user's own turns only;
27
+ - code, diffs, command output from AI chats and coding sessions: chat_import (user turns only;
28
+ a coding session keeps paths and commit subjects only). A source of such text sets
29
+ `drops_code` and `scrub` drops its fenced code; the owner's own notes keep their code;
30
+ - image or audio content: an Item is text only; importers' notes source skips non-text files
31
+ and drops embeds;
32
+ - other people's quoted text in mail: `scrub` here, for a source that sets `strips_quotes`
33
+ (mail); the owner's own notes and calendar keep what they quote;
34
+ - location finer than a city: `scrub` here rounds coordinates to 0.1 degree (about 10 km), for
35
+ a source that sets `coarse_place` (location, photos); notes and calendar keep theirs;
36
+ - inferred health, sexuality, religion or politics labels: no code infers labels about the
37
+ person; browse.lists' categories with those names only keep such visits local.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import hashlib
43
+ import json
44
+ import re
45
+ import unicodedata
46
+ from collections import defaultdict
47
+ from collections.abc import Callable, Iterable
48
+ from dataclasses import dataclass, field
49
+ from pathlib import Path, PurePosixPath
50
+
51
+ from ruamel.yaml.comments import CommentedMap
52
+
53
+ from keepfold import chats
54
+ from keepfold.access import Audience
55
+ from keepfold.catalog import slugify
56
+ from keepfold.vault import Vault, VaultError, _dump_fm, _to_yaml, is_private
57
+
58
+ TIERS_FILE = ".keepfold/import-tiers.json" # {source id: "local" | "cloud" | "skip"}
59
+ WORDS = {"private": Audience.LOCAL, "normal": Audience.CLOUD, "skip": Audience.SKIP}
60
+ CODE_LEFT_OUT = "[code left out]"
61
+
62
+ _HASH = re.compile(r"· sha: ([0-9a-f]{16})$", re.M)
63
+ _DAY_LINE = re.compile(r"- (\d{4}-\d\d-\d\d): ") # a month page's per-day summary line
64
+ # an item page's header line: label, date, origin, and (RR-18, by_origin sources) a body sha
65
+ HEADER = re.compile(r"^Source: (.+?) · Date: (\S+)(?: · From: (.*?))?"
66
+ r"(?: · body: ([0-9a-f]{16}))? · sha: [0-9a-f]{16}$", re.M)
67
+ SHOWN_EDITED = 5 # Review cards of hand-edited imported pages shown at a time
68
+ EDITED = "you edited the page; it was left as it is" # a `keeps_edits` source's skip reason
69
+ _WIKI = re.compile(r"(!?)\[\[([^\]|#]+)(?:#[^\]|]*)?(?:\|([^\]]+))?\]\]")
70
+ _FENCE = re.compile(r"^[ \t]{0,3}(`{3,}|~{3,})")
71
+ # "On Tue, 3 Nov 2026 at 09:30, Asha <her address> wrote:", which mail clients may wrap once
72
+ _ATTRIBUTION = re.compile(r"^On [^\n]{1,200}(?:\n[^\n]{0,200})?wrote:[ \t]*\r?$", re.M)
73
+ _QUOTED = re.compile(r"^[ \t]*>[^\n]*(?:\n|\Z)", re.M)
74
+ _FORWARDED = re.compile(r"^[ \t]*-{2,}[ \t]*(?:Original Message|Forwarded message)[ \t]*-{2,}",
75
+ re.M | re.I)
76
+ # shortcut: only "lat, lon" pairs with 4+ decimals (about 10 m); a source that reads a location
77
+ # history (item 14) reduces its own places to a city per day
78
+ _COORDS = re.compile(r"(?<![\d.])(-?\d{1,2}\.\d{4,})(\s*,\s*)(-?\d{1,3}\.\d{4,})(?![\d.])")
79
+ # the quality gate (`unreadable`): an item under GATE_MIN characters is never judged
80
+ GATE_MIN = 200
81
+ UNREADABLE = ("garbled", "mostly symbols", "link list", "repetitive") # the report's order
82
+ _URL = re.compile(r"\b(?:https?://|www\.)\S+", re.I)
83
+
84
+
85
+ @dataclass
86
+ class Item:
87
+ title: str
88
+ date: str # YYYY-MM-DD
89
+ text: str # an item page's body, or a month page's line
90
+ origin: str = "" # the file path or URL it came from, shown as `From:`
91
+ tags: list[str] = field(default_factory=list)
92
+ private: bool = False # the item itself asks to be private (a note's frontmatter)
93
+ key: str = "" # what dedupe hashes when it is not `text` (a note: with its frontmatter)
94
+ who: str = "" # R3-6: the person the item is by or with, when the source knows (an author)
95
+ summary: str = "" # R3-6: the item's own summary, when it has one (a note's frontmatter)
96
+ aliases: list[str] = field(default_factory=list) # R13d-2: a note's checked `aliases:`
97
+
98
+
99
+ @dataclass
100
+ class Source:
101
+ id: str # the key its tier is remembered under: "notes", "calendar"
102
+ label: str # its pages' `Source:` line: "Obsidian", "Calendar"
103
+ reads: str # "folder" or "file"
104
+ items: Callable[[], Iterable[Item | str]] # a str is an entry skipped, and why
105
+ default_tier: Audience = Audience.CLOUD
106
+ page: str = "item" # "item" or "month"
107
+ prefix: str = "" # page ids; the id when empty
108
+ noun: str = "items" # a month page's heading and summary: "events"
109
+ skips: tuple[str, ...] = () # the skip reasons, in the order the report lists them
110
+ # the never-capture filters past secrets, for text that is not the owner's own writing
111
+ drops_code: bool = False # AI or tool text: fenced code becomes CODE_LEFT_OUT
112
+ strips_quotes: bool = False # mail: other people's quoted text is dropped
113
+ coarse_place: bool = False # location, photos: coordinates rounded to 0.1 degree
114
+ updates: bool = False # a known `key` rewrites its page when the text changed (repos)
115
+ # `updates`: a page's figure (Spotify hours, mail messages); a re-import with a smaller one
116
+ # (a partial export) leaves the page as it is
117
+ size: Callable[[str], float] | None = None
118
+ # R17 (docs) `updates`: a page is rewritten only while its body is as the import wrote it
119
+ # (`_edited`); an owner-edited page stays as it is, counted under EDITED. A page another
120
+ # source wrote, or whose body is the same, is a duplicate
121
+ keeps_edits: bool = False
122
+ not_summary: re.Pattern | None = None # lines never taken as a page's summary (docs' headings)
123
+ # RR-18 (notes): a changed file at a known `From:` origin rewrites that page when its body
124
+ # is as the import wrote it (the header's `body:` sha); `walk_errors` (folders the walk
125
+ # could not read) keeps the report from counting pages as gone from the folder
126
+ by_origin: bool = False
127
+ walk_errors: list = field(default_factory=list)
128
+ # G5b-10 (notes: loops.from_notes): called (vault, item, page id, private, report) for each
129
+ # item page written or rewritten, never in a dry run
130
+ made: Callable[[Vault, Item, str, bool, dict], None] | None = None
131
+ vault: Vault | None = None # set by `run`, for items that need it (voice memos' prompt)
132
+
133
+
134
+ def tier(value: str | Audience) -> Audience:
135
+ """`private`, `normal` or `skip` (the CLI's words), or an Audience value (the app's)."""
136
+ try:
137
+ return WORDS.get(value) or Audience(value)
138
+ except ValueError:
139
+ raise ValueError(f"tier must be one of {', '.join(WORDS)}.") from None
140
+
141
+
142
+ def word(t: Audience) -> str:
143
+ return next(w for w, a in WORDS.items() if a is t)
144
+
145
+
146
+ def remembered(vault: Vault) -> dict[str, Audience]:
147
+ try:
148
+ d = json.loads((vault.root / TIERS_FILE).read_text("utf-8"))
149
+ except (OSError, ValueError):
150
+ return {}
151
+ return {k: Audience(v) for k, v in d.items() if v in set(Audience)} \
152
+ if isinstance(d, dict) else {}
153
+
154
+
155
+ def pick_tier(vault: Vault, src: Source, given: str | None = None,
156
+ ask: Callable[[Source], str] | None = None,
157
+ save: bool = True, said: Callable[[str], object] | None = None
158
+ ) -> tuple[Audience, str]:
159
+ """(tier, how it was chosen): `given` (the --tier flag or the app's click), else the last
160
+ choice for this source, else `ask` (a real terminal), else the source's default. A given or
161
+ asked choice is remembered when `save` (not in a dry run), and a stricter one reaches the
162
+ pages already imported (`tighten`); its one line goes to `said`."""
163
+ last = remembered(vault)
164
+ if given is None and src.id in last:
165
+ return last[src.id], "your last choice"
166
+ if given is None and ask is None:
167
+ return src.default_tier, "the default"
168
+ t = tier(given if given is not None else ask(src))
169
+ if save:
170
+ vault.write_text(vault.root / TIERS_FILE, json.dumps(
171
+ {k: v.value for k, v in {**last, src.id: t}.items()}, indent=1, sort_keys=True)
172
+ + "\n")
173
+ if (line := tighten(vault, src, last.get(src.id, src.default_tier), t)) and said:
174
+ said(line)
175
+ return t, "chosen"
176
+
177
+
178
+ _STRICT = (Audience.CLOUD, Audience.LOCAL, Audience.SKIP) # loosest first
179
+
180
+
181
+ def _labels(src: Source) -> set[str]:
182
+ """Every `Source:` label a tier key's pages carry: notes import as Obsidian, Notion or
183
+ Notes, highlights as Highlights or Pocket."""
184
+ from keepfold import importers # it imports this module
185
+ return {src.label, *{"notes": importers.LABELS.values(),
186
+ "highlights": ("Highlights", "Pocket")}.get(src.id, ())}
187
+
188
+
189
+ def source_pages(vault: Vault, src: Source) -> list[Path]:
190
+ """The pages earlier imports of `src`'s tier key wrote: resources/ pages whose header line
191
+ (just under the title) is `Source: <one of its labels> · Date: …`."""
192
+ labels, out = _labels(src), []
193
+ for p in sorted((vault.root / "resources").glob("*.md")):
194
+ try: # an import page's frontmatter is short: its first 8 KB hold the header line
195
+ with p.open("rb") as f:
196
+ head = f.read(8192).decode("utf-8", "replace").split("\n---\n", 1)[-1]
197
+ except OSError:
198
+ continue
199
+ m = re.search(r"^Source: (.+?) · Date: ", "\n".join(head.split("\n")[:6]), re.M)
200
+ if m and m.group(1) in labels:
201
+ out.append(p)
202
+ return out
203
+
204
+
205
+ def tighten(vault: Vault, src: Source, old: Audience, new: Audience) -> str | None:
206
+ """RR-29: a stricter tier reaches the pages already imported. To private: each of
207
+ `source_pages` not private yet gets `private: true` (through the vault). To skip: nothing
208
+ is deleted; the line says how many pages are still there and how to forget them. A looser
209
+ or the same tier changes nothing (never un-privates). The line to show, or None."""
210
+ if _STRICT.index(new) <= _STRICT.index(old):
211
+ return None
212
+ pages = source_pages(vault, src)
213
+ if new is Audience.SKIP:
214
+ n = len(pages)
215
+ return (f"{n:,} page{'s' * (n != 1)} from {src.label} {'are' if n != 1 else 'is'} "
216
+ f"still in your vault; to forget them, delete the pages in resources/ that say "
217
+ f"\"Source: {src.label}\" under their title.") if n else None
218
+ made = 0
219
+ for p in pages:
220
+ try:
221
+ if is_private(vault.read_path(p)):
222
+ continue
223
+ vault._edit_fields("resource", p.stem, {"private": True})
224
+ except VaultError: # a page with broken frontmatter is left as it is
225
+ continue
226
+ made += 1
227
+ return f"Made {made:,} earlier page{'s' * (made != 1)} from {src.label} private." \
228
+ if made else None
229
+
230
+
231
+ def _coarse(m: re.Match) -> str:
232
+ lat, lon = float(m.group(1)), float(m.group(3))
233
+ if abs(lat) > 90 or abs(lon) > 180:
234
+ return m.group(0)
235
+ return f"{lat:.1f}{m.group(2)}{lon:.1f}"
236
+
237
+
238
+ def scrub(text: str, src: Source | None = None) -> str:
239
+ """The never-capture filter every imported text passes: secrets become [redacted], always.
240
+ Per `src`: `drops_code` turns fenced code blocks into CODE_LEFT_OUT, `strips_quotes` drops
241
+ quoted mail (the `>` lines after an "On … wrote:" line, and everything from an "Original
242
+ Message" or "Forwarded message" line on), `coarse_place` rounds coordinates to 0.1 degree."""
243
+ drops_code = bool(src and src.drops_code)
244
+ out, fence = [], ""
245
+ for line in text.splitlines(keepends=True) if drops_code else ():
246
+ if fence:
247
+ s = line.strip()
248
+ if s.startswith(fence) and not s.strip(fence[0]):
249
+ fence = ""
250
+ continue
251
+ if m := _FENCE.match(line):
252
+ fence = m.group(1)
253
+ out.append(CODE_LEFT_OUT + ("\n" if line.endswith("\n") else ""))
254
+ continue
255
+ out.append(line)
256
+ text = "".join(out) if drops_code else text
257
+ if src and src.strips_quotes:
258
+ if m := _ATTRIBUTION.search(text):
259
+ text = text[:m.start()] + _QUOTED.sub("", text[m.end():])
260
+ if m := _FORWARDED.search(text):
261
+ text = text[:m.start()]
262
+ if src and src.coarse_place:
263
+ text = _COORDS.sub(_coarse, text)
264
+ return chats.redact(text)
265
+
266
+
267
+ def link_lines(lines: list[str]) -> int:
268
+ """How many of `lines` are mostly a web address (over half their non-space characters)."""
269
+ return sum(2 * sum(len(u) for u in _URL.findall(ln)) > len(ln.replace(" ", ""))
270
+ for ln in lines)
271
+
272
+
273
+ def unreadable(text: str) -> str | None:
274
+ """Why an item's text is garbage (an UNREADABLE reason), or None when it reads as text:
275
+ U+FFFD over 5% of its non-space characters (a bad decode), letters, digits and marks under
276
+ 25% of them, over 60% of its non-empty lines mostly a URL, or 10+ lines of which under 30%
277
+ are distinct. Text under GATE_MIN characters always passes."""
278
+ chars = [c for c in text if not c.isspace()]
279
+ if len(text) < GATE_MIN or not chars:
280
+ return None
281
+ if text.count("�") > 0.05 * len(chars):
282
+ return "garbled"
283
+ # a mark counts: a Devanagari or Tamil vowel sign is a mark, not a letter
284
+ if sum(c.isalnum() or unicodedata.category(c)[0] == "M" for c in chars) < 0.25 * len(chars):
285
+ return "mostly symbols"
286
+ lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
287
+ if link_lines(lines) > 0.6 * len(lines):
288
+ return "link list"
289
+ if len(lines) >= 10 and len(set(lines)) < 0.3 * len(lines):
290
+ return "repetitive"
291
+ return None
292
+
293
+
294
+ def _sha(text: str) -> str:
295
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
296
+
297
+
298
+ def _free_id(vault: Vault, base: str, taken: set[str]) -> str:
299
+ """`base`, or `base-2`, `-3`… when a page of any kind (ids are unique across kinds) or this
300
+ import already has it."""
301
+ nid, n = base, 2
302
+ while nid in taken or any((vault.root / d / f"{nid}.md").exists()
303
+ for k in vault.KIND_DIRS for d in vault.dirs(k)):
304
+ nid = f"{base[:78].rstrip('-.')}-{n}"
305
+ n += 1
306
+ taken.add(nid)
307
+ return nid
308
+
309
+
310
+ def _known_hashes(vault: Vault) -> dict[str, Path | None]:
311
+ """sha -> the page that carries it."""
312
+ return {h: p for p in (vault.root / "resources").glob("*.md")
313
+ for h in _HASH.findall(p.read_text("utf-8", errors="replace"))}
314
+
315
+
316
+ def run(vault: Vault, src: Source, tier: Audience = Audience.CLOUD,
317
+ dry_run: bool = False) -> dict:
318
+ """Import `src` at `tier`. The report: `read` (entries, skipped ones too), `imported` (new
319
+ pages for item sources, new lines for month sources), `private`, `duplicate`, `reasons`
320
+ (skip reason -> count), `items` (items read), `pages` (pages they belong on) and `updated`
321
+ (pages rewritten by a source that `updates` or `by_origin`), `unreadable` (quality-gate
322
+ reason -> count: the items `unreadable` kept out, for every source) and, for a `by_origin`
323
+ source, `gone` (earlier pages whose file was not in this walk: counted, never deleted, and
324
+ not counted when the walk had errors), and the counts a `made` hook adds (notes: `loops`,
325
+ `loops_over`, `loops_unsafe`)."""
326
+ r = {"read": 0, "imported": 0, "private": 0, "duplicate": 0, "updated": 0,
327
+ "reasons": dict.fromkeys(src.skips, 0), "items": 0, "pages": 0, "tier": tier.value,
328
+ "unreadable": {}}
329
+ if tier is Audience.SKIP:
330
+ return r
331
+ src.vault = vault
332
+ (_items if src.page == "item" else _months)(vault, src, tier is Audience.LOCAL, dry_run, r)
333
+ return r
334
+
335
+
336
+ def _read(src: Source, r: dict, walked: set[str] | None = None):
337
+ for it in src.items():
338
+ r["read"] += 1
339
+ if isinstance(it, str):
340
+ r["reasons"][it] = r["reasons"].get(it, 0) + 1
341
+ continue
342
+ if walked is not None: # every origin the walk saw, a gated item's too
343
+ walked.add(scrub(it.origin, src))
344
+ it.text = it.text.replace("\r\n", "\n") # as `untouched` reads a page back
345
+ if bad := unreadable(it.text):
346
+ r["unreadable"][bad] = r["unreadable"].get(bad, 0) + 1
347
+ else:
348
+ r["items"] += 1
349
+ yield it
350
+
351
+
352
+ def _items(vault: Vault, src: Source, private: bool, dry_run: bool, r: dict) -> None:
353
+ known, seen, taken, todo = _known_hashes(vault), set(), set(), []
354
+ origins, walked = (_by_origin(vault, src), set()) if src.by_origin else ({}, None)
355
+ for it in _read(src, r, walked):
356
+ h = _sha(it.key or it.text)
357
+ old = known.get(h)
358
+ if h in seen or (h in known and not (src.updates and old)):
359
+ r["duplicate"] += 1
360
+ continue
361
+ seen.add(h)
362
+ if old: # `updates`: compared with its page below; a private page stays private
363
+ todo.append((old.stem, it, h, private or it.private or _was_private(vault, old),
364
+ old))
365
+ continue
366
+ at = origins.get(scrub(it.origin, src)) if it.origin else None
367
+ if at and untouched(at[1]): # RR-18: a hand-edited page keeps its text: a new page
368
+ todo.append((at[0].stem, it, h, private or it.private or _was_private(vault, at[0]),
369
+ at[0]))
370
+ continue
371
+ # the id comes from the filtered title, so a key in a title never reaches a file name
372
+ slug = slugify(scrub(it.title, src)) or "untitled"
373
+ nid = _free_id(vault, f"{src.prefix or src.id}-{slug}"[:81].rstrip("-."), taken)
374
+ todo.append((nid, it, h, private or it.private, None))
375
+ if walked is not None and not src.walk_errors:
376
+ r["gone"] = sum(o not in walked for o in origins)
377
+ new = [t for t in todo if t[4] is None]
378
+ r["imported"], r["pages"] = len(new), len(todo)
379
+ r["private"] = sum(t[3] for t in new)
380
+ if dry_run and len(new) == len(todo):
381
+ return
382
+ # [[Title]] links between this import's public pages keep working; others become plain text
383
+ ids = {slugify(it.title): nid for nid, it, _, hidden, _ in todo if not hidden}
384
+
385
+ def link(m):
386
+ if m.group(1): # an embedded image or file
387
+ return ""
388
+ to = ids.get(slugify(PurePosixPath(m.group(2)).stem))
389
+ text = m.group(3) or m.group(2)
390
+ return f"[[{to}|{text}]]" if to else text
391
+
392
+ def made(it, text): # the body text (no facts) the import writes for `it` holding `text`
393
+ return scrub(_WIKI.sub(link, text), src).strip().removeprefix(f"# {it.title}\n")
394
+
395
+ for nid, it, h, hidden, old in todo:
396
+ body = made(it, it.text)
397
+ first = next((s.strip("# ").strip() for s in body.splitlines() if s.strip("# ").strip()
398
+ and not (src.not_summary and src.not_summary.fullmatch(s.strip()))),
399
+ it.title)
400
+ fields = {"title": scrub(it.title, src), "kind": "resource", "resource_type": "other",
401
+ "status": "reference", "covers": [], "related": [], "date": it.date,
402
+ "summary": first[:160]}
403
+ if it.tags:
404
+ fields["tags"] = list(it.tags)
405
+ if it.aliases:
406
+ fields["aliases"] = [scrub(a, src) for a in it.aliases]
407
+ if hidden:
408
+ fields["private"] = True
409
+ origin = f" · From: {scrub(it.origin, src)}" if it.origin else ""
410
+ body = f"{facts(it, src)}\n\n{body}".strip()
411
+ # the facts are body too
412
+ mark = f" · body: {_sha(body)}" if src.by_origin or src.updates else ""
413
+ page = (f"# {fields['title']}\n\nSource: {src.label} · Date: {it.date}{origin}{mark}"
414
+ f" · sha: {h}\n\n{body}\n")
415
+ if old is None:
416
+ if not dry_run:
417
+ vault.create_note("resource", nid, fields, page)
418
+ if src.made:
419
+ src.made(vault, it, nid, hidden, r)
420
+ continue
421
+ cur = old.read_text("utf-8", errors="replace")
422
+ if not src.by_origin and (m := HEADER.search(cur)) and m.group(4) == _sha(body):
423
+ r["duplicate"] += 1 # `updates`: the same text as last time; the owner's edits stay
424
+ continue
425
+ was = made(it, it.key or it.text) if src.keeps_edits else "" # as its key's page holds
426
+ if src.keeps_edits and (m := HEADER.search(cur)) and (
427
+ m.group(1) not in _labels(src) or _rest(cur, m) == body
428
+ or (it.origin and m.group(3) and m.group(3) != scrub(it.origin, src))):
429
+ # another source's page, the same body (no mark yet), or another file that opens
430
+ # with the same text (the key): never rewrite a page another file made
431
+ r["duplicate"] += 1
432
+ continue
433
+ if src.keeps_edits and _edited(cur, was):
434
+ r["reasons"][EDITED] = r["reasons"].get(EDITED, 0) + 1
435
+ continue
436
+ if src.size and src.size(body) < src.size(cur):
437
+ r["reasons"]["less than the page already has"] = \
438
+ r["reasons"].get("less than the page already has", 0) + 1
439
+ continue
440
+ # the owner's tags, links and status stay; the import's own keys move
441
+ fields = {**(_fields(vault, old) or fields),
442
+ **{k: fields[k] for k in ("title", "date", "summary", "aliases") if k in fields},
443
+ **({"private": True} if hidden else {})}
444
+ text = _note_text(nid, fields, page)
445
+ if cur == text:
446
+ r["duplicate"] += 1
447
+ continue
448
+ r["updated"] += 1
449
+ r["private"] += hidden
450
+ if not dry_run: # by_origin, keeps_edits: a page edited since the check keeps its edit
451
+ vault.update_text(old, lambda cur, t=text, was=was: cur if (
452
+ src.by_origin and untouched(cur) is False) or (
453
+ src.keeps_edits and _edited(cur, was)) else t)
454
+ if src.made:
455
+ src.made(vault, it, nid, hidden, r)
456
+
457
+
458
+ SUMMARY_CHARS = 200
459
+
460
+
461
+ def facts(it: Item, src: Source) -> str:
462
+ """R3-6: the fact header an item page's body starts with, so the page's first passage
463
+ answers alone: `When:` (the item's date), then `Who:` and `Summary:` only when the source
464
+ knows them (a book's author; a note's own `summary:` or `description:`), cut at a word.
465
+ Nothing is inferred. The `Source:` header line above it is unchanged."""
466
+ out = [f"When: {it.date}"]
467
+ for name, value in (("Who", it.who), ("Summary", it.summary)):
468
+ if value := " ".join(value.split()):
469
+ if len(value) > SUMMARY_CHARS:
470
+ value = value[:SUMMARY_CHARS].rsplit(" ", 1)[0].rstrip(",;:") + "…"
471
+ out.append(f"{name}: {scrub(value, src)}")
472
+ return "\n".join(out)
473
+
474
+
475
+ def untouched(text: str) -> bool | None:
476
+ """RR-18: whether an imported page's body is as its import wrote it (the header's `body:`
477
+ sha); None for a page with no body sha (imported before RR-18, or by another source)."""
478
+ m = HEADER.search(text)
479
+ if not m or not m.group(4):
480
+ return None
481
+ return _sha(_rest(text, m)) == m.group(4)
482
+
483
+
484
+ def _rest(text: str, m: re.Match) -> str:
485
+ """An imported page's body under its header line, as `untouched` hashes it."""
486
+ return text[m.end():].replace("\r\n", "\n").strip()
487
+
488
+
489
+ def _edited(cur: str, was: str) -> bool:
490
+ """R17: whether the owner edited an imported page: its body no longer matches its `body:`
491
+ sha, or (a page written with no sha: the docs import before R17) its text under the fact
492
+ lines is no longer `was`, the text the import wrote; a page whose header is gone too."""
493
+ m = HEADER.search(cur)
494
+ if not m:
495
+ return True
496
+ return untouched(cur) is False if m.group(4) else _rest(cur, m).split("\n\n", 1)[-1] != was
497
+
498
+
499
+ def _by_origin(vault: Vault, src: Source) -> dict[str, tuple[Path, str]]:
500
+ """RR-18: origin -> (the newest page an earlier import of `src`'s labels wrote for it, its
501
+ text); newest by header Date, then id length and id (`x-2` is newer than `x`)."""
502
+ labels, best = _labels(src), {}
503
+ for p in source_pages(vault, src):
504
+ text = p.read_text("utf-8", errors="replace")
505
+ m = HEADER.search(text)
506
+ if m and m.group(3) and m.group(1) in labels:
507
+ rank = (m.group(2), len(p.stem), p.stem)
508
+ if m.group(3) not in best or rank > best[m.group(3)][0]:
509
+ best[m.group(3)] = (rank, p, text)
510
+ return {o: (p, text) for o, (_, p, text) in best.items()}
511
+
512
+
513
+ def _fields(vault: Vault, page: Path) -> dict:
514
+ try:
515
+ return {k: v for k, v in vault.read_path(page).fields.items() if k != "id"}
516
+ except VaultError:
517
+ return {}
518
+
519
+
520
+ def edited_pages(vault: Vault, events) -> list[dict]:
521
+ """RR-18's Review cards: an imported page edited by hand (its body no longer matches its
522
+ `body:` sha) that a later import of the same file left alone, writing a newer page
523
+ instead. {key, page, new, title, private}, at most SHOWN_EDITED; Dismiss (a `dismiss`
524
+ change on id `imports` holding the key) closes one. Nothing is stored: a fold over the
525
+ header lines."""
526
+ from keepfold import importers, review, voice_memos # they import modules that import this
527
+ events = list(events)
528
+ groups = defaultdict(list)
529
+ # by_origin sources' labels (notes, voice memos): an `updates` page has no -2
530
+ notes = {*importers.LABELS.values(), voice_memos.LABEL}
531
+ for p in sorted((vault.root / "resources").glob("*.md")):
532
+ text = p.read_text("utf-8", errors="replace")
533
+ if (m := HEADER.search(text)) and m.group(3) and m.group(1) in notes:
534
+ groups[m.group(1), m.group(3)].append(((m.group(2), len(p.stem), p.stem), p, text))
535
+ out = []
536
+ for pages in groups.values():
537
+ pages.sort()
538
+ newest = pages[-1][1]
539
+ for _, p, text in pages[:-1]:
540
+ key = review.text_hash(f"{p.stem} {newest.stem}")
541
+ if untouched(text) is False and not review.dismissed(events, "imports", key):
542
+ f = _fields(vault, p)
543
+ out.append({"key": key, "page": p.stem, "new": newest.stem,
544
+ "title": str(f.get("title") or p.stem),
545
+ "private": _was_private(vault, p)})
546
+ return out[:SHOWN_EDITED]
547
+
548
+
549
+ def _was_private(vault: Vault, page: Path) -> bool:
550
+ """Whether a page an `updates` import rewrites is private now (set by an earlier private
551
+ import or by hand); a page that does not parse counts as private (fail closed)."""
552
+ try:
553
+ return is_private(vault.read_path(page))
554
+ except VaultError:
555
+ return True
556
+
557
+
558
+ def _note_text(nid: str, fields: dict, body: str) -> str:
559
+ """The text `Vault.create_note` writes, to compare with and rewrite an updated page."""
560
+ data = CommentedMap((k, _to_yaml(v)) for k, v in {"id": nid, **fields}.items())
561
+ return "---\n" + _dump_fm(data, "\n") + "---\n" + body
562
+
563
+
564
+ def _months(vault: Vault, src: Source, private: bool, dry_run: bool, r: dict) -> None:
565
+ months = defaultdict(set)
566
+ for it in _read(src, r):
567
+ months[it.date[:7], private or it.private].add(f"- {scrub(it.text, src)}")
568
+ r["pages"] = len(months)
569
+ for (month, hidden), lines in sorted(months.items()):
570
+ prefix = src.prefix or src.id
571
+ nid = f"{prefix}-private-{month}" if hidden else f"{prefix}-{month}"
572
+ p = vault.path_for("resource", nid)
573
+ # the other tier's page of the month too: a tier made stricter (or looser) since then
574
+ # never writes the same line twice
575
+ twin = vault.path_for("resource", f"{prefix}-{month}" if hidden
576
+ else f"{prefix}-private-{month}")
577
+ mine = set(p.read_text("utf-8").splitlines()) if p.is_file() else set()
578
+ theirs = set(twin.read_text("utf-8").splitlines()) if twin.is_file() else set()
579
+ add = sorted(lines - mine - theirs)
580
+ # a per-day summary line ("- YYYY-MM-DD: …", photos and location) replaces that day's,
581
+ # never in a public page from a private import
582
+ if hidden and theirs and not _was_private(vault, twin):
583
+ theirs = set()
584
+ old = {m.group(1): ln for ln in mine | theirs if (m := _DAY_LINE.match(ln))}
585
+ swap = {old[m.group(1)]: ln for ln in add
586
+ if (m := _DAY_LINE.match(ln)) and m.group(1) in old}
587
+ add = [ln for ln in add if ln not in swap.values()]
588
+ r["imported"] += len(add)
589
+ r["updated"] += len(swap)
590
+ r["private"] += len(add) if hidden else 0
591
+ if dry_run or not (add or swap):
592
+ continue
593
+ heading = src.noun.capitalize()
594
+ for q in (p, twin) if swap else (): # in whichever page holds the day's line
595
+ if q.is_file() and (q == p or theirs):
596
+ vault.update_text(q, lambda t, s=swap: "".join(
597
+ s.get(x.rstrip("\r\n"), x.rstrip("\r\n")) + x[len(x.rstrip("\r\n")):]
598
+ for x in t.splitlines(keepends=True)))
599
+ if mine or not add:
600
+ # shortcut: later imports append, so a month is sorted within each import only
601
+ if add:
602
+ vault.append_to_section("resource", nid, heading, "\n".join(add))
603
+ continue
604
+ fields = {"title": f"{src.label} {month}", "kind": "resource", "resource_type": "other",
605
+ "status": "reference", "covers": [], "related": [], "date": f"{month}-01",
606
+ "summary": f"{src.label} {src.noun} in {month}"}
607
+ if hidden:
608
+ fields["private"] = True
609
+ vault.create_note("resource", nid, fields, f"# {src.label} {month}\n\nSource: "
610
+ f"{src.label} · Date: {month}-01\n\n## {heading}\n" + "\n".join(add)
611
+ + "\n")
612
+ r["duplicate"] = r["items"] - r["imported"] - r["updated"]