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/clients.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Claude desktop (Chat) config files: where they live per OS, and the `keepfold` MCP server
|
|
2
|
+
entry. Used by `keepfold setup`, `keepfold doctor` and the app; `app.targets` writes the files."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
CONFIG = "claude_desktop_config.json"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def claude_desktop_config_paths(platform: str | None = None) -> list[Path]:
|
|
15
|
+
"""Candidate config files, in probe order, for each Claude folder that exists.
|
|
16
|
+
|
|
17
|
+
Windows has three layouts (per-profile Claude-Data, classic, the Store/MSIX virtualised
|
|
18
|
+
folder); callers see them all. The Store app reads its Claude-Data profile (`claude_<id>`,
|
|
19
|
+
with or without a config yet), so that comes first: a first setup with no config file
|
|
20
|
+
anywhere writes there, not to the classic folder the Store app left behind."""
|
|
21
|
+
platform = platform or sys.platform
|
|
22
|
+
out: list[Path] = []
|
|
23
|
+
if platform == "win32":
|
|
24
|
+
local = os.environ.get("LOCALAPPDATA")
|
|
25
|
+
if local:
|
|
26
|
+
out += sorted(d / CONFIG for d in Path(local, "Claude-Data").glob("*/")
|
|
27
|
+
if (d / CONFIG).is_file() or d.name.lower().startswith("claude_"))
|
|
28
|
+
if roaming := os.environ.get("APPDATA"):
|
|
29
|
+
out.append(Path(roaming, "Claude", CONFIG))
|
|
30
|
+
if local:
|
|
31
|
+
out += sorted(p / CONFIG for p in Path(local, "Packages").glob(
|
|
32
|
+
"Claude_*/LocalCache/Roaming/Claude"))
|
|
33
|
+
elif platform == "darwin":
|
|
34
|
+
out.append(Path.home() / "Library" / "Application Support" / "Claude" / CONFIG)
|
|
35
|
+
else:
|
|
36
|
+
base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
|
|
37
|
+
out.append(Path(base, "Claude", CONFIG))
|
|
38
|
+
return [p for p in out if p.parent.is_dir()]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def setup_targets(paths: list[Path]) -> list[Path]:
|
|
42
|
+
"""Which candidates setup writes: every config file that already exists, else the first
|
|
43
|
+
candidate folder only, so no stray configs appear in folders the app does not read."""
|
|
44
|
+
return [p for p in paths if p.is_file()] or paths[:1]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def keepfold_command() -> str:
|
|
48
|
+
"""Absolute path of the `keepfold` executable: Claude desktop may not share the shell PATH."""
|
|
49
|
+
found = shutil.which("keepfold")
|
|
50
|
+
return str(Path(found or sys.argv[0]).resolve())
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
UNINSTALL_KEY = r"Software\Microsoft\Windows\CurrentVersion\Uninstall\Keepfold" # the installer's
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _registry_install() -> Path | None: # tests replace this: never the real registry
|
|
57
|
+
"""The install folder Apps & Features names (installer/setup_app.py), else None."""
|
|
58
|
+
try:
|
|
59
|
+
import winreg
|
|
60
|
+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, UNINSTALL_KEY) as k:
|
|
61
|
+
return Path(winreg.QueryValueEx(k, "InstallLocation")[0])
|
|
62
|
+
except (ImportError, OSError):
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def installed_keepfold() -> Path | None:
|
|
67
|
+
"""`bin\\keepfold.exe` of the KeepfoldSetup.exe install (the folder this Python runs from, else
|
|
68
|
+
the one Apps & Features names, else the installer's default folder), else None."""
|
|
69
|
+
from keepfold import update
|
|
70
|
+
local = os.environ.get("LOCALAPPDATA")
|
|
71
|
+
for d in (update.install_dir(), _registry_install(),
|
|
72
|
+
Path(local, "Programs", "Keepfold") if local else None):
|
|
73
|
+
if d and (d / update.MARKER).is_file() and (d / "bin" / "keepfold.exe").is_file():
|
|
74
|
+
return d / "bin" / "keepfold.exe"
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def mcp_command() -> str:
|
|
79
|
+
"""The `command` of the `keepfold` MCP entry: the installed Keepfold when there is one, so AI
|
|
80
|
+
apps run the version the installer updates (not a separate `uv tool` copy); else
|
|
81
|
+
`keepfold_command()`."""
|
|
82
|
+
exe = installed_keepfold()
|
|
83
|
+
return str(exe) if exe else keepfold_command()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def other_copy(entry) -> bool:
|
|
87
|
+
"""`entry` (a `keepfold` MCP entry) runs another keepfold executable while an installed Keepfold
|
|
88
|
+
exists."""
|
|
89
|
+
exe = installed_keepfold()
|
|
90
|
+
cmd = entry.get("command") if isinstance(entry, dict) else None
|
|
91
|
+
return bool(exe and isinstance(cmd, str) and cmd and Path(cmd).resolve() != exe.resolve())
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def server_entry(command: str, vault: Path) -> dict:
|
|
95
|
+
return {"command": command, "args": ["mcp", "--vault", str(vault)]}
|
|
96
|
+
|
keepfold/cloudllm.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Opt-in cloud processing of cloud-audience browsing (docs/design/data-access.md §2-3).
|
|
2
|
+
|
|
3
|
+
`find` builds a localllm.Runner (kind openai) for an HTTPS OpenAI-compatible endpoint from
|
|
4
|
+
`cloudllm: {provider, model, base_url?, api_key_env, max_items}` in ~/.keepfold/config.yaml. The
|
|
5
|
+
key comes only from the environment variable named by `api_key_env`; it is never stored, logged
|
|
6
|
+
or shown. Requests go only over https to the configured base, with no proxy and no redirect.
|
|
7
|
+
Before each call the prompt is checked with vault.secret_pattern and the call is skipped on a
|
|
8
|
+
match; at most `max_items` calls (default 500) per run. `audit` appends one counts-only line per
|
|
9
|
+
run to `<vault>/.keepfold/cloud-log.jsonl`. Who may reach this runner is decided only by
|
|
10
|
+
`browse_serve.runner_for`; localllm keeps its loopback-only guarantee.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import logging
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import urllib.request
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from datetime import UTC, datetime
|
|
21
|
+
from urllib.parse import urlsplit
|
|
22
|
+
|
|
23
|
+
from keepfold import localllm
|
|
24
|
+
from keepfold.vault import Vault, secret_pattern
|
|
25
|
+
|
|
26
|
+
log = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
# OpenAI-compatible bases; `chat_path` is appended (checked 18 Nov 2026 in each provider's docs)
|
|
29
|
+
PRESETS = {
|
|
30
|
+
"openai": "https://api.openai.com/v1",
|
|
31
|
+
"openrouter": "https://openrouter.ai/api/v1",
|
|
32
|
+
"gemini": "https://generativelanguage.googleapis.com/v1beta/openai",
|
|
33
|
+
"anthropic": "https://api.anthropic.com/v1",
|
|
34
|
+
}
|
|
35
|
+
MAX_ITEMS = 500
|
|
36
|
+
LOG = ".keepfold/cloud-log.jsonl"
|
|
37
|
+
_REFUSED = "cloudllm: only https to the configured host is allowed"
|
|
38
|
+
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}), localllm._NoRedirect())
|
|
39
|
+
# r1 S10: the name of a secret, so PATH, HOME or USERPROFILE are never sent as a bearer token
|
|
40
|
+
_ENV_NAME = re.compile(r"[A-Z][A-Z0-9_]{1,63}")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def check_env_name(name) -> str:
|
|
44
|
+
"""Return `name` when it can name an API key variable (capitals, ending in _KEY, _TOKEN or
|
|
45
|
+
_API_KEY); raise ValueError otherwise."""
|
|
46
|
+
if not (isinstance(name, str) and _ENV_NAME.fullmatch(name)
|
|
47
|
+
and name.endswith(("_KEY", "_TOKEN"))):
|
|
48
|
+
raise ValueError("api_key_env is the NAME of the variable that holds your key: capitals, "
|
|
49
|
+
"ending in _KEY, _TOKEN or _API_KEY, such as OPENAI_API_KEY. Never "
|
|
50
|
+
"paste the key itself here.")
|
|
51
|
+
return name
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _check(url) -> str:
|
|
55
|
+
"""Return url when it is a plain https URL with a host; raise ValueError otherwise."""
|
|
56
|
+
if not isinstance(url, str) or any(c in url for c in "\\ \t\r\n\x00@"):
|
|
57
|
+
raise ValueError(_REFUSED)
|
|
58
|
+
try:
|
|
59
|
+
parts = urlsplit(url)
|
|
60
|
+
parts.port # noqa: B018 (raises on a junk port)
|
|
61
|
+
except ValueError:
|
|
62
|
+
raise ValueError(_REFUSED) from None
|
|
63
|
+
if parts.scheme != "https" or not parts.hostname:
|
|
64
|
+
raise ValueError(_REFUSED)
|
|
65
|
+
return url
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass
|
|
69
|
+
class CloudRunner(localllm.Runner):
|
|
70
|
+
provider: str = "custom"
|
|
71
|
+
key: str = field(default="", repr=False)
|
|
72
|
+
max_items: int = MAX_ITEMS
|
|
73
|
+
items: int = 0 # requests sent this run (a retry counts again)
|
|
74
|
+
chars: int = 0
|
|
75
|
+
skipped: int = 0 # calls refused for a secret
|
|
76
|
+
chat_path = "/chat/completions"
|
|
77
|
+
|
|
78
|
+
def _chat(self, system: str, user: str, **kw) -> str | None:
|
|
79
|
+
if self.items >= self.max_items:
|
|
80
|
+
return None
|
|
81
|
+
if secret_pattern(system) or secret_pattern(user):
|
|
82
|
+
self.skipped += 1
|
|
83
|
+
return None
|
|
84
|
+
self.items += 1
|
|
85
|
+
self.chars += len(system) + len(user)
|
|
86
|
+
return super()._chat(system, user, **kw)
|
|
87
|
+
|
|
88
|
+
def _post(self, url: str, body: dict, timeout: float) -> dict:
|
|
89
|
+
if not url.startswith(self.base + "/"):
|
|
90
|
+
raise ValueError(_REFUSED)
|
|
91
|
+
req = urllib.request.Request(_check(url), data=json.dumps(body).encode(), headers={
|
|
92
|
+
"Content-Type": "application/json", "Authorization": f"Bearer {self.key}"})
|
|
93
|
+
with _OPENER.open(req, timeout=timeout) as resp:
|
|
94
|
+
return json.loads(resp.read().decode("utf-8", "replace"))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def find(config: dict | None = None) -> CloudRunner | None:
|
|
98
|
+
"""The configured cloud runner, or None when `cloudllm` is missing or incomplete, its key
|
|
99
|
+
variable is unset, or the base is not https."""
|
|
100
|
+
if config is None:
|
|
101
|
+
from keepfold.taint import config as load_config
|
|
102
|
+
config = load_config()
|
|
103
|
+
c = config.get("cloudllm") if isinstance(config, dict) else None
|
|
104
|
+
if not isinstance(c, dict):
|
|
105
|
+
return None
|
|
106
|
+
provider = str(c.get("provider") or "custom").strip().lower()
|
|
107
|
+
base, model, env = c.get("base_url") or PRESETS.get(provider), c.get("model"), \
|
|
108
|
+
c.get("api_key_env")
|
|
109
|
+
try:
|
|
110
|
+
key = os.environ.get(check_env_name(env), "").strip()
|
|
111
|
+
except ValueError:
|
|
112
|
+
key = ""
|
|
113
|
+
if not (key and isinstance(model, str) and model.strip() and base):
|
|
114
|
+
return None
|
|
115
|
+
try:
|
|
116
|
+
_check(base)
|
|
117
|
+
except ValueError:
|
|
118
|
+
log.warning("cloudllm: base_url refused; it must be https")
|
|
119
|
+
return None
|
|
120
|
+
n = c.get("max_items")
|
|
121
|
+
n = n if isinstance(n, int) and not isinstance(n, bool) and n > 0 else MAX_ITEMS
|
|
122
|
+
return CloudRunner("openai", base.rstrip("/"), model.strip(), provider=provider, key=key,
|
|
123
|
+
max_items=n)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def audit(vault: Vault, runner: CloudRunner) -> None:
|
|
127
|
+
"""One counts-only line for this run: time, provider, model, requests, characters sent."""
|
|
128
|
+
line = json.dumps({"ts": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
129
|
+
"provider": runner.provider, "model": runner.model,
|
|
130
|
+
"items": runner.items, "chars": runner.chars,
|
|
131
|
+
"skipped": runner.skipped})
|
|
132
|
+
path = vault.root / LOG
|
|
133
|
+
with vault.lock():
|
|
134
|
+
old = path.read_text(encoding="utf-8") if path.is_file() else ""
|
|
135
|
+
vault.write_text(path, old + line + "\n")
|
keepfold/contract.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Teaching-contract helpers: scope `## Domain overrides` to the domains in play (wiki spec §2)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
MAX_CHARS = 4800 # ≈1,200 tokens; a 20-rule contract fits (tools.md)
|
|
8
|
+
_H = re.compile(r"^(#{2,3})\s+(.*?)\s*$")
|
|
9
|
+
_FENCE = re.compile(r"^\s*(```|~~~)")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def scope_contract(text: str, domains: set[str]) -> str:
|
|
13
|
+
"""The contract with only the `### <domain id>` overrides whose id is in `domains`.
|
|
14
|
+
|
|
15
|
+
No `## Domain overrides` section: returned unchanged. A section with no match is dropped.
|
|
16
|
+
"""
|
|
17
|
+
lines = text.splitlines(keepends=True)
|
|
18
|
+
out: list[str] = []
|
|
19
|
+
in_ov = keep = fenced = False
|
|
20
|
+
pre: list[str] = [] # the section heading and preamble, kept only if a subsection matches
|
|
21
|
+
emitted = False
|
|
22
|
+
want = {d.casefold() for d in domains}
|
|
23
|
+
for line in lines:
|
|
24
|
+
if _FENCE.match(line):
|
|
25
|
+
fenced = not fenced
|
|
26
|
+
m = None if fenced else _H.match(line)
|
|
27
|
+
if m and m.group(1) == "##":
|
|
28
|
+
in_ov = m.group(2).casefold() == "domain overrides"
|
|
29
|
+
keep, emitted = False, False
|
|
30
|
+
if in_ov:
|
|
31
|
+
pre = [line]
|
|
32
|
+
continue
|
|
33
|
+
elif in_ov and m: # a ### subsection
|
|
34
|
+
keep = m.group(2).casefold() in want
|
|
35
|
+
if keep and not emitted:
|
|
36
|
+
out += pre
|
|
37
|
+
emitted = True
|
|
38
|
+
elif in_ov and not keep and not emitted:
|
|
39
|
+
pre.append(line)
|
|
40
|
+
continue
|
|
41
|
+
if not in_ov or keep:
|
|
42
|
+
out.append(line)
|
|
43
|
+
return "".join(out)
|
keepfold/corrections.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Plan 5b (N2): repeated corrections. The user's own short corrective turns in imported AI
|
|
2
|
+
chats ("don't …", "stop …", "always …", "never …", "no, I said …", "please use …", and a soft
|
|
3
|
+
tier: "I prefer …", "from now on …", "too long", "not what I meant", "actually …"; at most
|
|
4
|
+
MAX_CHARS, not a question), grouped by `review.scorer`, and offered in the app's Review
|
|
5
|
+
("You told 3 chats: …"). An always/never/from-now-on line is a standing rule bound for me/core
|
|
6
|
+
(pinned to every chat), any other a me/preferences line. RR-25: a core line or a soft-tier
|
|
7
|
+
wording needs CORE_CHATS different chats, a preferences line MIN_CHATS.
|
|
8
|
+
|
|
9
|
+
Read-only over the vault; reads no model and sends nothing anywhere. The scan is cached in
|
|
10
|
+
CACHE (git-ignored, tool-private): per chat page its (mtime, size) and its correction lines, so
|
|
11
|
+
a rescan reads only the pages changed since. Private chats (`access.audience_of_note`: LOCAL)
|
|
12
|
+
are never scanned; their cache rows hold no text."""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import re
|
|
18
|
+
from collections import Counter
|
|
19
|
+
|
|
20
|
+
from keepfold import access, claims, harvest, review, topics
|
|
21
|
+
from keepfold.vault import VaultError
|
|
22
|
+
|
|
23
|
+
CACHE = ".keepfold/corrections.json"
|
|
24
|
+
VERSION = 2 # 2: the soft tier (RR-25)
|
|
25
|
+
MAX_CHARS = 200
|
|
26
|
+
MIN_CHATS, CORE_CHATS = 2, 3
|
|
27
|
+
SHOWN = 5
|
|
28
|
+
_START = re.compile(r"^(?:(?:no|nope|again)\b[\s,.!:;-]*)?(?:please\s+)?(?:don't|dont|do not|"
|
|
29
|
+
r"stop|always|never(?!\s+mind)|i (?:already )?said|i told you)\b"
|
|
30
|
+
r"|^please use\b", re.I)
|
|
31
|
+
_SOFT = re.compile(r"^(?:i(?:'d| would)? prefer|from now on|(?:(?:that's|that is|it's|this is|"
|
|
32
|
+
r"way|much) )?too long|(?:(?:that's|that is|this is) )?not what i meant|"
|
|
33
|
+
r"actually)\b", re.I)
|
|
34
|
+
_CORE = re.compile(r"^(?:(?:no|nope|again)\b[\s,.!:;-]*)?(?:please\s+)?(?:always|"
|
|
35
|
+
r"never(?!\s+mind)|from now on)\b", re.I)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def is_correction(turn: str) -> bool:
|
|
39
|
+
"""A short corrective turn: a `_START` or `_SOFT` opening, at most MAX_CHARS, not a
|
|
40
|
+
question."""
|
|
41
|
+
t = turn.replace("’", "'").strip()
|
|
42
|
+
return 0 < len(t) <= MAX_CHARS and not t.endswith("?") and bool(
|
|
43
|
+
_START.match(t) or _SOFT.match(t))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def bound(text: str) -> tuple[str, str, int]:
|
|
47
|
+
"""(me page, section, chats needed) for a correction line: a standing always/never rule
|
|
48
|
+
goes to me/core, read in every chat, so it needs CORE_CHATS; so does a soft wording, which
|
|
49
|
+
is more often not a correction at all; any other line is a preference."""
|
|
50
|
+
t = text.replace("’", "'").strip()
|
|
51
|
+
page, section = ("core", "Core") if _CORE.match(t) else ("preferences", "Personal")
|
|
52
|
+
return page, section, CORE_CHATS if page == "core" or _SOFT.match(t) else MIN_CHATS
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _lines(body: str) -> list[str]:
|
|
56
|
+
return [t for t in (" ".join(x.split()) for x in harvest.user_turns(body) or [])
|
|
57
|
+
if is_correction(t)]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def scan(vault) -> dict[str, list[str]]:
|
|
61
|
+
"""{chat page id: its correction lines} over the non-private imported chat pages; reads only
|
|
62
|
+
pages whose (mtime, size) changed since the cached scan, and rewrites CACHE only then."""
|
|
63
|
+
path = vault.root / CACHE
|
|
64
|
+
try:
|
|
65
|
+
old = json.loads(path.read_bytes().decode("utf-8"))
|
|
66
|
+
old = old["chats"] if old.get("version") == VERSION else {}
|
|
67
|
+
except (OSError, ValueError, AttributeError, KeyError):
|
|
68
|
+
old = {}
|
|
69
|
+
rows, dirty = {}, False
|
|
70
|
+
for p in vault.note_paths("resource"):
|
|
71
|
+
try:
|
|
72
|
+
st = p.stat()
|
|
73
|
+
except OSError:
|
|
74
|
+
continue
|
|
75
|
+
fp = [st.st_mtime_ns, st.st_size]
|
|
76
|
+
hit = old.get(p.stem)
|
|
77
|
+
if isinstance(hit, dict) and hit.get("fp") == fp and isinstance(hit.get("lines"), list):
|
|
78
|
+
rows[p.stem] = hit
|
|
79
|
+
continue
|
|
80
|
+
dirty = True
|
|
81
|
+
try:
|
|
82
|
+
n = vault.read_path(p)
|
|
83
|
+
except VaultError:
|
|
84
|
+
n = None
|
|
85
|
+
ok = (n is not None and bool(topics.page_source(n.body)) # semantic.is_chat, no numpy
|
|
86
|
+
and access.audience_of_note(n) is access.Audience.CLOUD)
|
|
87
|
+
rows[p.stem] = {"fp": fp, "lines": _lines(n.body) if ok else []}
|
|
88
|
+
if dirty or old.keys() - rows.keys():
|
|
89
|
+
vault.write_text(path, json.dumps({"version": VERSION, "chats": rows},
|
|
90
|
+
ensure_ascii=False))
|
|
91
|
+
return {k: v["lines"] for k, v in rows.items() if v["lines"]}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def proposals(vault, events, rows: list[dict]) -> list[dict]:
|
|
95
|
+
"""Up to SHOWN groups of similar correction lines from enough chats (`bound`), most chats
|
|
96
|
+
first, as {key (`review.text_hash`), text (raw: the most common wording, then the
|
|
97
|
+
shortest), chats, page, section}. Left out: a group the user dismissed (any member's
|
|
98
|
+
hash) and one already said by a live line of `rows`."""
|
|
99
|
+
items = [(cid, line) for cid, lines in sorted(scan(vault).items())
|
|
100
|
+
for line in dict.fromkeys(lines)]
|
|
101
|
+
if not items:
|
|
102
|
+
return []
|
|
103
|
+
voided = {e.get("ref") for e in events if e.get("kind") == "void"}
|
|
104
|
+
gone = {c.get("hash") for e in events if e.get("kind") == "change" and e.get("id") not in voided
|
|
105
|
+
and isinstance(c := review._payload(e).get("change"), dict)
|
|
106
|
+
and c.get("tool") == "dismiss" and c.get("id") == "corrections"}
|
|
107
|
+
live = [r["text"] for r in rows]
|
|
108
|
+
score, cut = review.scorer([line for _, line in items] + live)
|
|
109
|
+
groups: list[list[int]] = []
|
|
110
|
+
for i in range(len(items)): # greedy: the first group whose first line is close enough
|
|
111
|
+
g = next((g for g in groups if score(g[0], i) >= cut), None)
|
|
112
|
+
if g is None:
|
|
113
|
+
groups.append([i])
|
|
114
|
+
else:
|
|
115
|
+
g.append(i)
|
|
116
|
+
out = []
|
|
117
|
+
said_no = [i for i, (_, line) in enumerate(items) if review.text_hash(line) in gone]
|
|
118
|
+
for g in groups:
|
|
119
|
+
chats = {items[i][0] for i in g}
|
|
120
|
+
texts = [items[i][1] for i in g]
|
|
121
|
+
# D5: a Dismiss covers the group it was on and any later one saying it in other words
|
|
122
|
+
if len(chats) < MIN_CHATS or any(review.text_hash(t) in gone for t in texts) or any(
|
|
123
|
+
score(g[0], k) >= cut for k in said_no):
|
|
124
|
+
continue
|
|
125
|
+
if any(score(g[0], len(items) + k) >= cut for k in range(len(live))):
|
|
126
|
+
continue # already a live line about the user
|
|
127
|
+
said = Counter(claims.norm(t) for t in texts)
|
|
128
|
+
text = min(texts, key=lambda t: (-said[claims.norm(t)], len(t), t))
|
|
129
|
+
page, section, need = bound(text)
|
|
130
|
+
if len(chats) >= need:
|
|
131
|
+
out.append({"key": review.text_hash(text), "text": text, "chats": len(chats),
|
|
132
|
+
"page": page, "section": section})
|
|
133
|
+
out.sort(key=lambda x: (-x["chats"], x["text"]))
|
|
134
|
+
return out[:SHOWN]
|