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/vecstore.py ADDED
@@ -0,0 +1,218 @@
1
+ """Vector stores: one SQLite file (WAL) per cache under `.keepfold`, a row per page.
2
+
3
+ A row holds what a page's vectors were made from (`manifest`: semantic's path, mtime and
4
+ size; the browse search's content hash), whether every chunk of it is built, its chunk starts
5
+ (int32) and unit vectors (float16). A save upserts and deletes rows, so adding a page writes
6
+ that page only (the .npz caches before it rewrote every row). An upsert keeps the row with
7
+ more chunks built for the same manifest, so a server and a `keepfold model build` never undo
8
+ each other's work. `meta` holds the settings the rows were made with (other settings empty
9
+ the table), an `epoch` made with the file and two counters a reader polls as its change stamp:
10
+ `gen` (each row carries the gen it was saved at, so a reader fetches only the newer rows) and
11
+ `dels` (a delete bumps it; a reader then drops the ids that went). A deleted row is overwritten
12
+ (secure_delete) and the WAL checkpointed, so a forgotten page leaves nothing behind. A
13
+ disposable cache: a damaged file (unreadable, or failing the first open's quick_check in a
14
+ process) is moved aside by keepfold.quarantine and started again; its pages are embedded again.
15
+ Written by SQLite's transactions, not keepfold.vault's temp files, as keepfold.browse.store.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import logging
22
+ import os
23
+ import sqlite3
24
+ from contextlib import contextmanager
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+
29
+ from keepfold import quarantine
30
+
31
+ log = logging.getLogger(__name__)
32
+
33
+ _DDL = """
34
+ CREATE TABLE IF NOT EXISTS meta(k TEXT PRIMARY KEY, v TEXT);
35
+ CREATE TABLE IF NOT EXISTS vecs(id TEXT PRIMARY KEY, manifest TEXT NOT NULL,
36
+ full INTEGER NOT NULL, n INTEGER NOT NULL, starts BLOB NOT NULL, vecs BLOB NOT NULL,
37
+ gen INTEGER NOT NULL);
38
+ CREATE INDEX IF NOT EXISTS vecs_gen ON vecs(gen);
39
+ """
40
+ # the row with more chunks built wins for the same manifest (the chunking is deterministic)
41
+ _UPSERT = ("INSERT INTO vecs VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET "
42
+ "manifest = excluded.manifest, full = excluded.full, n = excluded.n, "
43
+ "starts = excluded.starts, vecs = excluded.vecs, gen = excluded.gen "
44
+ "WHERE excluded.manifest != vecs.manifest "
45
+ "OR (excluded.full, excluded.n) > (vecs.full, vecs.n)")
46
+ SUFFIXES = quarantine.SUFFIXES
47
+ COLS = ["id", "manifest", "full", "n", "starts", "vecs", "gen"] # the vecs table, as _DDL makes it
48
+
49
+
50
+ def _open(path: Path) -> sqlite3.Connection:
51
+ con = sqlite3.connect(path, timeout=10, isolation_level=None, check_same_thread=False)
52
+ try:
53
+ con.execute("PRAGMA journal_mode=WAL")
54
+ con.execute("PRAGMA synchronous=NORMAL")
55
+ con.execute("PRAGMA secure_delete=ON") # a forgotten page's row is overwritten
56
+ con.executescript(_DDL)
57
+ quarantine.check(con, path, "vecs", COLS) # once per process
58
+ if get_meta(con, "epoch") is None:
59
+ with tx(con):
60
+ con.execute("INSERT OR IGNORE INTO meta VALUES ('epoch', ?)",
61
+ (json.dumps(os.urandom(8).hex()),))
62
+ except BaseException:
63
+ con.close()
64
+ raise
65
+ return con
66
+
67
+
68
+ def connect(path: Path, create: bool = True, vault=None) -> sqlite3.Connection:
69
+ """The store at `path`, made when missing; a damaged one (`quarantine.torn`) is moved
70
+ aside through `vault` (the vault holding `path` when None) and made again. With `create`
71
+ False (a reader) a damaged one raises sqlite3.DatabaseError instead, as does one that
72
+ cannot be moved (held open by another program)."""
73
+ path.parent.mkdir(parents=True, exist_ok=True)
74
+ try:
75
+ return _open(path)
76
+ except sqlite3.DatabaseError as e:
77
+ if not create or not quarantine.torn(e): # locked, busy, no access: not damaged
78
+ raise
79
+ if not heal(path, e, vault):
80
+ raise
81
+ return _open(path)
82
+
83
+
84
+ def heal(path: Path, e: BaseException, vault=None) -> bool:
85
+ """Move the damaged store at `path` aside (`quarantine.heal`); False when it stayed."""
86
+ return quarantine.heal(path, e, "its pages are embedded again", vault)
87
+
88
+
89
+ @contextmanager
90
+ def tx(con: sqlite3.Connection):
91
+ """A write transaction that takes the write lock up front (a read-then-write one could
92
+ not upgrade while another process writes)."""
93
+ con.execute("BEGIN IMMEDIATE")
94
+ try:
95
+ yield
96
+ except BaseException:
97
+ con.execute("ROLLBACK")
98
+ raise
99
+ con.execute("COMMIT")
100
+
101
+
102
+ def get_meta(con: sqlite3.Connection, k: str, default=None):
103
+ row = con.execute("SELECT v FROM meta WHERE k = ?", (k,)).fetchone()
104
+ return json.loads(row[0]) if row else default
105
+
106
+
107
+ def set_meta(con: sqlite3.Connection, k: str, v) -> None:
108
+ con.execute("INSERT OR REPLACE INTO meta VALUES (?, ?)", (k, json.dumps(v)))
109
+
110
+
111
+ def _bump(con: sqlite3.Connection, k: str) -> int:
112
+ n = int(get_meta(con, k, 0)) + 1
113
+ set_meta(con, k, n)
114
+ return n
115
+
116
+
117
+ def prepare(con: sqlite3.Connection, want: dict) -> bool:
118
+ """Empty the rows when they were made with settings other than `want`; True if it did."""
119
+ if get_meta(con, "settings") == want:
120
+ return False
121
+ with tx(con):
122
+ if get_meta(con, "settings") == want: # another process did it meanwhile
123
+ return False
124
+ if con.execute("DELETE FROM vecs").rowcount:
125
+ _bump(con, "dels")
126
+ set_meta(con, "settings", want)
127
+ return True
128
+
129
+
130
+ def stamp(con: sqlite3.Connection) -> tuple:
131
+ """(epoch, gen, dels): changes whenever any process saves or deletes a row."""
132
+ got = dict(con.execute("SELECT k, v FROM meta WHERE k IN ('epoch', 'gen', 'dels')"))
133
+ return tuple(json.loads(got[k]) if k in got else 0 for k in ("epoch", "gen", "dels"))
134
+
135
+
136
+ def rows(con: sqlite3.Connection, dim: int, since: int | None = None):
137
+ """(id, manifest, full, starts int32, vecs float16 (n, dim)) of every row, or of those
138
+ saved after gen `since`; the arrays are views of the stored bytes."""
139
+ q = "SELECT id, manifest, full, starts, vecs FROM vecs"
140
+ for i, m, full, s, v in (con.execute(q) if since is None
141
+ else con.execute(q + " WHERE gen > ?", (since,))):
142
+ yield (i, m, bool(full), np.frombuffer(s, np.int32),
143
+ np.frombuffer(v, np.float16).reshape(-1, dim))
144
+
145
+
146
+ def heads(con: sqlite3.Connection, dim: int) -> tuple[list[str], np.ndarray]:
147
+ """(ids, float32 (n, dim)) of each row's first vector, the rest of each blob unread."""
148
+ got = con.execute("SELECT id, substr(vecs, 1, ?) FROM vecs", (2 * dim,)).fetchall()
149
+ m = np.frombuffer(b"".join(v for _, v in got), np.float16).reshape(-1, dim)
150
+ return [i for i, _ in got], m.astype(np.float32)
151
+
152
+
153
+ def manifests(con: sqlite3.Connection) -> dict[str, str]:
154
+ return dict(con.execute("SELECT id, manifest FROM vecs"))
155
+
156
+
157
+ def sync(con: sqlite3.Connection, dim: int, st0, cache: dict, parse) -> tuple[tuple, bool]:
158
+ """Bring `cache` ({id: (parse(manifest), full, starts, vecs)}, a process's copy as of
159
+ stamp `st0`) up to the store: every row on the first call or after the file was made
160
+ again, else only the rows saved and the ids deleted since. (stamp, whether it changed)."""
161
+ st = stamp(con)
162
+ if st == st0:
163
+ return st, False
164
+ if st0 is None or st0[0] != st[0]:
165
+ cache.clear()
166
+ new = rows(con, dim)
167
+ else:
168
+ new = rows(con, dim, st0[1])
169
+ if st[2] != st0[2]:
170
+ have = manifests(con)
171
+ for i in [i for i in cache if i not in have]:
172
+ del cache[i]
173
+ for i, m, full, s, v in new:
174
+ cache[i] = (parse(m), full, s, v)
175
+ return st, True
176
+
177
+
178
+ def put(con: sqlite3.Connection, items: dict) -> None:
179
+ """Upsert {id: (manifest, full, starts, vecs)} in one transaction."""
180
+ if not items:
181
+ return
182
+ with tx(con):
183
+ g = _bump(con, "gen")
184
+ con.executemany(_UPSERT, [
185
+ (i, m, int(full), len(s), np.asarray(s, np.int32).tobytes(),
186
+ np.asarray(v, np.float16).tobytes(), g)
187
+ for i, (m, full, s, v) in items.items()])
188
+
189
+
190
+ def delete(con: sqlite3.Connection, ids) -> int:
191
+ """Delete the rows of `ids`; how many went. Their old page images leave the WAL too."""
192
+ ids = list(ids)
193
+ if not ids:
194
+ return 0
195
+ with tx(con):
196
+ n = sum(con.execute("DELETE FROM vecs WHERE id = ?", (i,)).rowcount for i in ids)
197
+ if n:
198
+ _bump(con, "dels")
199
+ if n:
200
+ con.execute("PRAGMA wal_checkpoint(TRUNCATE)")
201
+ return n
202
+
203
+
204
+ def stack(cache: dict, dim: int) -> tuple:
205
+ """(ids, row -> page index, row chunk start, float32 rows) of `cache` ({id: (manifest,
206
+ full, starts, vecs)}) as one contiguous matrix; each entry is rebound to views of it, so
207
+ memory holds the matrix once."""
208
+ ids = list(cache)
209
+ sizes = [len(cache[i][2]) for i in ids]
210
+ cut = np.concatenate([[0], np.cumsum(sizes, dtype=np.int64)])
211
+ m = np.empty((int(cut[-1]), dim), np.float32)
212
+ start = np.empty(int(cut[-1]), np.int32)
213
+ for k, i in enumerate(ids):
214
+ meta, full, s, v = cache[i]
215
+ a, b = cut[k], cut[k + 1]
216
+ m[a:b], start[a:b] = v, s
217
+ cache[i] = (meta, full, start[a:b], m[a:b])
218
+ return ids, np.repeat(np.arange(len(ids), dtype=np.int32), sizes), start, m
keepfold/voice.py ADDED
@@ -0,0 +1,260 @@
1
+ """Voice (v5 PHASE4.md V1): the user's own messages (samples), one JSON row per line in
2
+ `voice/samples.jsonl` (an old vault may also hold `voice/drafts.jsonl`; only `people.forget`
3
+ still reads it). `voice/` is no kind folder, so the index, recall, vectors, the dashboard,
4
+ `index.md` and lint never see it. Writes go through `keepfold.vault`; `id` and `day` are stamped
5
+ here, never taken from input."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ import unicodedata
12
+ from collections import Counter
13
+ from datetime import datetime
14
+ from statistics import median
15
+
16
+ from ulid import ULID
17
+
18
+ from keepfold.chats import drop_private
19
+ from keepfold.events import local_day
20
+ from keepfold.vault import invalid, scan_secrets
21
+
22
+ ACTS = ("request", "reply", "thanks", "apology", "update", "decline", "intro", "other")
23
+ CHANNELS = ("email", "chat", "sms", "social", "ai", "other") # ai: typed to an AI, never voice
24
+ AUDIENCE_RE = re.compile(r"[a-z0-9-]{1,40}|people/[a-z0-9][a-z0-9.-]{0,80}")
25
+ LANG_RE = re.compile(r"[a-z]{2,3}(-[a-z0-9]{2,8})?")
26
+ TEXT_MAX = 4000
27
+ SAMPLES = "voice/samples.jsonl"
28
+ SPLIT_RE = re.compile(r"^---[ \t]*$", re.M)
29
+
30
+
31
+ def check_audience(audience) -> str:
32
+ if not isinstance(audience, str) or not AUDIENCE_RE.fullmatch(audience):
33
+ raise invalid("audience must be a short tag ([a-z0-9-], up to 40, e.g. professor) or a "
34
+ "person id people/<slug>.")
35
+ return audience
36
+
37
+
38
+ def _text(text) -> str:
39
+ if not isinstance(text, str) or not text.strip() or len(text) > TEXT_MAX:
40
+ raise invalid(f"text must be the message itself, 1 to {TEXT_MAX:,} characters.")
41
+ text = drop_private(text) # a private span is never saved, nor refused as a secret
42
+ scan_secrets(text)
43
+ return text
44
+
45
+
46
+ def fields(p: dict) -> dict:
47
+ """The validated `{audience, act, channel, lang?, text}` of a sample."""
48
+ if p.get("act") not in ACTS:
49
+ raise invalid(f"act must be one of {', '.join(ACTS)}.")
50
+ if p.get("channel") not in CHANNELS:
51
+ raise invalid(f"channel must be one of {', '.join(CHANNELS)}.")
52
+ out = {"audience": check_audience(p.get("audience")), "act": p["act"],
53
+ "channel": p["channel"]}
54
+ if p.get("lang") is not None:
55
+ if not isinstance(p["lang"], str) or not LANG_RE.fullmatch(p["lang"]):
56
+ raise invalid("lang must be a language tag such as en or pt-br.")
57
+ out["lang"] = p["lang"]
58
+ return {**out, "text": _text(p.get("text"))}
59
+
60
+
61
+ def rows(vault, name: str) -> list[dict]:
62
+ """The rows of voice/<name>, oldest first; a line that is not a JSON object is skipped."""
63
+ p = vault.root / name
64
+ out = []
65
+ for line in (p.read_bytes().decode("utf-8").splitlines() if p.is_file() else ()):
66
+ try:
67
+ r = json.loads(line)
68
+ except ValueError:
69
+ continue
70
+ if isinstance(r, dict):
71
+ out.append(r)
72
+ return out
73
+
74
+
75
+ def add(vault, name: str, items: list[dict], now: datetime) -> list[str]:
76
+ """Append `items` to voice/<name> with server ids and day; returns the ids."""
77
+ base, day = int(ULID.from_datetime(now)), local_day(now)
78
+ new = [{"id": str(ULID.from_int(base + i)), "day": day, **it} for i, it in enumerate(items)]
79
+ path = vault.root / name
80
+ with vault.lock():
81
+ old = path.read_bytes().decode("utf-8") if path.is_file() else ""
82
+ vault.write_text(path, old + "".join(json.dumps(r, ensure_ascii=False) + "\n"
83
+ for r in new))
84
+ return [r["id"] for r in new]
85
+
86
+
87
+ def import_text(vault, text: str, audience: str, act: str, channel: str,
88
+ now: datetime) -> int:
89
+ """`keepfold voice import`: messages separated by lines of `---`, all or none."""
90
+ items = [fields({"audience": audience, "act": act, "channel": channel, "text": m.strip()})
91
+ for m in SPLIT_RE.split(text.replace("\r\n", "\n")) if m.strip()]
92
+ return len(add(vault, SAMPLES, items, now)) if items else 0
93
+
94
+
95
+ def exemplars(vault, audiences: set[str], act: str | None, channel: str | None,
96
+ n: int = 3) -> list[dict]:
97
+ """Up to `n` samples scored audience 2, act 1, channel 0.5 (newest first on ties), never
98
+ `channel: ai` and never a sample that matches nothing."""
99
+ scored = []
100
+ for i, s in enumerate(rows(vault, SAMPLES)):
101
+ if s.get("channel") == "ai" or not isinstance(s.get("text"), str):
102
+ continue
103
+ score = (2 * (s.get("audience") in audiences) + (s.get("act") == act)
104
+ + 0.5 * (s.get("channel") == channel))
105
+ if score:
106
+ scored.append((-score, -i, s))
107
+ return [s for *_, s in sorted(scored, key=lambda x: x[:2])[:n]]
108
+
109
+
110
+ # ---- the measured style (V1): counted numbers, no model, no network -------------------------
111
+
112
+ MIN_GROUP = 8 # samples an audience needs before its numbers say anything
113
+ SHARED = 0.3 # an opener or sign-off counts when over this share of messages use it
114
+ MEASURED = "Measured: " # marks the lines `propose` writes, so a re-run finds its own
115
+ # a measured line waiting in inbox.md, as Keepfold._propose writes it
116
+ _WAITING = re.compile(r"- (?P<section>[^:\n]+): (?P<text>Measured: .+?) "
117
+ r"\(proposed \d{4}-\d{2}-\d{2}, me/voice\)\s*$")
118
+ _SENT = re.compile(r"[^.!?\n]+[.!?]*")
119
+ _WORD = re.compile(r"[^\W_]+(?:['’][^\W_]+)?")
120
+ _SUFFIX = {"m", "re", "s", "ve", "ll", "d", "t"} # shortcut: "Sam's" counts too
121
+ _SIGN = re.compile(r"[\w' ,.!-]{1,30}") # an opener or sign-off fit to quote on me/voice
122
+ _CONFIRMED = re.compile(r"\s*\(confirmed \d{4}-\d{2}-\d{2}\)$")
123
+
124
+
125
+ def _common(items: list[str], n: int) -> str | None:
126
+ """The most common non-empty item (case and trailing punctuation folded) when over SHARED
127
+ of `n` messages use it, as first written; else None."""
128
+ key = [i.rstrip(",.!").lower() for i in items]
129
+ top = Counter(k for k in key if k).most_common(1)
130
+ if not top or top[0][1] / n <= SHARED:
131
+ return None
132
+ word = items[key.index(top[0][0])]
133
+ return word if _SIGN.fullmatch(word) else None
134
+
135
+
136
+ def _numbers(texts: list[str]) -> dict:
137
+ sents, msg_words, firsts, lasts = [], [], [], []
138
+ words = contractions = emoji = lower = 0
139
+ for t in texts:
140
+ w = _WORD.findall(t)
141
+ msg_words.append(len(w))
142
+ words += len(w)
143
+ contractions += sum(x.replace("’", "'").partition("'")[2].lower() in _SUFFIX
144
+ for x in w)
145
+ sents += [s.strip() for s in _SENT.findall(t) if _WORD.search(s)]
146
+ emoji += sum(unicodedata.category(c) == "So" and ord(c) >= 0x2600 for c in t)
147
+ lower += any(c.isalpha() for c in t) and t == t.lower()
148
+ lines = [ln.strip() for ln in t.splitlines() if ln.strip()]
149
+ firsts.append(w[0] if w else "")
150
+ lasts.append(lines[-1] if len(lines) > 1 and len(lines[-1].split()) <= 3 else "")
151
+ n, ns = len(texts), max(len(sents), 1)
152
+ return {"n": n,
153
+ "sentence_words": median(len(_WORD.findall(s)) for s in sents) if sents else 0,
154
+ "questions": round(sum(s.endswith("?") for s in sents) / ns, 2),
155
+ "contractions": round(100 * contractions / max(words, 1), 1),
156
+ "exclamations": round(100 * sum(s.count("!") for s in sents) / ns, 1),
157
+ "opens": _common(firsts, n), "closes": _common(lasts, n),
158
+ "lowercase": round(lower / n, 2), "emoji": round(emoji / n, 2),
159
+ "message_words": median(msg_words)}
160
+
161
+
162
+ def measure(vault) -> dict:
163
+ """{group: numbers} over the samples not typed to an AI: each audience and "all", a group
164
+ with fewer than MIN_GROUP samples left out. Deterministic."""
165
+ groups: dict[str, list[str]] = {}
166
+ for s in rows(vault, SAMPLES):
167
+ if s.get("channel") != "ai" and isinstance(s.get("text"), str):
168
+ t = s["text"].replace("\r\n", "\n")
169
+ groups.setdefault("all", []).append(t)
170
+ a = s.get("audience") # a hand-edited row may lack one; "all" is the whole set
171
+ if isinstance(a, str) and AUDIENCE_RE.fullmatch(a) and a != "all":
172
+ groups.setdefault(a, []).append(t)
173
+ return {g: _numbers(ts) for g, ts in sorted(groups.items()) if len(ts) >= MIN_GROUP}
174
+
175
+
176
+ def style_lines(m: dict, group: str = "all") -> list[str]:
177
+ """At most 4 plain lines on `group`'s numbers; a number near the middle says nothing."""
178
+ g = m.get(group)
179
+ if not g:
180
+ return []
181
+ out = []
182
+ s, q = g["sentence_words"], g["questions"]
183
+ size = "short" if s <= 8 else "long" if s >= 20 else None
184
+ asks = "many questions" if q >= 0.3 else "few questions" if q <= 0.05 else None
185
+ if size:
186
+ out.append(f"Writes {size} sentences (median {s:g} words)"
187
+ + (f" and asks {asks}" if asks else "") + ".")
188
+ elif asks:
189
+ out.append(f"Asks {asks} ({round(q * 100)}% of sentences).")
190
+ if g["opens"] and g["closes"]:
191
+ out.append(f'Opens with "{g["opens"]}" and signs off "{g["closes"]}".')
192
+ elif g["opens"] or g["closes"]:
193
+ out.append(f'Opens with "{g["opens"]}".' if g["opens"] else
194
+ f'Signs off "{g["closes"]}".')
195
+ tone = [t for t, ok in (
196
+ ("uses exclamation marks often", g["exclamations"] >= 30),
197
+ ("rarely uses exclamation marks", g["exclamations"] <= 3),
198
+ ("often writes all lowercase", g["lowercase"] >= 0.5),
199
+ ("uses contractions (I'm, don't)", g["contractions"] >= 3),
200
+ ("avoids contractions", g["contractions"] <= 0.5)) if ok]
201
+ shape = [t for t, ok in (
202
+ (f"keeps messages short (median {g['message_words']:g} words)", g["message_words"] <= 12),
203
+ (f"writes long messages (median {g['message_words']:g} words)", g["message_words"] >= 80),
204
+ (f"uses emoji often ({g['emoji']:g} per message)", g["emoji"] >= 1),
205
+ ("uses no emoji", g["emoji"] == 0)) if ok]
206
+ out += [x[0].upper() + x[1:] + "." for x in ("; ".join(tone), "; ".join(shape)) if x]
207
+ return out[:4]
208
+
209
+
210
+ def propose(vault, m: dict | None = None) -> dict:
211
+ """Propose each group's style lines for me/voice (`all` under Everyone, an audience under
212
+ its own section, where keepfold_as_me serves them) the way an inferred line on a page that
213
+ waits is proposed (keepfold_patch's queued path, as tags.act): under `## About me
214
+ (unconfirmed)` in inbox.md, until the user's Approve in the Keepfold app writes it. Measured
215
+ lines still waiting that the new numbers no longer say are withdrawn; lines on the page
216
+ (approved) are never touched, and one under `## Not me` is not proposed again. Returns
217
+ counts: proposed, kept, withdrawn, not_me."""
218
+ from keepfold import claims, review
219
+ from keepfold.mcp_server import Keepfold # the SDK: only when writing
220
+ from keepfold.render import plain
221
+
222
+ m = measure(vault) if m is None else m
223
+ want = {("Everyone" if g == "all" else g): [MEASURED + x for x in style_lines(m, g)]
224
+ for g in m}
225
+ every = set(want.get("Everyone", ())) # an audience does not repeat what all says
226
+ want = {k: v if k == "Everyone" else [x for x in v if x not in every]
227
+ for k, v in want.items()}
228
+ core = Keepfold(vault, build=False) # me/ pages only: no index (as fact_harvest._save)
229
+ core._ready.set()
230
+ day, page = local_day(core._now()), core._raw("me/voice.md")
231
+ approved = {(r["section"], _CONFIRMED.sub("", r["text"]))
232
+ for r in claims.parse("voice", page) if r["status"] == "live"}
233
+ waiting = {(x["section"], x["text"]) for x in map(_WAITING.match,
234
+ core._raw("inbox.md").splitlines()) if x}
235
+ n: Counter = Counter()
236
+ core.session = core.sessions.start("save")
237
+ core._reset()
238
+ try:
239
+ for section, text in waiting:
240
+ if text not in want.get(section, ()):
241
+ core._unpropose(f"{section}: {text}")
242
+ n["withdrawn"] += 1
243
+ for section, lines in want.items():
244
+ for line in lines:
245
+ if (section, line) in approved | waiting:
246
+ n["kept"] += 1
247
+ elif claims.is_not_me("voice", page, line):
248
+ n["not_me"] += 1
249
+ else:
250
+ core._propose(f"- {section}: {line} (proposed {day}, me/voice)")
251
+ core.proposed.append(plain(f"{section}: {line}", 200))
252
+ core.sessions.note("patched", change={
253
+ "tool": "propose", "id": "voice", "kind": "me",
254
+ "op": "append_to_section", "target": section,
255
+ "hash": review.text_hash(line)})
256
+ n["proposed"] += 1
257
+ finally:
258
+ if core.sessions.current is not None:
259
+ core.sessions.close(summary="Keepfold measured how you write")
260
+ return dict(n)