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.
- keepfold/__init__.py +1 -0
- keepfold/_proc.py +102 -0
- keepfold/access.py +154 -0
- keepfold/agent_eval.py +162 -0
- keepfold/agent_text.py +56 -0
- keepfold/anki.py +285 -0
- keepfold/app/__init__.py +5 -0
- keepfold/app/actions.py +690 -0
- keepfold/app/desktop.py +677 -0
- keepfold/app/exports.py +254 -0
- keepfold/app/hello.py +79 -0
- keepfold/app/launch.py +114 -0
- keepfold/app/news.py +60 -0
- keepfold/app/server.py +3142 -0
- keepfold/app/status.py +811 -0
- keepfold/app/targets.py +1374 -0
- keepfold/app/winpath.py +54 -0
- keepfold/app/wizard.py +506 -0
- keepfold/ask.py +475 -0
- keepfold/askfile.py +322 -0
- keepfold/assets/LICENSE-d3.txt +13 -0
- keepfold/assets/agent_eval.json +235 -0
- keepfold/assets/app/app.css +611 -0
- keepfold/assets/app/app.js +2712 -0
- keepfold/assets/app/capture.html +16 -0
- keepfold/assets/app/capture.js +91 -0
- keepfold/assets/app/index.html +149 -0
- keepfold/assets/brain3d.js +3730 -0
- keepfold/assets/chat_eval.json +454 -0
- keepfold/assets/d3.v7.min.js +2 -0
- keepfold/assets/dashboard.css +774 -0
- keepfold/assets/dashboard.html.tmpl +170 -0
- keepfold/assets/dashboard.js +4262 -0
- keepfold/assets/help/GUIDE.md +544 -0
- keepfold/assets/help/help.md +83 -0
- keepfold/assets/keepfold.ico +0 -0
- keepfold/assets/whats_new.json +162 -0
- keepfold/backup.py +100 -0
- keepfold/brainmap.py +1382 -0
- keepfold/browse/__init__.py +10 -0
- keepfold/browse/build.py +1320 -0
- keepfold/browse/forget.py +510 -0
- keepfold/browse/legacy.py +95 -0
- keepfold/browse/lists.py +285 -0
- keepfold/browse/privacy.py +391 -0
- keepfold/browse/selftest.py +166 -0
- keepfold/browse/sites.py +1068 -0
- keepfold/browse/sources.py +329 -0
- keepfold/browse/store.py +991 -0
- keepfold/browse/takeout.py +312 -0
- keepfold/browse/titles.py +127 -0
- keepfold/browse/vectors.py +326 -0
- keepfold/browse_serve.py +332 -0
- keepfold/catalog.py +564 -0
- keepfold/chat.py +1464 -0
- keepfold/chat_archive.py +165 -0
- keepfold/chat_eval.py +583 -0
- keepfold/chat_facts.py +721 -0
- keepfold/chat_import.py +1045 -0
- keepfold/chat_pages.py +291 -0
- keepfold/chat_study.py +371 -0
- keepfold/chats.py +669 -0
- keepfold/claims.py +650 -0
- keepfold/cli.py +3254 -0
- keepfold/clients.py +96 -0
- keepfold/cloudllm.py +135 -0
- keepfold/contract.py +43 -0
- keepfold/corrections.py +134 -0
- keepfold/dashboard.py +959 -0
- keepfold/dates.py +202 -0
- keepfold/delta.py +146 -0
- keepfold/digest.py +72 -0
- keepfold/doctor.py +565 -0
- keepfold/duplicates.py +145 -0
- keepfold/egress.py +68 -0
- keepfold/eval_history.py +109 -0
- keepfold/events.py +554 -0
- keepfold/export_context.py +109 -0
- keepfold/fact_harvest.py +578 -0
- keepfold/forget.py +720 -0
- keepfold/harvest.py +334 -0
- keepfold/home.py +714 -0
- keepfold/importers.py +627 -0
- keepfold/index.py +733 -0
- keepfold/know.py +40 -0
- keepfold/learning_eval.py +261 -0
- keepfold/levels.py +595 -0
- keepfold/life_sources.py +747 -0
- keepfold/lint.py +241 -0
- keepfold/localllm.py +699 -0
- keepfold/loops.py +316 -0
- keepfold/mcp_server.py +4464 -0
- keepfold/migrate.py +552 -0
- keepfold/more_sources.py +709 -0
- keepfold/packs.py +148 -0
- keepfold/people.py +99 -0
- keepfold/planner.py +819 -0
- keepfold/prime.py +630 -0
- keepfold/prime_hook.py +265 -0
- keepfold/profiles.py +118 -0
- keepfold/quarantine.py +123 -0
- keepfold/recall_log.py +93 -0
- keepfold/redteam.py +393 -0
- keepfold/reflect.py +164 -0
- keepfold/relink.py +477 -0
- keepfold/render.py +406 -0
- keepfold/review.py +1181 -0
- keepfold/rollups.py +412 -0
- keepfold/safety_net.py +571 -0
- keepfold/sample.py +103 -0
- keepfold/sample_vault/areas/programming.algorithms.md +11 -0
- keepfold/sample_vault/areas/programming.basics.md +11 -0
- keepfold/sample_vault/concepts/big-o-notation.md +13 -0
- keepfold/sample_vault/concepts/functions.md +13 -0
- keepfold/sample_vault/concepts/loops.md +14 -0
- keepfold/sample_vault/concepts/recursion.md +13 -0
- keepfold/sample_vault/domains/programming.md +10 -0
- keepfold/sample_vault/journal/2026-01-12.md +9 -0
- keepfold/sample_vault/me/goals.md +17 -0
- keepfold/sample_vault/me/profile.md +19 -0
- keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
- keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
- keepfold/sample_vault/problems/fizzbuzz.md +12 -0
- keepfold/sample_vault/projects/text-adventure.md +15 -0
- keepfold/sample_vault/resources/python-tutorial.md +16 -0
- keepfold/semantic.py +1254 -0
- keepfold/session.py +764 -0
- keepfold/share.py +69 -0
- keepfold/sources.py +612 -0
- keepfold/sync_copies.py +83 -0
- keepfold/tags.py +230 -0
- keepfold/taint.py +301 -0
- keepfold/tonight.py +195 -0
- keepfold/topics.py +1072 -0
- keepfold/update.py +300 -0
- keepfold/vault.py +942 -0
- keepfold/vecstore.py +218 -0
- keepfold/voice.py +260 -0
- keepfold/voice_memos.py +280 -0
- keepfold/watch.py +303 -0
- keepfold/where.py +119 -0
- keepfold/xray.py +516 -0
- keepfold/zotero.py +303 -0
- keepfold-0.6.4.dist-info/METADATA +644 -0
- keepfold-0.6.4.dist-info/RECORD +148 -0
- keepfold-0.6.4.dist-info/WHEEL +4 -0
- keepfold-0.6.4.dist-info/entry_points.txt +6 -0
- keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
keepfold/review.py
ADDED
|
@@ -0,0 +1,1181 @@
|
|
|
1
|
+
"""Plan 5a: the Keepfold app's Review view, read-only. What waits for the user's own click:
|
|
2
|
+
|
|
3
|
+
- pending: the lines under `## About me (unconfirmed)` in inbox.md (about-me lines and
|
|
4
|
+
teaching-contract rules), each with Approve and Dismiss;
|
|
5
|
+
- expired: live claim lines past their own `(until …)` day (Retire);
|
|
6
|
+
- stale: confirmed lines not reconfirmed or rewritten in STALE_DAYS (Still true or Retire),
|
|
7
|
+
at most STALE_PER_MONTH a month, oldest first;
|
|
8
|
+
- conflicts (plan 5b, D2): pairs of live lines that clash (Keep both, Keep first, Keep second):
|
|
9
|
+
two lines that say opposite things (`opposed`), both the owner's or both inferred; two lines
|
|
10
|
+
on one page that may clash (close, exactly one negated, not `opposed`; W1b); a guessed
|
|
11
|
+
update pair `settle` left alone (W1b). Everything else `settle` resolves itself: lines that
|
|
12
|
+
say the same facts (D1, W1 `same_facts`), recorded `possible_update_of` / `supersedes`
|
|
13
|
+
pairs and an owner's line against an inferred one (D2); mcp_server.Keepfold._tidy retires the
|
|
14
|
+
loser through the retire path;
|
|
15
|
+
- rules (plan 5b, N2): a correction the user typed in two or more imported chats, offered as a
|
|
16
|
+
me/core line (keepfold.corrections; Approve or Dismiss);
|
|
17
|
+
- decisions (RR-9): decision-like commit subjects of imported git repos
|
|
18
|
+
(more_sources.decision_proposals); Approve makes a decision page, Dismiss drops it;
|
|
19
|
+
- forget (R3-5): a `//forget:` the user typed that matched no line or several, with its
|
|
20
|
+
candidate lines (keepfold.tags.forget_cards; Retire a line, or Dismiss);
|
|
21
|
+
- imports (RR-18): an imported page edited by hand whose file changed, so the re-import wrote
|
|
22
|
+
a newer page beside it (keepfold.sources.edited_pages; Dismiss);
|
|
23
|
+
- unsafe (G6): a live claim line that reads as an instruction to an AI or holds invisible
|
|
24
|
+
characters (`unsafe_lines`); it is not served until Keep it (Keep it out retires it);
|
|
25
|
+
- outside (R5a): a line on me/core, me/setup or the teaching contract that Keepfold did not write
|
|
26
|
+
and that was not there at the baseline (`outside_lines`); not served until Keep (Remove
|
|
27
|
+
retires a claim line, deletes any other);
|
|
28
|
+
- crowded (G7): lines the X-ray shows cut for space in most of the latest primes that offered
|
|
29
|
+
them (`crowded`; Keep pins it, Retire, Skip), and unused playbooks (G7): no X-ray call served
|
|
30
|
+
them and their file is UNUSED_DAYS old (`unused`; Keep asks again in UNUSED_DAYS, Open);
|
|
31
|
+
together at most STALE_PER_MONTH a month (`_spare_left`);
|
|
32
|
+
- promote (R28a): a preferences line that keeps coming back (`reinforced`) or that prime
|
|
33
|
+
serves near the top, offered for me/core (`promote`; Pin to Core, Not now), one a month.
|
|
34
|
+
|
|
35
|
+
Similarity (`scorer`): cosine with the bge embedder when this process has it loaded already
|
|
36
|
+
(never loaded or downloaded here), else word overlap: the Jaccard of the crudely stemmed words,
|
|
37
|
+
stop words and negation words left out.
|
|
38
|
+
|
|
39
|
+
The app's handlers (app/server.py) write through `mcp_server.Keepfold` with `app_clicks` set,
|
|
40
|
+
so every write is keepfold_patch's or keepfold_log's own code path."""
|
|
41
|
+
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
import datetime as dt
|
|
45
|
+
import functools
|
|
46
|
+
import hashlib
|
|
47
|
+
import itertools
|
|
48
|
+
import json
|
|
49
|
+
import re
|
|
50
|
+
import sys
|
|
51
|
+
import unicodedata
|
|
52
|
+
|
|
53
|
+
from keepfold import claims
|
|
54
|
+
from keepfold.reflect import _PROPOSED, UNCONFIRMED, UNCONFIRMED_DAYS
|
|
55
|
+
from keepfold.render import plain
|
|
56
|
+
from keepfold.vault import VaultError, is_private
|
|
57
|
+
|
|
58
|
+
STALE_DAYS = {"preferences": 180, "personality": 180, "profile": 365}
|
|
59
|
+
STALE_PER_MONTH = 3
|
|
60
|
+
# the pages a proposal may wait for: mcp_server.CONFIRM_PAGES and, while harvesting, every
|
|
61
|
+
# claim page; the order is the guess for an old line with no `me/<page>` tag
|
|
62
|
+
PAGES = (*claims.PAGES, "portrait", "teaching-contract")
|
|
63
|
+
SHOWN = 300 # characters of a line shown
|
|
64
|
+
_CONFIRMED = re.compile(r"\(confirmed (\d{4}-\d\d-\d\d)\)")
|
|
65
|
+
COS = 0.72 # cosine (warm embedder) from which two lines say about the same thing
|
|
66
|
+
JACCARD = 0.6 # the same for word overlap, when the embedder is not loaded
|
|
67
|
+
SHOWN_PAIRS = 3 # conflict pairs shown at a time (D2)
|
|
68
|
+
INFERRED = ("agent", "exposed") # D1/D2: the tiers of a line a chat inferred (claims.tiers)
|
|
69
|
+
TIDY_MAX = 200 # D1/D2: automatic retires in one sweep
|
|
70
|
+
TODAY_MAX = 5 # R3-4: Today's 5, cards a day
|
|
71
|
+
TODAY_CARDS = ("pending", "conflict", "rule") # the kinds of card Today's 5 offers
|
|
72
|
+
SIGHTINGS = 2 # chats that must propose the same line before it is offered in Today's 5
|
|
73
|
+
SINGLE_DAYS = 14 # a line fewer chats proposed leaves the view this many days after its stamp
|
|
74
|
+
# RR-10: what makes Review cards, as the Status line names them
|
|
75
|
+
PRODUCERS = {"chats": "Lines chats suggest", "imports": "Lines from imported chats",
|
|
76
|
+
"corrections": "Corrections you repeat", "decisions": "Decisions in your commits",
|
|
77
|
+
"forget": "//forget cards"}
|
|
78
|
+
PAUSE_AFTER = 20 # decided cards before a producer whose rejects exceed its accepts pauses
|
|
79
|
+
LEGACY_DISMISS = ("corrections", "decisions", "forget") # a dismiss change's id: its producer
|
|
80
|
+
PRIMES = ("keepfold_prime", "prime-hook") # the X-ray rows that offer the Preferences lines
|
|
81
|
+
WINDOW = 40 # G7: the latest primes a crowded line is judged over
|
|
82
|
+
CROWD_MIN = 5 # primes that must have offered a line before it counts as crowded out
|
|
83
|
+
UNUSED_DAYS = 60 # G7: a playbook's file this old and served by no X-ray call; Keep's quiet days
|
|
84
|
+
SPARE_CARDS = ("crowded", "unused") # the card stamps that spend the G7 monthly cap
|
|
85
|
+
PLAYBOOK_TAG = "playbook" # mcp_server.PLAYBOOK_TAG (it imports this module)
|
|
86
|
+
REINFORCE = "reinforce" # R13b: a change's note when a new line repeated a live one
|
|
87
|
+
PROMOTE = "promote_core" # R28a: the "Pin it to Core?" card's stamp and its Not now's id
|
|
88
|
+
PROMOTE_PROOFS, PROMOTE_APPS = 4, 2 # sessions and AI apps a line came back in, to be offered
|
|
89
|
+
PROMOTE_TOP, PROMOTE_SERVED = 5, 10 # or: primes that served it in their top 5 preferences
|
|
90
|
+
PROMOTE_QUIET = 183 # days Not now keeps a line from being offered again
|
|
91
|
+
_STOP = frozenset("a an the i me my mine to of and or in on at for with is are be am it its "
|
|
92
|
+
"this that so as by from you your".split())
|
|
93
|
+
# a line "says no" with one of these, a `_NEG_PHRASE` or any word ending n't: never/always,
|
|
94
|
+
# don't/do, avoid/prefer, stopped using/uses
|
|
95
|
+
_NEG = frozenset("no not never none nothing nor neither without avoid avoids avoiding stop "
|
|
96
|
+
"stops stopped stopping quit quits quitting refuse refuses refused "
|
|
97
|
+
"hate hates dislike dislikes dont cannot".split())
|
|
98
|
+
_NEG_PHRASE = re.compile(r"\b(?:no longer|g(?:ive|ives|ave|iving|iven) up)\b")
|
|
99
|
+
# W1: a line that says something ended ("used to", "ex-") is never the same fact as one that
|
|
100
|
+
# does not; past verb forms the stemmer merges ("lived") are `_past`'s
|
|
101
|
+
_ENDED = re.compile(r"\b(?:used to|formerly|previously|no longer|back in \d{4})\b|\bex-")
|
|
102
|
+
_NUM = re.compile(r"(\d+(?:[.,]\d+)*)\s*([^\s\d]\S*|)") # a number and the word after it
|
|
103
|
+
_CMP = re.compile(r"\b(rather than|instead of|over|than|before|after)\b") # comparative order
|
|
104
|
+
_COMPARE = re.compile(r"(\S+)\s+(rather than|instead of|over|than|before|after)\s+"
|
|
105
|
+
r"(\S+)") # a comparative with the word on each side (of `_words`)
|
|
106
|
+
_SUFFIX = re.compile(r"(?:(?<=..)ing|(?<!e)ed|es|s)$")
|
|
107
|
+
_VECS: dict = {} # normalised line -> unit vector, from the embedder in _VECS_OF[0]
|
|
108
|
+
_VECS_OF: list = [None]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@functools.cache
|
|
112
|
+
def _word() -> re.Pattern:
|
|
113
|
+
"""R30c: a word is Unicode letters and digits (not `_`) with their combining marks (a Hindi
|
|
114
|
+
matra or virama, which Python's word class leaves out) and apostrophes, so "München",
|
|
115
|
+
"दिल्ली" and "東京" are words. Built on first use (about 30 ms), so importing this module
|
|
116
|
+
stays cheap.
|
|
117
|
+
shortcut: marks of the Basic Multilingual Plane only; all planes if a script needs it."""
|
|
118
|
+
spans: list[list[int]] = []
|
|
119
|
+
for c in range(0x300, 0x10000):
|
|
120
|
+
if unicodedata.category(chr(c))[0] == "M":
|
|
121
|
+
if spans and spans[-1][1] == c - 1:
|
|
122
|
+
spans[-1][1] = c
|
|
123
|
+
else:
|
|
124
|
+
spans.append([c, c])
|
|
125
|
+
marks = "".join(chr(a) if a == b else f"{chr(a)}-{chr(b)}" for a, b in spans)
|
|
126
|
+
return re.compile(rf"(?:[^\W_]|['{marks}])+")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _words(text: str) -> list[str]:
|
|
130
|
+
return _word().findall(unicodedata.normalize("NFC", claims.norm(text)).replace("’", "'"))
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def negated(text: str) -> bool:
|
|
134
|
+
"""Does the line say no (a `_NEG` word or phrase, or a word ending n't)?"""
|
|
135
|
+
return (any(w in _NEG or w.endswith("n't") for w in _words(text))
|
|
136
|
+
or bool(_NEG_PHRASE.search(" ".join(_words(text)))))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _stem(w: str) -> str:
|
|
140
|
+
"""shortcut: a crude suffix strip (use, uses, using, used -> us; study, studies, studying,
|
|
141
|
+
studied -> study); it misses doubled consonants (running) and irregular forms. Tense is
|
|
142
|
+
`same_facts`' job, not the stemmer's. A real stemmer if pairs are missed."""
|
|
143
|
+
if len(w) > 4 and w.endswith(("ies", "ied")):
|
|
144
|
+
return w[:-3] + "y"
|
|
145
|
+
if len(w) > 3:
|
|
146
|
+
w = _SUFFIX.sub("", w)
|
|
147
|
+
return w.rstrip("e") if len(w) > 2 else w
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _bag(text: str) -> frozenset:
|
|
151
|
+
return frozenset(_stem(w) for w in _NEG_PHRASE.sub(" ", " ".join(_words(text))).split()
|
|
152
|
+
if w not in _STOP and w not in _NEG and not w.endswith("n't"))
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def ended(text: str) -> bool:
|
|
156
|
+
"""W1: does the line say something ended (`_ENDED`: used to, formerly, no longer, ex-)?"""
|
|
157
|
+
return bool(_ENDED.search(" ".join(_words(text))))
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _past(text: str) -> frozenset:
|
|
161
|
+
"""W1: the stems of the line's past verb forms, any word ending -ed (lived, used, studied).
|
|
162
|
+
shortcut: an adjective (based, interested) counts too, so such lines stay two (the safe
|
|
163
|
+
side); a part-of-speech tagger if that keeps real copies apart."""
|
|
164
|
+
return frozenset(_stem(w) for w in _words(text) if len(w) > 3 and w.endswith("ed"))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@functools.lru_cache(maxsize=8192) # settle compares every pair: each line is parsed once
|
|
168
|
+
def _facts(text: str) -> tuple:
|
|
169
|
+
"""W1: what `same_facts` compares: the bag, polarity, tense (`ended`, `_past`), the
|
|
170
|
+
numbers with their units (a multiset), the raw `(until …)` stamp (claims.norm drops it),
|
|
171
|
+
and the content words on each side of every comparative (`_CMP`)."""
|
|
172
|
+
norm = " ".join(_words(text))
|
|
173
|
+
m = claims._UNTIL.search(text)
|
|
174
|
+
order = tuple(s if k % 2 else _bag(s) for k, s in enumerate(_CMP.split(norm)))
|
|
175
|
+
return (_bag(text), negated(text), ended(text), _past(text), tuple(sorted(_NUM.findall(norm))),
|
|
176
|
+
m and m.group(1), order)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def same_facts(a: str, b: str) -> bool:
|
|
180
|
+
"""W1: the two lines say the same thing, so Keepfold may retire one by itself: equal bags and
|
|
181
|
+
the same polarity, tense, numbers, `(until …)` stamp and comparative order (`_facts`). A
|
|
182
|
+
strict subset ("…peanuts" / "…peanuts and shellfish") never is."""
|
|
183
|
+
return _facts(a) == _facts(b)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@functools.lru_cache(maxsize=8192)
|
|
187
|
+
def _swapped(text: str) -> tuple:
|
|
188
|
+
"""The (word before, comparative, word after) of each comparative in the line."""
|
|
189
|
+
return tuple(_COMPARE.findall(" ".join(_words(text))))
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# the words a `_NEG` word answers (never/always, avoid/prefer, dislike/like, hate/love): left
|
|
193
|
+
# out of the bags `opposed` compares, so "Always uses tabs" / "Never uses tabs" are opposites
|
|
194
|
+
_POLE = frozenset(map(_stem, ("always", "prefer", "like", "love")))
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def opposed(a: str, b: str) -> bool:
|
|
198
|
+
"""W1: the two lines say opposite things: equal bags (negation words and `_POLE` left
|
|
199
|
+
out) and exactly one negated, or equal bags and a comparative reversed ("Rust over Go" /
|
|
200
|
+
"Go over Rust")."""
|
|
201
|
+
fa, fb = _facts(a), _facts(b)
|
|
202
|
+
if fa[0] - _POLE != fb[0] - _POLE:
|
|
203
|
+
return False
|
|
204
|
+
x, y = _swapped(a), _swapped(b)
|
|
205
|
+
return fa[1] != fb[1] or (bool(x) and x != y and y == tuple((r, c, w) for w, c, r in x))
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def since_for(old: dict, new: dict, day: str, newer: bool | None = None) -> str | None:
|
|
209
|
+
"""R13a: the `(since …)` day line `new` gets when it replaces `old` (rows with `text`, and
|
|
210
|
+
`day` when `newer` is None), or None. A line saying the same facts keeps the old line's own
|
|
211
|
+
since day; a newer line saying something else gets `day`; an older one (the owner's line
|
|
212
|
+
kept over a later guess) none. `newer` None: `new`'s tier day is after `old`'s."""
|
|
213
|
+
if same_facts(old["text"], new["text"]):
|
|
214
|
+
return claims.since(old["text"])
|
|
215
|
+
if newer is None:
|
|
216
|
+
newer = str(new.get("day") or "") > str(old.get("day") or "")
|
|
217
|
+
return day if newer else None
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def apart(a: str, b: str) -> bool:
|
|
221
|
+
"""Each line names something the other does not ("reads news" / "reads papers", "uses
|
|
222
|
+
Python" / "uses Rust"): two facts however close they score, so Keepfold never retires one
|
|
223
|
+
for the other by itself (22 Nov QA: the sweep retired "Reads news every morning")."""
|
|
224
|
+
x, y = _bag(a), _bag(b)
|
|
225
|
+
return bool(x - y) and bool(y - x)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _warm(texts: list[str]) -> list | None:
|
|
229
|
+
"""Unit vectors of `texts` from the bge embedder, only while this process has it in memory
|
|
230
|
+
(`semantic.loaded_embedder`): never imports keepfold.semantic, loads a model or restarts its
|
|
231
|
+
idle clock (M3). None when not in memory or it fails."""
|
|
232
|
+
sem = sys.modules.get("keepfold.semantic")
|
|
233
|
+
embed = sem.loaded_embedder() if sem is not None else None
|
|
234
|
+
if embed is None:
|
|
235
|
+
return None
|
|
236
|
+
try:
|
|
237
|
+
if _VECS_OF[0] is not embed or len(_VECS) > 20000:
|
|
238
|
+
_VECS.clear()
|
|
239
|
+
_VECS_OF[0] = embed
|
|
240
|
+
if new := [t for t in dict.fromkeys(texts) if t not in _VECS]:
|
|
241
|
+
_VECS.update(zip(new, sem._embed(embed, new), strict=True))
|
|
242
|
+
return [_VECS[t] for t in texts]
|
|
243
|
+
except Exception: # a model error must never cost the write or the view: words serve
|
|
244
|
+
return None
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def scorer(texts: list[str], loose: bool = False):
|
|
248
|
+
"""(score(i, j), cut) over `texts`: cosine and COS with a warm embedder, else the Jaccard
|
|
249
|
+
of `_bag`s and JACCARD. A pair scoring at least `cut` says about the same thing; an
|
|
250
|
+
`apart` pair scores 0 unless `loose` (`collision`'s guess, which the agent settles)."""
|
|
251
|
+
bags = [_bag(t) for t in texts]
|
|
252
|
+
|
|
253
|
+
def off(i: int, j: int) -> bool:
|
|
254
|
+
return not loose and bool(bags[i] - bags[j]) and bool(bags[j] - bags[i])
|
|
255
|
+
|
|
256
|
+
vecs = _warm([claims.norm(t) for t in texts])
|
|
257
|
+
if vecs is not None:
|
|
258
|
+
return (lambda i, j: 0.0 if off(i, j) else float(vecs[i] @ vecs[j])), COS
|
|
259
|
+
return (lambda i, j: 0.0 if off(i, j)
|
|
260
|
+
else len(bags[i] & bags[j]) / (len(bags[i] | bags[j]) or 1)), JACCARD
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def collision(vault, page: str, text: str, today: str) -> dict | None:
|
|
264
|
+
"""The live line of a non-private claim page (on a tie, `page`'s own) that `text`, a line
|
|
265
|
+
about to be appended to me/<page>, most likely updates: {page, id, text (raw note text),
|
|
266
|
+
apart}, or None under the cut (`scorer`, loose). An `apart` guess is left to the agent:
|
|
267
|
+
`settle` never retires either line for it."""
|
|
268
|
+
hidden = _private(vault)
|
|
269
|
+
live = [r for r in claims.rows(vault) if claims.is_live(r, today) and r["page"] not in hidden]
|
|
270
|
+
if not live or not claims.norm(text):
|
|
271
|
+
return None
|
|
272
|
+
score, cut = scorer([text, *(r["text"] for r in live)], loose=True)
|
|
273
|
+
k = max(range(len(live)), key=lambda k: (score(0, k + 1), live[k]["page"] == page))
|
|
274
|
+
if score(0, k + 1) < cut:
|
|
275
|
+
return None
|
|
276
|
+
return {"page": live[k]["page"], "id": live[k]["id"], "text": live[k]["text"],
|
|
277
|
+
"apart": apart(text, live[k]["text"])}
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def pair_key(a: dict, b: dict) -> str:
|
|
281
|
+
"""A conflict pair's key: both `page/id`, sorted, so either order is the same pair."""
|
|
282
|
+
return claims.pair_key((a["page"], a["id"]), (b["page"], b["id"]))
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def owned(r: dict) -> bool:
|
|
286
|
+
"""D1/D2: the owner's own line (typed, legacy, or confirmed/approved), not a chat's
|
|
287
|
+
inference (`INFERRED`)."""
|
|
288
|
+
return r.get("tier") not in INFERRED
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def rank(r: dict) -> tuple:
|
|
292
|
+
"""D1: of near-duplicate lines the highest stays: the owner's over an inferred one, then
|
|
293
|
+
the newer (its tier's day), then the longer, then the later line on its page."""
|
|
294
|
+
return (owned(r), str(r.get("day") or ""), len(claims.norm(r["text"])), r.get("line_no", 0))
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def known_texts(vault) -> dict:
|
|
298
|
+
"""(page, id) -> text of every claim line, any status: what `kept_cover` compares with."""
|
|
299
|
+
return {(r["page"], r["id"]): r["text"] for r in claims.rows(vault)}
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def kept_cover(rows: list[dict], events, known: dict | None = None):
|
|
303
|
+
"""D5: (covered(i, j), score, cut, no) over `rows`: covered when the user kept both of
|
|
304
|
+
that pair (a `keep_both` change) or of a pair whose two lines are each near-duplicates of
|
|
305
|
+
the two kept ones (`known`: `known_texts`)."""
|
|
306
|
+
_, kept = claims.recorded_pairs(events)
|
|
307
|
+
known = known or {}
|
|
308
|
+
sides = [[tuple(s.split("/", 1)) for s in k.split("|")] for k in kept]
|
|
309
|
+
sides = [s for s in sides if len(s) == 2 and all(x in known for x in s)]
|
|
310
|
+
texts = [r["text"] for r in rows] + [known[x] for s in sides for x in s]
|
|
311
|
+
score, cut = scorer(texts)
|
|
312
|
+
no = [negated(t) for t in texts]
|
|
313
|
+
n = len(rows)
|
|
314
|
+
|
|
315
|
+
def near(i: int, k: int) -> bool: # W1: only a line saying the same facts
|
|
316
|
+
return score(i, k) >= cut and same_facts(texts[i], texts[k])
|
|
317
|
+
|
|
318
|
+
def covered(i: int, j: int) -> bool:
|
|
319
|
+
if pair_key(rows[i], rows[j]) in kept:
|
|
320
|
+
return True
|
|
321
|
+
return any((near(i, a) and near(j, a + 1)) or (near(i, a + 1) and near(j, a))
|
|
322
|
+
for a in range(n, len(texts), 2))
|
|
323
|
+
|
|
324
|
+
return covered, score, cut, no
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def settle(rows: list[dict], events, known: dict | None = None, skip=frozenset()) -> dict:
|
|
328
|
+
"""D1, D2, D5 over `rows` (tiered live claim rows, none private): {retire: [{retire, keep,
|
|
329
|
+
why, newer}] with raw rows, cards: [{key, why, left, right}]} (why `opposite`, `maybe_update`
|
|
330
|
+
or `maybe_opposite`). `newer` (R13a, `since_for`): whether `keep` is a recorded pair's newer
|
|
331
|
+
line; None when no pair says.
|
|
332
|
+
- a recorded pair (claims.recorded_pairs) whose lines agree: the newer stays, unless the
|
|
333
|
+
older is the owner's and the newer inferred (why `update` or `supersedes`); a guessed
|
|
334
|
+
`update` pair is applied only when `same_facts` or `opposed` (W1), else it is a card
|
|
335
|
+
(why `maybe_update`, the older line left), so prime.held's hold can end;
|
|
336
|
+
- lines on one page that say the same facts (`scorer` cut and `same_facts`): the one
|
|
337
|
+
`rank` puts first stays (why `duplicate`), so n copies are one line;
|
|
338
|
+
- two of the lines left that are `opposed` (or a recorded pair exactly one of which is
|
|
339
|
+
negated): the owner's stays over an inferred one (why `opposite`); two of the owner's or two
|
|
340
|
+
inferred are a card, one per pair of near-copy groups;
|
|
341
|
+
- W1b: two lines left on one page, at least the `scorer` cut, exactly one negated but not
|
|
342
|
+
`opposed` ("Likes spicy food" / "Doesn't like very spicy Thai food"): a card (why
|
|
343
|
+
`maybe_opposite`) whoever wrote them, never retired by itself.
|
|
344
|
+
`conflicts` shows SHOWN_PAIRS cards at a time. A pair the user kept both of (`kept_cover`)
|
|
345
|
+
or whose key is in `skip` is left alone, and so is a line whose `page/id` is in `skip`
|
|
346
|
+
(an automatic retire the user undid)."""
|
|
347
|
+
events = list(events)
|
|
348
|
+
covered, score, cut, no = kept_cover(rows, events, known)
|
|
349
|
+
recorded, _ = claims.recorded_pairs(events)
|
|
350
|
+
at = {(r["page"], r["id"]): i for i, r in enumerate(rows)}
|
|
351
|
+
out, gone, forced = [], set(), []
|
|
352
|
+
|
|
353
|
+
def free(i: int, j: int) -> bool:
|
|
354
|
+
return pair_key(rows[i], rows[j]) not in skip and not covered(i, j)
|
|
355
|
+
|
|
356
|
+
def kept(i: int) -> bool: # the user undid Keepfold retiring this line: never again
|
|
357
|
+
return f"{rows[i]['page']}/{rows[i]['id']}" in skip
|
|
358
|
+
|
|
359
|
+
def drop(i: int, k: int, why: str, newer: bool | None = None) -> None:
|
|
360
|
+
out.append({"retire": rows[i], "keep": rows[k], "why": why, "newer": newer})
|
|
361
|
+
gone.add(i)
|
|
362
|
+
|
|
363
|
+
asks = [] # W1b: guessed updates left alone: a card, so prime.held's hold on the older ends
|
|
364
|
+
for old, new, why in recorded.values():
|
|
365
|
+
o, n = at.get(old), at.get(new)
|
|
366
|
+
if o is None or n is None or o in gone or n in gone or not free(o, n):
|
|
367
|
+
continue
|
|
368
|
+
a, b = rows[o]["text"], rows[n]["text"]
|
|
369
|
+
if why == "update" and not (same_facts(a, b) or opposed(a, b)):
|
|
370
|
+
asks.append((o, n)) # W1: a guessed pair that would lose a fact: both stay
|
|
371
|
+
continue
|
|
372
|
+
if no[o] != no[n]:
|
|
373
|
+
forced.append((o, n))
|
|
374
|
+
elif owned(rows[o]) and not owned(rows[n]):
|
|
375
|
+
if not kept(n):
|
|
376
|
+
drop(n, o, why, False)
|
|
377
|
+
elif not kept(o):
|
|
378
|
+
drop(o, n, why, True)
|
|
379
|
+
rep: dict[int, int] = {} # a line -> the kept line it near-duplicates
|
|
380
|
+
keep: list[int] = []
|
|
381
|
+
for i in sorted((i for i in range(len(rows)) if i not in gone),
|
|
382
|
+
key=lambda i: rank(rows[i]), reverse=True):
|
|
383
|
+
k = next((k for k in keep if rows[k]["page"] == rows[i]["page"] and score(i, k) >= cut
|
|
384
|
+
and same_facts(rows[i]["text"], rows[k]["text"]) and free(i, k)), None)
|
|
385
|
+
if k is None or kept(i):
|
|
386
|
+
keep.append(i)
|
|
387
|
+
else:
|
|
388
|
+
rep[i] = k
|
|
389
|
+
drop(i, k, "duplicate")
|
|
390
|
+
keep.sort()
|
|
391
|
+
pairs = [(rep.get(a, a), rep.get(b, b)) for a, b in forced]
|
|
392
|
+
by: dict[frozenset, list[int]] = {} # opposed lines share their bag less `_POLE`
|
|
393
|
+
for a in keep:
|
|
394
|
+
by.setdefault(_facts(rows[a]["text"])[0] - _POLE, []).append(a)
|
|
395
|
+
pairs += sorted((a, b) for g in by.values() for x, a in enumerate(g) for b in g[x + 1:]
|
|
396
|
+
if opposed(rows[a]["text"], rows[b]["text"]))
|
|
397
|
+
cards, seen = [], set()
|
|
398
|
+
for a, b in pairs:
|
|
399
|
+
if a == b or a in gone or b in gone or frozenset((a, b)) in seen or not free(a, b):
|
|
400
|
+
continue
|
|
401
|
+
seen.add(frozenset((a, b)))
|
|
402
|
+
if owned(rows[a]) != owned(rows[b]):
|
|
403
|
+
lose, win = (b, a) if owned(rows[a]) else (a, b)
|
|
404
|
+
if not kept(lose):
|
|
405
|
+
drop(lose, win, "opposite")
|
|
406
|
+
else:
|
|
407
|
+
cards.append((a, b, "opposite"))
|
|
408
|
+
for a, b in asks: # older left, newer right: the app's Y keeps the right line
|
|
409
|
+
if frozenset((a, b)) not in seen:
|
|
410
|
+
seen.add(frozenset((a, b)))
|
|
411
|
+
cards.append((a, b, "maybe_update"))
|
|
412
|
+
# W1b: lines on one page as close as `scorer`'s cut, exactly one negated, not `opposed`:
|
|
413
|
+
# they may clash, so a card whoever wrote them, never a retire
|
|
414
|
+
sides: dict[str, tuple] = {}
|
|
415
|
+
for a in keep:
|
|
416
|
+
if a not in gone:
|
|
417
|
+
sides.setdefault(rows[a]["page"], ([], []))[no[a]].append(a)
|
|
418
|
+
for yes, nay in sides.values():
|
|
419
|
+
for a, b in sorted(tuple(sorted(p)) for p in itertools.product(yes, nay)):
|
|
420
|
+
if (frozenset((a, b)) not in seen and score(a, b) >= cut and free(a, b)
|
|
421
|
+
and not opposed(rows[a]["text"], rows[b]["text"])):
|
|
422
|
+
seen.add(frozenset((a, b)))
|
|
423
|
+
cards.append((a, b, "maybe_opposite"))
|
|
424
|
+
return {"retire": out, "cards": [
|
|
425
|
+
{"key": pair_key(rows[a], rows[b]), "why": why, "left": rows[a], "right": rows[b]}
|
|
426
|
+
for a, b, why in cards if a not in gone and b not in gone]}
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def conflicts(rows: list[dict], events: list[dict], known: dict | None = None) -> list[dict]:
|
|
430
|
+
"""D2: up to SHOWN_PAIRS pairs of `rows` (live, shown claim rows) that clash and Keepfold
|
|
431
|
+
does not settle itself (`settle`'s cards: an opposite pair of two of the owner's lines or
|
|
432
|
+
two inferred ones, a guessed update left alone, a pair that may clash), as {key, why,
|
|
433
|
+
left, right} with raw rows; Keep first or second retires the other line, Keep both
|
|
434
|
+
covers near-copies of the pair too (`kept_cover`)."""
|
|
435
|
+
return settle(rows, events, known)["cards"][:SHOWN_PAIRS]
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def copies(rows: list[dict], r: dict) -> list[dict]:
|
|
439
|
+
"""D5: `r` and the `rows` on its page that say the same (the `scorer` cut, W1
|
|
440
|
+
`same_facts`), `r` first: what Keep first or second on a conflict card retires."""
|
|
441
|
+
same = [x for x in rows if x["page"] == r["page"] and x["id"] != r["id"]
|
|
442
|
+
and same_facts(x["text"], r["text"])] # W1: never a line holding another fact
|
|
443
|
+
score, cut = scorer([r["text"], *(x["text"] for x in same)])
|
|
444
|
+
return [r, *(x for i, x in enumerate(same, 1) if score(0, i) >= cut)]
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def collapse(items: list[dict], text=lambda x: x["text"]) -> list[dict]:
|
|
448
|
+
"""D5: near-identical `items` (the `scorer` cut, W1 `same_facts`) as one: the first of each
|
|
449
|
+
group, with `members` (the group, itself first). A click on it covers every member."""
|
|
450
|
+
if not items:
|
|
451
|
+
return []
|
|
452
|
+
texts = [text(x) for x in items]
|
|
453
|
+
score, cut = scorer(texts)
|
|
454
|
+
groups: list[list[int]] = []
|
|
455
|
+
for i in range(len(items)):
|
|
456
|
+
g = next((g for g in groups if score(g[0], i) >= cut
|
|
457
|
+
and same_facts(texts[g[0]], texts[i])), None) # W1: the same facts only
|
|
458
|
+
if g is None:
|
|
459
|
+
groups.append([i])
|
|
460
|
+
else:
|
|
461
|
+
g.append(i)
|
|
462
|
+
return [{**items[g[0]], "members": [items[i] for i in g]} for g in groups]
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def group(items: list[dict], want, field: str = "key", text=lambda x: x["text"]) -> list:
|
|
466
|
+
"""D5: the `field` values of the `collapse` group of `items` holding the item whose `field`
|
|
467
|
+
is `want`, that one first; [want] when none holds it."""
|
|
468
|
+
for g in collapse(items, text):
|
|
469
|
+
got = [m[field] for m in g["members"]]
|
|
470
|
+
if want in got:
|
|
471
|
+
return [want, *(x for x in got if x != want)]
|
|
472
|
+
return [want]
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _spare_left(events, today: str) -> int:
|
|
476
|
+
"""G7: how many crowded and unused cards this month still has: STALE_PER_MONTH minus the
|
|
477
|
+
clicks this month stamped with a SPARE_CARDS card (one per click, its session)."""
|
|
478
|
+
voided, said = _voided(events), set()
|
|
479
|
+
for e in events:
|
|
480
|
+
c = _payload(e).get("change") if e.get("kind") == "change" else None
|
|
481
|
+
if (isinstance(c, dict) and c.get("card") in SPARE_CARDS and e.get("id") not in voided
|
|
482
|
+
and str(e.get("day") or "")[:7] == today[:7]):
|
|
483
|
+
said.add(e.get("session"))
|
|
484
|
+
return max(0, STALE_PER_MONTH - len(said))
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _ids(blocks) -> set[str]:
|
|
488
|
+
"""The ids of an X-ray row's `served` or `trimmed` {block: [ids]}, whatever its shape."""
|
|
489
|
+
return {i for v in (blocks.values() if isinstance(blocks, dict) else ())
|
|
490
|
+
for i in (v if isinstance(v, list) else ()) if isinstance(i, str)}
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def crowded(vault, rows: list[dict]) -> tuple[list[dict], int]:
|
|
494
|
+
"""G7: (the `rows` (live, shown claim rows) the X-ray shows cut for space in most of the
|
|
495
|
+
latest WINDOW primes that offered them, at least CROWD_MIN, as {page, id, text (raw), cut,
|
|
496
|
+
seen} most cut first; how many primes the window holds). A pinned line (Keep pins it) or a
|
|
497
|
+
muted one is left out."""
|
|
498
|
+
from collections import Counter
|
|
499
|
+
|
|
500
|
+
from keepfold import xray
|
|
501
|
+
primes = [r for r in xray.rows(vault) if r.get("tool") in PRIMES][-WINDOW:]
|
|
502
|
+
seen, cut = Counter(), Counter()
|
|
503
|
+
for r in primes:
|
|
504
|
+
s, t = _ids(r.get("served")), _ids(r.get("trimmed"))
|
|
505
|
+
seen.update(s | t)
|
|
506
|
+
cut.update(t - s)
|
|
507
|
+
xs = xray.settings(vault)
|
|
508
|
+
flagged = xs["pin"] | xs["mute"]
|
|
509
|
+
out = [{"page": r["page"], "id": r["id"], "text": r["text"], "cut": cut[c], "seen": seen[c]}
|
|
510
|
+
for r in rows if (c := xray.claim(r["id"])) not in flagged
|
|
511
|
+
and seen[c] >= CROWD_MIN and 2 * cut[c] > seen[c]]
|
|
512
|
+
out.sort(key=lambda x: (-x["cut"] / x["seen"], x["page"], x["id"]))
|
|
513
|
+
return out, len(primes)
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def unused(vault, events, today: str) -> tuple[list[dict], int, str | None]:
|
|
517
|
+
"""G7: (the playbooks (`note` pages tagged PLAYBOOK_TAG, none private or muted) that no
|
|
518
|
+
X-ray call served and whose file is over UNUSED_DAYS old, not kept (a `dismiss` change on
|
|
519
|
+
id `playbooks` holding the id's hash) in the last UNUSED_DAYS, oldest first, as {id, title,
|
|
520
|
+
path (vault-relative), changed}; the X-ray calls seen; the first one's day). Nothing while
|
|
521
|
+
the X-ray holds no call. R27b: a keepfold_find, keepfold_recall or keepfold_read that returned a
|
|
522
|
+
playbook counts as serving it too, which only ever keeps a playbook off this list."""
|
|
523
|
+
from keepfold import xray
|
|
524
|
+
calls = xray.rows(vault)
|
|
525
|
+
if not calls:
|
|
526
|
+
return [], 0, None
|
|
527
|
+
served = {i for r in calls for i in _ids(r.get("served"))}
|
|
528
|
+
since = (dt.date.fromisoformat(today) - dt.timedelta(days=UNUSED_DAYS)).isoformat()
|
|
529
|
+
voided, kept = _voided(events), set()
|
|
530
|
+
for e in events:
|
|
531
|
+
c = _payload(e).get("change") if e.get("kind") == "change" else None
|
|
532
|
+
if (isinstance(c, dict) and c.get("tool") == "dismiss" and c.get("id") == "playbooks"
|
|
533
|
+
and e.get("id") not in voided and str(e.get("day") or "") > since):
|
|
534
|
+
kept.add(c.get("hash"))
|
|
535
|
+
mute = xray.settings(vault)["mute"]
|
|
536
|
+
out = []
|
|
537
|
+
for n in vault.iter_notes("note"):
|
|
538
|
+
tags = n.fields.get("tags")
|
|
539
|
+
if (PLAYBOOK_TAG not in (tags if isinstance(tags, list) else [tags]) or is_private(n)
|
|
540
|
+
or n.id in mute or n.id in served or text_hash(n.id) in kept):
|
|
541
|
+
continue
|
|
542
|
+
changed = dt.date.fromtimestamp(n.path.stat().st_mtime).isoformat()
|
|
543
|
+
if changed < since:
|
|
544
|
+
out.append({"id": n.id, "title": plain(str(n.fields.get("title") or n.id), SHOWN),
|
|
545
|
+
"path": n.path.relative_to(vault.root).as_posix(), "changed": changed})
|
|
546
|
+
out.sort(key=lambda x: (x["changed"], x["id"]))
|
|
547
|
+
try: # the oldest call's Keepfold day
|
|
548
|
+
from keepfold.events import local_day
|
|
549
|
+
first = local_day(dt.datetime.fromisoformat(str(calls[0].get("ts"))))
|
|
550
|
+
except (TypeError, ValueError):
|
|
551
|
+
first = None
|
|
552
|
+
return out, len(calls), first
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def text_hash(text: str) -> str:
|
|
556
|
+
"""A dismissed line's mark in its `dismiss` change event: never the text itself."""
|
|
557
|
+
return hashlib.sha256(claims.norm(text).encode()).hexdigest()[:16]
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def _voided(events: list[dict]) -> set:
|
|
561
|
+
return {e.get("ref") for e in events if e.get("kind") == "void"}
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def _payload(e: dict) -> dict:
|
|
565
|
+
return e["payload"] if isinstance(e.get("payload"), dict) else {}
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def dismissed(events, page: str, text: str) -> bool:
|
|
569
|
+
"""True when Dismiss in the app dropped `text` for me/<page> (a `dismiss` change event)."""
|
|
570
|
+
events, h = list(events), text_hash(text)
|
|
571
|
+
voided = _voided(events)
|
|
572
|
+
for e in events:
|
|
573
|
+
c = _payload(e).get("change") if e.get("kind") == "change" else None
|
|
574
|
+
if (isinstance(c, dict) and c.get("tool") == "dismiss" and c.get("id") == page
|
|
575
|
+
and c.get("hash") == h and e.get("id") not in voided):
|
|
576
|
+
return True
|
|
577
|
+
return False
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def unsafe_lines(vault, events) -> list[dict]:
|
|
581
|
+
"""G6: the live claim lines (private pages too) whose text or section claims.unsafe flags
|
|
582
|
+
and Keep has not kept, as {key, page, id, section, text (raw), what}. Keep is a `dismiss`
|
|
583
|
+
change on id `unsafe` holding the key's hash (`dismissed`); the key hashes the page and the
|
|
584
|
+
exact line, so a line edited since is checked again.
|
|
585
|
+
G5b-6: also a line whose text or section claims.command flags, when an AI app wrote it
|
|
586
|
+
(tier agent or exposed, or confirmed by a yes other than the owner's click or tag); its row
|
|
587
|
+
has `command: True`. The tier fold runs only when such a line is found."""
|
|
588
|
+
events = list(events)
|
|
589
|
+
voided, kept = _voided(events), set()
|
|
590
|
+
for e in events:
|
|
591
|
+
c = _payload(e).get("change") if e.get("kind") == "change" else None
|
|
592
|
+
if (isinstance(c, dict) and c.get("tool") == "dismiss" and c.get("id") == "unsafe"
|
|
593
|
+
and e.get("id") not in voided):
|
|
594
|
+
kept.add(c.get("hash"))
|
|
595
|
+
out, sections = [], {}
|
|
596
|
+
for r in claims.rows(vault):
|
|
597
|
+
if r["status"] != "live":
|
|
598
|
+
continue
|
|
599
|
+
what = claims.unsafe(r["text"], r["page"]) or claims.unsafe(r["section"], r["page"])
|
|
600
|
+
if not what and r["section"] not in sections:
|
|
601
|
+
sections[r["section"]] = claims.command(r["section"])
|
|
602
|
+
cmd = None if what else claims.command(r["text"]) or sections[r["section"]]
|
|
603
|
+
if not (what or cmd):
|
|
604
|
+
continue
|
|
605
|
+
key = hashlib.sha256(f"{r['page']}\n{r['section']}\n{r['text']}".encode()).hexdigest()[:16]
|
|
606
|
+
if text_hash(key) not in kept:
|
|
607
|
+
out.append({"key": key, "page": r["page"], "id": r["id"], "section": r["section"],
|
|
608
|
+
"text": r["text"], "what": what or cmd, **({"command": True} if cmd
|
|
609
|
+
else {})})
|
|
610
|
+
if any(x.get("command") for x in out):
|
|
611
|
+
by = {(t["page"], t["id"]): t for t in claims.tiers(vault, events)}
|
|
612
|
+
out = [x for x in out if not x.get("command") or _by_app(by.get((x["page"], x["id"])))]
|
|
613
|
+
return out
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def _by_app(t: dict | None) -> bool:
|
|
617
|
+
"""G5b-6: a claims.tiers row an AI app wrote: not the owner's (a click or a //pref or
|
|
618
|
+
//fact tag), nor a typed or legacy line."""
|
|
619
|
+
return bool(t) and (t["tier"] in INFERRED or (
|
|
620
|
+
t["tier"] == "confirmed" and t["confirm"] not in ("clicked", "tagged")))
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
# R5a: the pages every AI app takes as standing orders. A line on them that Keepfold did not write
|
|
624
|
+
# and the owner did not keep is "changed outside Keepfold" and is not served until Keep.
|
|
625
|
+
GUARDED = ("core", "setup", "teaching-contract")
|
|
626
|
+
OUTSIDE = "outside" # the card's type and its Keep's `dismiss` id
|
|
627
|
+
GUARD_FILE = ".keepfold/guard-baseline.json" # the guarded lines present at the upgrade
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def line_hash(line: str) -> str:
|
|
631
|
+
"""R5a: a guarded line's mark: the line without its claim id, whitespace collapsed; case
|
|
632
|
+
and `(confirmed …)`-style markers count, so any edit makes a new line."""
|
|
633
|
+
return hashlib.sha256(" ".join(claims.strip_id(line).split()).encode()).hexdigest()[:16]
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def line_key(page: str, line: str) -> str:
|
|
637
|
+
"""R5a: a guarded line's card key, also its mark in prime.held's set."""
|
|
638
|
+
return f"{page}:{line_hash(line)}"
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def guarded_lines(vault) -> list[dict]:
|
|
642
|
+
"""R5a: every line an AI app may be served from the GUARDED pages, as {page, section,
|
|
643
|
+
line, id (a claim row's, else None), key}: on me/core and me/setup the non-blank lines of
|
|
644
|
+
each `## ` section but Past and Not me, its heading included (keepfold_context serves a
|
|
645
|
+
section's other lines too); on the contract every non-blank line, front matter too."""
|
|
646
|
+
out = []
|
|
647
|
+
for page in GUARDED:
|
|
648
|
+
p = vault.root / "me" / f"{page}.md"
|
|
649
|
+
text = p.read_bytes().decode("utf-8") if p.is_file() else ""
|
|
650
|
+
claim = page in claims.PAGES
|
|
651
|
+
ids = {r["line_no"]: r["id"] for r in claims.parse(page, text)} if claim else {}
|
|
652
|
+
section = None
|
|
653
|
+
for no, ln in enumerate(text.splitlines()):
|
|
654
|
+
if claim and (m := claims._H2.match(ln)):
|
|
655
|
+
section = m.group(1)
|
|
656
|
+
if not ln.strip() or claim and (section is None
|
|
657
|
+
or section.lower() in claims.RESERVED):
|
|
658
|
+
continue
|
|
659
|
+
out.append({"page": page, "section": section, "line": ln.rstrip(),
|
|
660
|
+
"id": ids.get(no), "key": line_key(page, ln)})
|
|
661
|
+
return out
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def _baseline(vault) -> dict | None:
|
|
665
|
+
"""R5a: GUARD_FILE's {page: line hashes}, None when it is missing or unreadable."""
|
|
666
|
+
try:
|
|
667
|
+
got = json.loads((vault.root / GUARD_FILE).read_bytes())
|
|
668
|
+
except (OSError, ValueError):
|
|
669
|
+
return None
|
|
670
|
+
return got.get("lines") if isinstance(got, dict) and isinstance(got.get("lines"),
|
|
671
|
+
dict) else None
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
def guard(vault, events) -> tuple[dict | None, set]:
|
|
675
|
+
"""R5a: ({page: line hashes Keepfold wrote or found at the baseline}, None before the
|
|
676
|
+
baseline is taken; the hashes of the kept card keys). Written: an unvoided change on a
|
|
677
|
+
GUARDED page listing its `lines` (keepfold_patch), or a retire's `kept` line it stamped with
|
|
678
|
+
`(since …)` (R13a); kept: a `dismiss` change on id OUTSIDE."""
|
|
679
|
+
base = _baseline(vault)
|
|
680
|
+
events = list(events)
|
|
681
|
+
voided, ok, kept = _voided(events), {p: set() for p in GUARDED}, set()
|
|
682
|
+
for e in events:
|
|
683
|
+
c = _payload(e).get("change") if e.get("kind") == "change" else None
|
|
684
|
+
if not isinstance(c, dict) or e.get("id") in voided:
|
|
685
|
+
continue
|
|
686
|
+
if c.get("id") in GUARDED and isinstance(c.get("lines"), list):
|
|
687
|
+
ok[c["id"]].update(h for h in c["lines"] if isinstance(h, str))
|
|
688
|
+
elif c.get("tool") == "dismiss" and c.get("id") == OUTSIDE:
|
|
689
|
+
kept.add(c.get("hash"))
|
|
690
|
+
k = c.get("kept") # R13a: the line a retire stamped `(since …)`, as Keepfold wrote it
|
|
691
|
+
if isinstance(k, dict) and k.get("page") in GUARDED and isinstance(k.get("line"), str):
|
|
692
|
+
ok[k["page"]].add(k["line"])
|
|
693
|
+
if base is None:
|
|
694
|
+
return None, kept
|
|
695
|
+
for p in GUARDED:
|
|
696
|
+
if isinstance(got := base.get(p), list):
|
|
697
|
+
ok[p].update(h for h in got if isinstance(h, str))
|
|
698
|
+
return ok, kept
|
|
699
|
+
|
|
700
|
+
|
|
701
|
+
def outside_lines(vault, events) -> list[dict]:
|
|
702
|
+
"""R5a: the `guarded_lines` changed outside Keepfold: neither written by Keepfold, present at
|
|
703
|
+
the baseline nor kept; [] before the baseline is taken. A removed line needs no guard."""
|
|
704
|
+
ok, kept = guard(vault, events)
|
|
705
|
+
if ok is None:
|
|
706
|
+
return []
|
|
707
|
+
return [x for x in guarded_lines(vault) if line_hash(x["line"]) not in ok[x["page"]]
|
|
708
|
+
and text_hash(x["key"]) not in kept]
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
def record_baseline(vault) -> bool:
|
|
712
|
+
"""R5a, first run: with no GUARD_FILE yet, every guarded line present now is written there
|
|
713
|
+
as Keepfold's own (through keepfold.vault, under its lock), so nothing the owner has on upgrade
|
|
714
|
+
is withheld. A cache file, as the X-ray's, never a note; True when it wrote one.
|
|
715
|
+
shortcut: a deleted file is taken again from the pages as they are then; an event in the
|
|
716
|
+
log if a program that deletes it ever matters (it could edit the log as well)."""
|
|
717
|
+
path = vault.root / GUARD_FILE
|
|
718
|
+
if path.is_file():
|
|
719
|
+
return False
|
|
720
|
+
with vault.lock():
|
|
721
|
+
if path.is_file(): # another process took it meanwhile
|
|
722
|
+
return False
|
|
723
|
+
lines: dict[str, set[str]] = {p: set() for p in GUARDED}
|
|
724
|
+
for x in guarded_lines(vault):
|
|
725
|
+
lines[x["page"]].add(line_hash(x["line"]))
|
|
726
|
+
vault.write_text(path, json.dumps({"lines": {p: sorted(h) for p, h in lines.items()}}))
|
|
727
|
+
return True
|
|
728
|
+
|
|
729
|
+
|
|
730
|
+
def _private(vault) -> set[str]:
|
|
731
|
+
return {n.id for n in vault.iter_notes("me") if is_private(n)}
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
def _page_of(vault, section: str) -> str:
|
|
735
|
+
"""An old line with no `me/<page>` tag: the first page with its `## section`, a YYYY-MM
|
|
736
|
+
section the portrait, else preferences."""
|
|
737
|
+
if re.fullmatch(r"\d{4}-\d\d", section):
|
|
738
|
+
return "portrait"
|
|
739
|
+
want = f"## {section}".casefold()
|
|
740
|
+
for page in PAGES:
|
|
741
|
+
p = vault.root / "me" / f"{page}.md"
|
|
742
|
+
if p.is_file() and want in (ln.strip().casefold()
|
|
743
|
+
for ln in p.read_bytes().decode("utf-8").splitlines()):
|
|
744
|
+
return page
|
|
745
|
+
return "preferences"
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def pending(vault, today: str) -> list[dict]:
|
|
749
|
+
"""The waiting lines as {key, page, section, text, since} with raw note text, one per
|
|
750
|
+
(page, section, text) with its latest stamp. Left out as reflect.unconfirmed leaves them
|
|
751
|
+
(stamped over UNCONFIRMED_DAYS ago), and lines with no `<section>: ` or for a private page."""
|
|
752
|
+
p = vault.root / "inbox.md"
|
|
753
|
+
cut = (dt.date.fromisoformat(today) - dt.timedelta(days=UNCONFIRMED_DAYS)).isoformat()
|
|
754
|
+
hidden, out, on = _private(vault), {}, False
|
|
755
|
+
for ln in p.read_bytes().decode("utf-8").splitlines() if p.is_file() else []:
|
|
756
|
+
if ln.startswith("#"):
|
|
757
|
+
on = ln.strip() == UNCONFIRMED
|
|
758
|
+
continue
|
|
759
|
+
if not on or not ln.startswith("- "):
|
|
760
|
+
continue
|
|
761
|
+
m = _PROPOSED.search(ln)
|
|
762
|
+
section, sep, text = _PROPOSED.sub("", ln)[2:].strip().partition(": ")
|
|
763
|
+
section, text, since = section.strip(), text.strip(), m.group(1) if m else None
|
|
764
|
+
if not (sep and section and text) or (since and since < cut):
|
|
765
|
+
continue
|
|
766
|
+
page = (m and m.group(2)) or _page_of(vault, section)
|
|
767
|
+
if page not in PAGES or page in hidden:
|
|
768
|
+
continue
|
|
769
|
+
key = hashlib.sha256(f"{page}\n{claims.norm(section)}\n{claims.norm(text)}".encode()
|
|
770
|
+
).hexdigest()[:16]
|
|
771
|
+
if key not in out or (since or "") > (out[key]["since"] or ""):
|
|
772
|
+
out[key] = {"key": key, "page": page, "section": section, "text": text,
|
|
773
|
+
"since": since}
|
|
774
|
+
return list(out.values())
|
|
775
|
+
|
|
776
|
+
|
|
777
|
+
def _shown(text: str) -> str:
|
|
778
|
+
"""Note text for the page: no `(confirmed …)`-style markers, links, images or HTML."""
|
|
779
|
+
return plain(claims._MARK.sub("", text), SHOWN)
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def reinforce(log, session: str, page: str, claim: str, client: str | None = None) -> None:
|
|
783
|
+
"""R13b: a new line repeated live line `claim` of me/<page> (a near-copy dropped at write
|
|
784
|
+
time): a `change` event {note: reinforce, page, claim, client} in `session`. `client` is
|
|
785
|
+
the AI app as the server knows it (the MCP handshake), never tool input; id, day and
|
|
786
|
+
session are stamped by the log. History only (`reinforced` folds it); best effort."""
|
|
787
|
+
try:
|
|
788
|
+
log.append(session=session, kind="change", source="tutor", fields={"payload": {
|
|
789
|
+
"note": REINFORCE, "page": page, "claim": claim,
|
|
790
|
+
**({"client": client[:100]} if client else {})}})
|
|
791
|
+
except VaultError:
|
|
792
|
+
pass # a sighting is never worth failing the write it rides on
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
def reinforced(events, known: dict | None = None) -> dict[str, dict]:
|
|
796
|
+
"""R13b: {claim id: {sessions, apps, last}} for each line that came back: a `reinforce`
|
|
797
|
+
change names it, or Keepfold retired a near-copy of it (an `auto` retire whose `kept` it is:
|
|
798
|
+
why `duplicate`, or why `update` when `known` (`known_texts`) shows the two lines say the
|
|
799
|
+
same facts, as a repeat at write time is recorded; not a swapped comparative). A sighting
|
|
800
|
+
is the session that said the line again (for a retired copy, the session that wrote the
|
|
801
|
+
copy; a copy no change wrote is not counted), its AI app (the event's `client`, else its
|
|
802
|
+
session's `open` one) and its day. A kept line takes over its retired copy's sightings, so
|
|
803
|
+
a line said again and again keeps adding up; once a line has one, its own write counts
|
|
804
|
+
too. `len(sessions)` is its proofs, `len(apps)` its apps, `days` {session: its first day}
|
|
805
|
+
(for `use`)."""
|
|
806
|
+
events = list(events)
|
|
807
|
+
voided, apps, wrote, out = _voided(events), {}, {}, {}
|
|
808
|
+
|
|
809
|
+
def saw(cid, by) -> dict | None:
|
|
810
|
+
if not isinstance(cid, str) or by is None or not by[1]:
|
|
811
|
+
return None
|
|
812
|
+
x = out.setdefault(cid, {"sessions": set(), "apps": set(), "last": "", "days": {}})
|
|
813
|
+
sid, day, app = by
|
|
814
|
+
x["sessions"].add(sid)
|
|
815
|
+
x["days"][sid] = min(day, x["days"].get(sid, day))
|
|
816
|
+
if app := app or apps.get(sid):
|
|
817
|
+
x["apps"].add(app)
|
|
818
|
+
x["last"] = max(x["last"], day)
|
|
819
|
+
return x
|
|
820
|
+
|
|
821
|
+
for e in events:
|
|
822
|
+
if e.get("id") in voided:
|
|
823
|
+
continue
|
|
824
|
+
pl, sid, day = _payload(e), e.get("session"), str(e.get("day") or "")
|
|
825
|
+
if e.get("kind") == "open" and isinstance(pl.get("client"), str):
|
|
826
|
+
apps[sid] = pl["client"]
|
|
827
|
+
if e.get("kind") != "change":
|
|
828
|
+
continue
|
|
829
|
+
if pl.get("note") == REINFORCE:
|
|
830
|
+
saw(pl.get("claim"), (sid, day, pl.get("client")))
|
|
831
|
+
c = pl.get("change")
|
|
832
|
+
if not isinstance(c, dict):
|
|
833
|
+
continue
|
|
834
|
+
if c.get("tier") and c.get("claim"):
|
|
835
|
+
for cid in c["claim"] if isinstance(c["claim"], list) else [c["claim"]]:
|
|
836
|
+
wrote[cid] = (sid, day, None)
|
|
837
|
+
if c.get("auto") and isinstance(k := c.get("kept"), dict) and (
|
|
838
|
+
c.get("why") == "duplicate" or c.get("why") == "update" and _same(
|
|
839
|
+
known, (c.get("id"), c.get("claim")), (k.get("page"), k.get("claim")))):
|
|
840
|
+
copy = c.get("claim")
|
|
841
|
+
x = saw(c["kept"].get("claim"), wrote.get(copy) if isinstance(copy, str) else None)
|
|
842
|
+
if x is not None and (y := out.pop(copy, None)) is not None:
|
|
843
|
+
x["sessions"] |= y["sessions"]
|
|
844
|
+
for s, d in y["days"].items():
|
|
845
|
+
x["days"][s] = min(d, x["days"].get(s, d))
|
|
846
|
+
x["apps"] |= y["apps"]
|
|
847
|
+
x["last"] = max(x["last"], y["last"])
|
|
848
|
+
for cid in list(out):
|
|
849
|
+
saw(cid, wrote.get(cid))
|
|
850
|
+
return out
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def use(vault, events, before: str | None = None, known: dict | None = None,
|
|
854
|
+
back: dict | None = None) -> dict[str, dict]:
|
|
855
|
+
"""G5b-4: {claim id: {n, last}}: how often a claim line was used and the last day it was:
|
|
856
|
+
each X-ray call that served it to an AI app, each yes reconfirm and each time it came back
|
|
857
|
+
(`back`: `reinforced` over `events`, folded here when not given; `known`: `known_texts`,
|
|
858
|
+
read when not given). With `before` (an ISO day) only days before it, so prime's order from
|
|
859
|
+
it stays the same all day. A fold over the X-ray ring and the events; nothing stored.
|
|
860
|
+
shortcut: the ring keeps xray.CAP calls, and a tidy's retire hands a copy's past sightings
|
|
861
|
+
to the kept line, so either during the day can move a line across a bucket edge
|
|
862
|
+
(prime.use_order); snapshot the fold per day if caches miss."""
|
|
863
|
+
from keepfold import xray
|
|
864
|
+
from keepfold.events import local_day
|
|
865
|
+
|
|
866
|
+
out: dict[str, dict] = {}
|
|
867
|
+
events = list(events)
|
|
868
|
+
if back is None:
|
|
869
|
+
back = reinforced(events, known_texts(vault) if known is None else known)
|
|
870
|
+
|
|
871
|
+
def add(cid, day: str) -> None:
|
|
872
|
+
if isinstance(cid, str) and day and (before is None or day < before):
|
|
873
|
+
x = out.setdefault(cid, {"n": 0, "last": ""})
|
|
874
|
+
x["n"] += 1
|
|
875
|
+
x["last"] = max(x["last"], day)
|
|
876
|
+
|
|
877
|
+
for r in xray.rows(vault):
|
|
878
|
+
try:
|
|
879
|
+
day = local_day(dt.datetime.fromisoformat(str(r.get("ts"))))
|
|
880
|
+
except (TypeError, ValueError):
|
|
881
|
+
continue
|
|
882
|
+
for i in _ids(r.get("served")):
|
|
883
|
+
if i.startswith("^"):
|
|
884
|
+
add(i[1:], day)
|
|
885
|
+
events = [e for e in events if before is None or str(e.get("day") or "") < before]
|
|
886
|
+
voided = _voided(events)
|
|
887
|
+
for e in events:
|
|
888
|
+
pl = _payload(e)
|
|
889
|
+
if (e.get("kind") == "log" and pl.get("kind") == "reconfirm" and pl.get("verdict") == "yes"
|
|
890
|
+
and e.get("id") not in voided):
|
|
891
|
+
add(pl.get("claim"), str(e.get("day") or ""))
|
|
892
|
+
for cid, x in back.items():
|
|
893
|
+
for day in x["days"].values():
|
|
894
|
+
add(cid, day)
|
|
895
|
+
return out
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
def _same(known: dict | None, a: tuple, b: tuple) -> bool:
|
|
899
|
+
"""Do lines `a` and `b` ((page, id) in `known`) say the same facts, markers aside (a
|
|
900
|
+
retired line carries its `(until …)`)?"""
|
|
901
|
+
x, y = (known or {}).get(a), (known or {}).get(b)
|
|
902
|
+
return x is not None and y is not None and same_facts(claims._MARK.sub("", x),
|
|
903
|
+
claims._MARK.sub("", y))
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
def _clicked_this_month(events, card: str, today: str) -> bool:
|
|
907
|
+
"""A click this calendar month whose change the app stamped with `card`."""
|
|
908
|
+
voided = _voided(events)
|
|
909
|
+
return any(isinstance(c := _payload(e).get("change"), dict) and c.get("card") == card
|
|
910
|
+
and e.get("kind") == "change" and e.get("id") not in voided
|
|
911
|
+
and str(e.get("day") or "")[:7] == today[:7] for e in events)
|
|
912
|
+
|
|
913
|
+
|
|
914
|
+
def promote(vault, rows: list[dict], events, today: str) -> list[dict]:
|
|
915
|
+
"""R28a: the "Pin it to Core?" card, at most one a calendar month (none once a click this
|
|
916
|
+
month was stamped PROMOTE): the owner's live preferences line (confirmed, typed or legacy;
|
|
917
|
+
not on me/core, not X-ray muted, not put off with Not now in the last PROMOTE_QUIET days: a
|
|
918
|
+
`dismiss` change on id PROMOTE holding its id's hash) that came back in PROMOTE_PROOFS
|
|
919
|
+
sessions from PROMOTE_APPS AI apps (`reinforced`), or that prime served in its top
|
|
920
|
+
PROMOTE_TOP Preferences lines PROMOTE_SERVED times (the X-ray's rows). Most proofs first,
|
|
921
|
+
then most served. As [{page, id, text (raw), proofs, apps, served}]."""
|
|
922
|
+
from keepfold import xray
|
|
923
|
+
events = list(events)
|
|
924
|
+
if _clicked_this_month(events, PROMOTE, today):
|
|
925
|
+
return []
|
|
926
|
+
since = (dt.date.fromisoformat(today) - dt.timedelta(days=PROMOTE_QUIET)).isoformat()
|
|
927
|
+
voided, later = _voided(events), set()
|
|
928
|
+
for e in events:
|
|
929
|
+
c = _payload(e).get("change") if e.get("kind") == "change" else None
|
|
930
|
+
if (isinstance(c, dict) and c.get("tool") == "dismiss" and c.get("id") == PROMOTE
|
|
931
|
+
and e.get("id") not in voided and str(e.get("day") or "") > since):
|
|
932
|
+
later.add(c.get("hash"))
|
|
933
|
+
core = {claims.norm(r["text"]) for r in rows if r["page"] == "core"}
|
|
934
|
+
top: dict[str, int] = {}
|
|
935
|
+
for r in xray.rows(vault):
|
|
936
|
+
got = r.get("served")
|
|
937
|
+
prefs = got.get("preferences") if isinstance(got, dict) else None
|
|
938
|
+
if r.get("tool") in PRIMES and isinstance(prefs, list):
|
|
939
|
+
for i in prefs[:PROMOTE_TOP]:
|
|
940
|
+
top[i] = top.get(i, 0) + 1
|
|
941
|
+
back, mute = reinforced(events, known_texts(vault)), xray.settings(vault)["mute"]
|
|
942
|
+
out = []
|
|
943
|
+
for r in rows:
|
|
944
|
+
x = back.get(r["id"], {})
|
|
945
|
+
proofs, apps, served = len(x.get("sessions", ())), len(x.get("apps", ())), top.get(
|
|
946
|
+
xray.claim(r["id"]), 0)
|
|
947
|
+
if (r["page"] == "preferences" and r.get("tier") in ("confirmed", "legacy", "typed")
|
|
948
|
+
and claims.norm(r["text"]) not in core and xray.claim(r["id"]) not in mute
|
|
949
|
+
and text_hash(r["id"]) not in later
|
|
950
|
+
and ((proofs >= PROMOTE_PROOFS and apps >= PROMOTE_APPS)
|
|
951
|
+
or served >= PROMOTE_SERVED)):
|
|
952
|
+
out.append({"page": r["page"], "id": r["id"], "text": r["text"], "proofs": proofs,
|
|
953
|
+
"apps": apps, "served": served})
|
|
954
|
+
out.sort(key=lambda x: (-x["proofs"], -x["served"], x["id"]))
|
|
955
|
+
return out[:1]
|
|
956
|
+
|
|
957
|
+
|
|
958
|
+
def stale(rows: list[dict], events: list[dict], today: str, known: dict | None = None
|
|
959
|
+
) -> list[dict]:
|
|
960
|
+
"""Live confirmed lines on the STALE_DAYS pages whose last confirm (a `(confirmed DAY)`
|
|
961
|
+
marker, the confirming change event, a yes reconfirm or, R13b, the line coming back
|
|
962
|
+
(`reinforced`'s last day, `known`: `known_texts`)) is older than the page's days, oldest
|
|
963
|
+
first; at most STALE_PER_MONTH minus this month's Review answers (clicked
|
|
964
|
+
reconfirms and retires; shortcut: an expired line retired in the Review counts too). D5:
|
|
965
|
+
near-identical lines are one card, its `ids` every member's (Still true or Retire covers
|
|
966
|
+
them all)."""
|
|
967
|
+
voided, said, answered = _voided(events), {}, 0
|
|
968
|
+
for e in events:
|
|
969
|
+
if e.get("id") in voided:
|
|
970
|
+
continue
|
|
971
|
+
pl, day = _payload(e), str(e.get("day") or "")
|
|
972
|
+
this_month = day[:7] == today[:7]
|
|
973
|
+
if e.get("kind") == "log" and pl.get("kind") == "reconfirm":
|
|
974
|
+
if pl.get("verdict") == "yes":
|
|
975
|
+
said[pl.get("claim")] = max(said.get(pl.get("claim"), ""), day)
|
|
976
|
+
answered += this_month and pl.get("confirm") == "clicked"
|
|
977
|
+
c = pl.get("change") if e.get("kind") == "change" else None
|
|
978
|
+
if isinstance(c, dict) and c.get("op") == "retire" and c.get("confirm") == "clicked":
|
|
979
|
+
answered += this_month
|
|
980
|
+
out, back = [], reinforced(events, known)
|
|
981
|
+
for r in rows:
|
|
982
|
+
days = STALE_DAYS.get(r["page"])
|
|
983
|
+
if days is None or r["tier"] not in ("confirmed", "legacy", "typed") or claims.expired(
|
|
984
|
+
r["text"], today):
|
|
985
|
+
continue
|
|
986
|
+
last = max([*_CONFIRMED.findall(r["text"]), said.get(r["id"], ""),
|
|
987
|
+
str(r["day"] or "") if r["tier"] == "confirmed" else "",
|
|
988
|
+
back.get(r["id"], {}).get("last", "")])
|
|
989
|
+
if last and last < (dt.date.fromisoformat(today) - dt.timedelta(days=days)).isoformat():
|
|
990
|
+
out.append({"page": r["page"], "id": r["id"], "text": _shown(r["text"]),
|
|
991
|
+
"since": last})
|
|
992
|
+
out.sort(key=lambda x: (x["since"], x["page"], x["id"]))
|
|
993
|
+
out = [{**{k: v for k, v in g.items() if k != "members"},
|
|
994
|
+
"ids": [m["id"] for m in g["members"]]} for g in collapse(out)]
|
|
995
|
+
return out[:max(0, STALE_PER_MONTH - answered)]
|
|
996
|
+
|
|
997
|
+
|
|
998
|
+
def live_rows(vault, events, today: str) -> list[dict]:
|
|
999
|
+
"""The tiered live claim rows the Review works on: none private, none past its until."""
|
|
1000
|
+
hidden = _private(vault)
|
|
1001
|
+
return [r for r in claims.tiers(vault, events, today=today) if r["page"] not in hidden]
|
|
1002
|
+
|
|
1003
|
+
|
|
1004
|
+
def _proposals(events) -> dict:
|
|
1005
|
+
"""{(page, text_hash): {sessions, producer}} of the unvoided `propose` changes that hold
|
|
1006
|
+
their line's hash; `producer` (RR-10) is the latest one's, `chats` when it names none."""
|
|
1007
|
+
events = list(events)
|
|
1008
|
+
voided, out = _voided(events), {}
|
|
1009
|
+
for e in events:
|
|
1010
|
+
c = _payload(e).get("change") if e.get("kind") == "change" else None
|
|
1011
|
+
if (isinstance(c, dict) and c.get("tool") == "propose" and isinstance(c.get("hash"), str)
|
|
1012
|
+
and e.get("id") not in voided):
|
|
1013
|
+
x = out.setdefault((c.get("id"), c["hash"]), {"sessions": set()})
|
|
1014
|
+
x["sessions"].add(e.get("session"))
|
|
1015
|
+
x["producer"] = c.get("producer") if c.get("producer") in PRODUCERS else "chats"
|
|
1016
|
+
return out
|
|
1017
|
+
|
|
1018
|
+
|
|
1019
|
+
def sightings(events) -> dict:
|
|
1020
|
+
"""R3-4: {(page, text_hash): sessions}: the chats (one session each) that proposed the
|
|
1021
|
+
same line."""
|
|
1022
|
+
return {k: v["sessions"] for k, v in _proposals(events).items()}
|
|
1023
|
+
|
|
1024
|
+
|
|
1025
|
+
def producer_of(proposals: dict, page: str, text: str) -> str:
|
|
1026
|
+
"""RR-10: which producer proposed a waiting line (`_proposals`); an old line: `chats`."""
|
|
1027
|
+
return proposals.get((page, text_hash(text)), {}).get("producer", "chats")
|
|
1028
|
+
|
|
1029
|
+
|
|
1030
|
+
def ledger(events) -> dict:
|
|
1031
|
+
"""RR-10: {producer: {accept, reject, paused}} over the Review clicks on each producer's
|
|
1032
|
+
cards since its latest `resume` change: a click's changes carry the `producer` the app
|
|
1033
|
+
stamped (one verdict per click, its session); before that stamp, a commit decision's
|
|
1034
|
+
`decide` and a `dismiss` of corrections, decisions or forget still count. A producer whose
|
|
1035
|
+
rejects exceed its accepts over PAUSE_AFTER or more decided cards is `paused`."""
|
|
1036
|
+
events = list(events)
|
|
1037
|
+
voided, said = _voided(events), {p: {} for p in PRODUCERS}
|
|
1038
|
+
for e in events:
|
|
1039
|
+
c = _payload(e).get("change") if e.get("kind") == "change" else None
|
|
1040
|
+
if not isinstance(c, dict) or e.get("id") in voided or c.get("confirm") != "clicked":
|
|
1041
|
+
continue
|
|
1042
|
+
if c.get("tool") == "resume":
|
|
1043
|
+
if c.get("producer") in PRODUCERS:
|
|
1044
|
+
said[c["producer"]] = {} # counting starts again
|
|
1045
|
+
continue
|
|
1046
|
+
p = c.get("producer")
|
|
1047
|
+
if p not in PRODUCERS: # a click from before the stamp
|
|
1048
|
+
p = ("decisions" if c.get("tool") == "decide" else c.get("id")
|
|
1049
|
+
if c.get("tool") == "dismiss" and c.get("id") in LEGACY_DISMISS else None)
|
|
1050
|
+
if p is None:
|
|
1051
|
+
continue
|
|
1052
|
+
no = c.get("tool") == "dismiss" or c.get("op") == "reject"
|
|
1053
|
+
said[p][e.get("session") or e.get("id")] = "reject" if no else "accept"
|
|
1054
|
+
out = {}
|
|
1055
|
+
for p, votes in said.items():
|
|
1056
|
+
n = {v: list(votes.values()).count(v) for v in ("accept", "reject")}
|
|
1057
|
+
out[p] = {**n, "paused": n["accept"] + n["reject"] >= PAUSE_AFTER
|
|
1058
|
+
and n["reject"] > n["accept"]}
|
|
1059
|
+
return out
|
|
1060
|
+
|
|
1061
|
+
|
|
1062
|
+
def answered_today(events, today: str) -> int:
|
|
1063
|
+
"""R3-4: the Today's 5 kinds of card (TODAY_CARDS) the user answered on `today`: one per
|
|
1064
|
+
app click, each its own session stamped with the card's kind (app/server.py `_click`)."""
|
|
1065
|
+
voided, said = _voided(events), set()
|
|
1066
|
+
for e in events:
|
|
1067
|
+
c = _payload(e).get("change") if e.get("kind") == "change" else None
|
|
1068
|
+
if (isinstance(c, dict) and c.get("card") in TODAY_CARDS and e.get("day") == today
|
|
1069
|
+
and e.get("id") not in voided and not c.get("auto")): # D1/D2: not a click
|
|
1070
|
+
said.add(e.get("session"))
|
|
1071
|
+
return len(said)
|
|
1072
|
+
|
|
1073
|
+
|
|
1074
|
+
def view(vault, events, today: str) -> dict:
|
|
1075
|
+
"""The Review view: every text is shown text (`_shown`). D4: the badge `count` is the
|
|
1076
|
+
Today's 5 cards still unanswered; `more` counts every board's cards. R3-4: a
|
|
1077
|
+
single inference (a waiting line other than a teaching rule that fewer than SIGHTINGS
|
|
1078
|
+
chats proposed) leaves the view SINGLE_DAYS after its stamp (inbox.md keeps it), and
|
|
1079
|
+
`today` orders at most TODAY_MAX cards a day (`_today`). RR-10: a `paused` producer's
|
|
1080
|
+
cards (`ledger`) are not offered; `paused` lists them for the Status line. G5b-4: a claim
|
|
1081
|
+
line on a card that chats said again carries `said` {times, last} (`reinforced`)."""
|
|
1082
|
+
events = list(events)
|
|
1083
|
+
led = ledger(events)
|
|
1084
|
+
off = {p for p, x in led.items() if x["paused"]}
|
|
1085
|
+
hidden = _private(vault)
|
|
1086
|
+
rows = [r for r in claims.tiers(vault, events) if r["page"] not in hidden] # writes nothing
|
|
1087
|
+
expired = [{"page": r["page"], "id": r["id"], "text": _shown(r["text"]), "until": until}
|
|
1088
|
+
for r in rows if (until := claims.expired(r["text"], today))]
|
|
1089
|
+
seen, cut = _proposals(events), (dt.date.fromisoformat(today)
|
|
1090
|
+
- dt.timedelta(days=SINGLE_DAYS)).isoformat()
|
|
1091
|
+
|
|
1092
|
+
def single(p: dict) -> bool:
|
|
1093
|
+
return p["page"] != "teaching-contract" and len(
|
|
1094
|
+
seen.get((p["page"], text_hash(p["text"])), {}).get("sessions", ())) < SIGHTINGS
|
|
1095
|
+
|
|
1096
|
+
waiting = [{**p, "section": plain(p["section"], 80), "text": _shown(p["text"]),
|
|
1097
|
+
"single": single(p)}
|
|
1098
|
+
for p in pending(vault, today) if not (single(p) and (p["since"] or "~") < cut)
|
|
1099
|
+
and producer_of(seen, p["page"], p["text"]) not in off]
|
|
1100
|
+
waiting = [{**{k: v for k, v in g.items() if k != "members"},
|
|
1101
|
+
"keys": [m["key"] for m in g["members"]]} # D5: one card per near-copy group
|
|
1102
|
+
for page in dict.fromkeys(p["page"] for p in waiting)
|
|
1103
|
+
for g in collapse([p for p in waiting if p["page"] == page])]
|
|
1104
|
+
known = known_texts(vault)
|
|
1105
|
+
back = reinforced(events, known)
|
|
1106
|
+
|
|
1107
|
+
def said(cid: str) -> dict: # G5b-4: how often chats said the line, a fold (`reinforced`)
|
|
1108
|
+
x = back.get(cid)
|
|
1109
|
+
return {"said": {"times": len(x["sessions"]), "last": x["last"]}} if x else {}
|
|
1110
|
+
|
|
1111
|
+
old = [{**x, **said(x["id"])} for x in stale(rows, events, today, known)]
|
|
1112
|
+
|
|
1113
|
+
def side(r: dict) -> dict:
|
|
1114
|
+
return {"page": r["page"], "id": r["id"], "text": _shown(r["text"]), **said(r["id"])}
|
|
1115
|
+
|
|
1116
|
+
current = [r for r in rows if not claims.expired(r["text"], today)] # = live_rows
|
|
1117
|
+
pairs = [{"key": c["key"], "why": c["why"], "left": side(c["left"]),
|
|
1118
|
+
"right": side(c["right"])} for c in conflicts(current, events, known)]
|
|
1119
|
+
from keepfold import corrections, more_sources # read imported pages: only the Review asks
|
|
1120
|
+
rules = [{"key": x["key"], "text": _shown(x["text"]), "chats": x["chats"],
|
|
1121
|
+
"page": x["page"]}
|
|
1122
|
+
for x in ([] if "corrections" in off else corrections.proposals(vault, events,
|
|
1123
|
+
current))]
|
|
1124
|
+
decisions = [{**x, "project": plain(x["project"], 80), "subject": plain(x["subject"], SHOWN)}
|
|
1125
|
+
for x in ([] if "decisions" in off
|
|
1126
|
+
else more_sources.decision_proposals(vault, events))]
|
|
1127
|
+
from keepfold import tags # it imports this module
|
|
1128
|
+
forget = [{"key": g["key"], "keys": [m["key"] for m in g["members"]],
|
|
1129
|
+
"text": plain(g["text"], SHOWN),
|
|
1130
|
+
"candidates": list({c["id"]: side(c) for m in g["members"]
|
|
1131
|
+
for c in m["candidates"]}.values())}
|
|
1132
|
+
for g in collapse([] if "forget" in off else tags.forget_cards(vault, events,
|
|
1133
|
+
today))]
|
|
1134
|
+
from keepfold import sources
|
|
1135
|
+
imports = [{**x, "title": plain(x["title"], SHOWN)}
|
|
1136
|
+
for x in sources.edited_pages(vault, events)]
|
|
1137
|
+
unsafe = [{"key": g["key"], "page": g["page"], "id": g["id"], "what": g["what"],
|
|
1138
|
+
"keys": [m["key"] for m in g["members"]], "ids": [m["id"] for m in g["members"]],
|
|
1139
|
+
"invisible": claims.invisible(g["what"]), "command": bool(g.get("command")),
|
|
1140
|
+
"text": _shown("".join(c for c in g["text"] if c.isprintable()))}
|
|
1141
|
+
for g in collapse([x for x in unsafe_lines(vault, events)
|
|
1142
|
+
if x["page"] not in hidden])]
|
|
1143
|
+
outside = [{"key": x["key"], "page": x["page"], "section": plain(x["section"] or "", 80),
|
|
1144
|
+
"id": x["id"], "text": _shown("".join(
|
|
1145
|
+
c for c in claims.strip_id(x["line"]).removeprefix("- ") if c.isprintable()))}
|
|
1146
|
+
for x in outside_lines(vault, events) if x["page"] not in hidden]
|
|
1147
|
+
spare = _spare_left(events, today) # G7: crowded first, then unused, within the month's cap
|
|
1148
|
+
lines, window = crowded(vault, current) if spare else ([], 0)
|
|
1149
|
+
crowd = [{**side(x), "cut": x["cut"], "seen": x["seen"], "window": window}
|
|
1150
|
+
for x in lines[:spare]]
|
|
1151
|
+
books, calls, since = unused(vault, events, today) if spare > len(crowd) else ([], 0, None)
|
|
1152
|
+
books = [{**x, "calls": calls, "since": since} for x in books[:spare - len(crowd)]]
|
|
1153
|
+
pin = [{**side(x), "proofs": x["proofs"], "apps": x["apps"], "served": x["served"]}
|
|
1154
|
+
for x in promote(vault, current, events, today)] # R28a: one a month at most
|
|
1155
|
+
left = max(0, TODAY_MAX - answered_today(events, today))
|
|
1156
|
+
first = ([{"type": "unsafe", "key": x["key"]} for x in unsafe] # G6: always asked, first
|
|
1157
|
+
+ [{"type": OUTSIDE, "key": x["key"]} for x in outside]) # R5a: likewise
|
|
1158
|
+
today_ = first + _today(waiting, pairs, rules)[:max(0, left - len(first))]
|
|
1159
|
+
return {"pending": waiting, "expired": expired, "stale": old, "conflicts": pairs,
|
|
1160
|
+
"rules": rules, "decisions": decisions, "forget": forget, "imports": imports,
|
|
1161
|
+
"unsafe": unsafe, OUTSIDE: outside, "crowded": crowd, "unused": books, "promote": pin,
|
|
1162
|
+
"today": today_, "today_left": left,
|
|
1163
|
+
"paused": [{"producer": p, "label": PRODUCERS[p], **led[p]} for p in sorted(off)],
|
|
1164
|
+
"count": len(today_), # D4: the badge counts only Today's 5 still unanswered
|
|
1165
|
+
"more": len(waiting) + len(expired) + len(old) + len(pairs) + len(rules)
|
|
1166
|
+
+ len(decisions) + len(forget) + len(imports) + len(unsafe) + len(outside)
|
|
1167
|
+
+ len(crowd)
|
|
1168
|
+
+ len(books) + len(pin)}
|
|
1169
|
+
|
|
1170
|
+
|
|
1171
|
+
def _today(waiting: list[dict], pairs: list[dict], rules: list[dict]) -> list[dict]:
|
|
1172
|
+
"""R3-4's order, as {type, key} of cards in the boards (after G6's unsafe lines, which
|
|
1173
|
+
`view` puts first): teaching-rule proposals, then contradiction pairs, repeated
|
|
1174
|
+
corrections, and last the other waiting lines that 2+ chats proposed (a single inference
|
|
1175
|
+
never)."""
|
|
1176
|
+
rule = [p for p in waiting if p["page"] == "teaching-contract"]
|
|
1177
|
+
return ([{"type": "pending", "key": p["key"]} for p in rule]
|
|
1178
|
+
+ [{"type": "conflict", "key": c["key"]} for c in pairs]
|
|
1179
|
+
+ [{"type": "rule", "key": x["key"]} for x in rules]
|
|
1180
|
+
+ [{"type": "pending", "key": p["key"]} for p in waiting
|
|
1181
|
+
if p not in rule and not p["single"]])
|