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/lint.py ADDED
@@ -0,0 +1,241 @@
1
+ """Vault lint (docs/design/phase4-wiki.md §3): candidate problems for the model to fix.
2
+
3
+ Read-only; returns at most MAX_FINDINGS findings `{kind, id, detail}`, most severe kinds first
4
+ (SEVERITY), noisy kinds capped (KIND_CAP), plus per-kind totals before the cut. Private notes are
5
+ never reported (they still count as link sources and targets).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import datetime as dt
11
+ import re
12
+ from collections import Counter
13
+ from collections.abc import Mapping
14
+
15
+ from keepfold.catalog import page_slug
16
+ from keepfold.events import DAY_ROLLOVER
17
+ from keepfold.index import EDGE_KEYS, STOPWORDS, _edge_targets
18
+ from keepfold.people import PREFIX
19
+ from keepfold.relink import TOKEN_RE, _tgt
20
+ from keepfold.render import plain
21
+ from keepfold.vault import Vault, is_private
22
+
23
+ MAX_FINDINGS = 30
24
+ # Order before the cut: broken links first, unlinked mentions (the noisiest) last.
25
+ SEVERITY = ("id_clash", "sync_conflict", "missing_link", "expired_claim", "merged_related",
26
+ "orphan", "no_summary", "weak_summary", "links_no_reason", "resource_no_covers",
27
+ "stale_project", "long_note", "old_fleeting", "unlinked_mention")
28
+ KIND_CAP = {"unlinked_mention": 10, "weak_summary": 10}
29
+ # RR-26: a summary is what search and prime show; one that only restates the title, or is a
30
+ # few words, adds no words to be found by
31
+ SUMMARY_MIN_CHARS, SUMMARY_TITLE_OVERLAP = 30, 0.7
32
+ # `keepfold lint --findability`: words of a page's second chunk that must find it in the top N
33
+ PROBE_WORDS, FINDABLE_TOP = 20, 3
34
+ LONG_NOTE_WORDS = 350
35
+ STALE_PROJECT_DAYS = 30
36
+ FLEETING_DAYS = 7
37
+ # profile pages and generated session notes have no links; browse pages hold browser titles and
38
+ # rollup pages generated counts, not the user's text to link (no mention findings)
39
+ NOT_ORPHANS = ("me", "session", "browse", "rollup")
40
+ _ANY_LINK_RE = re.compile(r"\[\[[^\]]*\]\]")
41
+ _FLEETING_RE = re.compile(r"^- \[ \] (.+?) \(fleeting, (\d{4}-\d\d-\d\d)\)\s*$")
42
+ _BARE_LINK_RE = re.compile(r"^[-*+]\s*\[\[[^\]]*\]\]\s*$") # a ## Links bullet with no reason
43
+ # an imported page (a chat, YouTube, NotebookLM) says `Source: <app>` near its top; it is filed by
44
+ # topic, not by concept, and its text is not the user's to link: no covers or mention findings
45
+ _IMPORTED_RE = re.compile(r"^(?:Timeline: .*?· )?Source: [^\n·]+", re.M)
46
+
47
+
48
+ def _out_edges(fields: Mapping, body: str) -> tuple[set[str], set[str]]:
49
+ """(valid-id targets from frontmatter edges, raw wikilink targets from the body)."""
50
+ fm = {t for k in EDGE_KEYS if k in fields for t in _edge_targets(fields[k])}
51
+ # [[people/x]] (the people hub's form) is the person note x
52
+ # TOKEN_RE skips fenced blocks and inline code, as Obsidian does
53
+ raw = (_tgt(m["t"]) for m in TOKEN_RE.finditer(body) if m["t"] is not None)
54
+ return fm, {t.removeprefix(PREFIX) for t in raw if t}
55
+
56
+
57
+ def lint_report(vault: Vault, now: dt.datetime | None = None,
58
+ withheld: set[str] = frozenset()) -> tuple[list[dict], dict]:
59
+ """(findings sorted by SEVERITY, capped per KIND_CAP and at MAX_FINDINGS;
60
+ {kind: total found} before any cut). `withheld`: bare ids of me/ pages whose claim text
61
+ the caller may not see (mcp_server.Keepfold._withheld)."""
62
+ now = now or dt.datetime.now()
63
+ notes = list(vault.iter_notes())
64
+ kinds_of: dict[str, list[str]] = {}
65
+ for n in notes:
66
+ kinds_of.setdefault(n.id, []).append(n.kind)
67
+ merged = {n.id for n in notes if n.kind == "concept" and n.fields.get("merged_into")}
68
+ out: list[dict] = []
69
+
70
+ def add(kind: str, id: str, detail: str) -> None:
71
+ out.append({"kind": kind, "id": id, "detail": detail})
72
+
73
+ for id, kinds in sorted(kinds_of.items()):
74
+ if len(kinds) > 1 and not _is_private_id(notes, id):
75
+ add("id_clash", id, f"used by {', '.join(kinds)}")
76
+
77
+ from keepfold import sync_copies
78
+
79
+ for copy, orig in sync_copies.find_visible(vault)[0]: # never a private page's
80
+ add("sync_conflict", plain(copy), f"a sync conflict copy of {plain(orig)}: open both, "
81
+ "keep what you want in the original, delete the copy")
82
+
83
+ edges, inbound = {}, Counter()
84
+ for n in notes:
85
+ fm, body = _out_edges(n.fields, n.body)
86
+ edges[(n.kind, n.id)] = (fm, body)
87
+ for t in (fm | body) & kinds_of.keys() - {n.id}:
88
+ inbound[t] += 1
89
+
90
+ mention = _mention_re(notes, merged)
91
+ for n in notes:
92
+ if is_private(n):
93
+ continue
94
+ fm, body = edges[(n.kind, n.id)]
95
+ for t in sorted(fm | body):
96
+ if t not in kinds_of and not t.startswith("raw/"):
97
+ add("missing_link", n.id, f"links to [[{plain(t, 60)}]], which does not exist")
98
+ if not ((fm | body) & kinds_of.keys() - {n.id}) and not inbound[n.id] \
99
+ and n.kind not in NOT_ORPHANS:
100
+ add("orphan", n.id, "no links in or out")
101
+ imported = n.kind == "resource" and bool(_IMPORTED_RE.search(n.body[:600]))
102
+ if n.kind == "resource" and not imported \
103
+ and not _edge_targets(n.fields.get("covers") or []):
104
+ add("resource_no_covers", n.id, "covers lists no concept")
105
+ if n.kind == "project" and n.fields.get("status") == "active":
106
+ age = (now - dt.datetime.fromtimestamp(n.path.stat().st_mtime)).days
107
+ if age > STALE_PROJECT_DAYS:
108
+ add("stale_project", n.id, f"active, not updated for {age} days")
109
+ if n.kind == "note" and n.fields.get("note_type") == "permanent":
110
+ words = len(n.body.split())
111
+ if words > LONG_NOTE_WORDS:
112
+ add("long_note", n.id, f"{words} words; split it into atomic notes")
113
+ if not str(n.fields.get("summary") or "").strip():
114
+ add("no_summary", n.id, "permanent note has no summary")
115
+ links = _links_section(n.body)
116
+ if not links:
117
+ add("links_no_reason", n.id, "## Links is empty")
118
+ elif any(_BARE_LINK_RE.match(ln) for ln in links):
119
+ add("links_no_reason", n.id, "a ## Links bullet has no reason")
120
+ if n.kind not in NOT_ORPHANS and (why := weak_summary(n.fields)): # me/ labels
121
+ add("weak_summary", n.id, why)
122
+ for t in sorted(_edge_targets(n.fields.get("related") or [])):
123
+ if t in merged:
124
+ add("merged_related", n.id, f"related points at [[{t}]], which was merged")
125
+ if mention and n.kind not in NOT_ORPHANS and not imported:
126
+ found = {m.lower(): m for m in mention[0].findall(_ANY_LINK_RE.sub(" ", n.body))}
127
+ for low, text in sorted(found.items()):
128
+ cid = mention[1].get(low) # None if case folding differs from lower()
129
+ if cid and cid != n.id and cid not in fm | body:
130
+ add("unlinked_mention", n.id, f"mentions '{plain(text, 60)}' without "
131
+ f"[[{cid}]]")
132
+
133
+ from keepfold import claims # claims -> reflect -> lint: a top-level import is circular
134
+
135
+ today = (now - DAY_ROLLOVER).date().isoformat() # `now` is naive local time
136
+ for r in claims.rows(vault): # agenda 4: served no more, but never moved automatically
137
+ if r["status"] == "live" and (until := claims.expired(r["text"], today)) \
138
+ and r["page"] not in withheld and not _is_private_id(notes, r["page"]):
139
+ add("expired_claim", f"me/{r['page']}", f"'{plain(r['text'], 60)}' is past its "
140
+ f"(until {until}); retire it: keepfold_patch(op='retire', target='^{r['id']}')")
141
+ for text, since in old_fleeting(vault, now):
142
+ add("old_fleeting", f"inbox:{page_slug(text)}", f"fleeting since {since}; "
143
+ "process it into a note or drop it")
144
+ totals = Counter(f["kind"] for f in out)
145
+ rank = {k: i for i, k in enumerate(SEVERITY)}
146
+ out.sort(key=lambda f: rank.get(f["kind"], len(SEVERITY))) # stable: vault order within
147
+ shown, kept = Counter(), []
148
+ for f in out:
149
+ if shown[f["kind"]] < KIND_CAP.get(f["kind"], MAX_FINDINGS):
150
+ shown[f["kind"]] += 1
151
+ kept.append(f)
152
+ return kept[:MAX_FINDINGS], dict(totals)
153
+
154
+
155
+ def _words(text) -> set[str]:
156
+ return {w for w in re.findall(r"\w+", str(text or "").lower()) if w not in STOPWORDS}
157
+
158
+
159
+ def weak_summary(fields: Mapping) -> str:
160
+ """Why a set `summary` helps findability little ('' when it is fine): under
161
+ SUMMARY_MIN_CHARS, or its words and the title's overlap by more than SUMMARY_TITLE_OVERLAP
162
+ (Jaccard, stopwords out), so it says little the title does not."""
163
+ summary = " ".join(str(fields.get("summary") or "").split())
164
+ if not summary:
165
+ return ""
166
+ if len(summary) < SUMMARY_MIN_CHARS:
167
+ return f"summary is under {SUMMARY_MIN_CHARS} characters"
168
+ t, w = _words(fields.get("title")), _words(summary)
169
+ if t and len(t & w) / len(t | w) > SUMMARY_TITLE_OVERLAP:
170
+ return "summary mostly repeats the title"
171
+ return ""
172
+
173
+
174
+ def findability(vault: Vault, embed=None) -> list[dict]:
175
+ """RR-26, report only: `{kind: not_findable, id, detail}` per page (not private or hidden;
176
+ an imported chat ranks as any page here) with a second chunk whose first PROBE_WORDS
177
+ words, as a recall query, do not put it in the top FINDABLE_TOP. No reranker and no graph
178
+ hops; keyword only when `embed` is None. Never writes a page."""
179
+ from keepfold import semantic
180
+ from keepfold.catalog import Catalog
181
+ from keepfold.index import Index
182
+
183
+ idx = Index(vault, Catalog.load(vault))
184
+ out = []
185
+ for id, n in sorted(idx._notes.items()):
186
+ chunks = semantic._chunks(n)
187
+ if len(chunks) < 2:
188
+ continue
189
+ probe = " ".join(chunks[1][1].split("\n", 1)[-1].split()[:PROBE_WORDS]) # no header
190
+ hits = semantic.recall(idx, probe, embed, FINDABLE_TOP, hops=0, chats=True)
191
+ if id not in [h["id"] for h in hits[:FINDABLE_TOP]]:
192
+ out.append({"kind": "not_findable", "id": id, "detail": f"'{plain(probe, 60)}' "
193
+ f"from its second chunk does not find it in the top {FINDABLE_TOP}"})
194
+ return out
195
+
196
+
197
+ def not_shown(findings: list[dict], totals: Mapping[str, int]) -> str:
198
+ """'140 more unlinked_mention, 2 more orphan' for what the cut hid; '' when nothing."""
199
+ shown = Counter(f["kind"] for f in findings)
200
+ return ", ".join(f"{totals[k] - shown[k]} more {k}" for k in SEVERITY
201
+ if totals.get(k, 0) > shown[k])
202
+
203
+
204
+ def _links_section(body: str) -> list[str]:
205
+ """Non-blank lines under '## Links' up to the next heading; [] when there is none."""
206
+ lines = body.splitlines()
207
+ for i, ln in enumerate(lines):
208
+ if ln.strip().lower() == "## links":
209
+ rest = lines[i + 1:]
210
+ end = next((j for j, x in enumerate(rest) if x.startswith("#")), len(rest))
211
+ return [x.strip() for x in rest[:end] if x.strip()]
212
+ return []
213
+
214
+
215
+ def _mention_re(notes, merged: set[str]):
216
+ """(one case-insensitive whole-word regex over every public concept title of 2+ words,
217
+ lowercased title -> id), or None when there are no such titles."""
218
+ titles = {}
219
+ for n in notes:
220
+ title = " ".join(str(n.fields.get("title") or "").split())
221
+ if (n.kind == "concept" and len(title.split()) >= 2 and not is_private(n)
222
+ and n.id not in merged):
223
+ titles.setdefault(title.lower(), n.id)
224
+ if not titles:
225
+ return None
226
+ alt = "|".join(map(re.escape, sorted(titles, key=len, reverse=True))) # longest first
227
+ return re.compile(rf"(?<!\w)(?:{alt})(?!\w)", re.IGNORECASE), titles
228
+
229
+
230
+ def old_fleeting(vault: Vault, now: dt.datetime) -> list[tuple[str, str]]:
231
+ """(text, date) of inbox.md fleeting lines older than FLEETING_DAYS."""
232
+ inbox = vault.root / "inbox.md"
233
+ if not inbox.is_file():
234
+ return []
235
+ ms = (_FLEETING_RE.match(ln) for ln in inbox.read_bytes().decode("utf-8").splitlines())
236
+ return [(m[1], m[2]) for m in ms
237
+ if m and (now.date() - dt.date.fromisoformat(m[2])).days > FLEETING_DAYS]
238
+
239
+
240
+ def _is_private_id(notes, id: str) -> bool:
241
+ return any(n.id == id and is_private(n) for n in notes)