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/migrate.py
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
"""The first-run move from Cortex (0.6.1 and older) to Keepfold (docs/INSTALL.md "Coming from
|
|
2
|
+
Cortex"; docs/design/v11/RENAME-PLAN.md R3):
|
|
3
|
+
|
|
4
|
+
- home: ~/.cortex becomes ~/.keepfold, one same-volume os.replace of the folder, only while
|
|
5
|
+
~/.keepfold is missing (never merged, never deleted);
|
|
6
|
+
- vault: <vault>/.cortex/ becomes .keepfold/ the same way, then its ignore lines, the notes'
|
|
7
|
+
`cortex_status`/`cortex_next` keys, the Obsidian views that name them, old-named files in
|
|
8
|
+
.keepfold/ and the vault's git identity follow, with a git commit before and after.
|
|
9
|
+
|
|
10
|
+
States: `nothing` (no old folder), `done`, `both` (both folders exist: the new one is used and
|
|
11
|
+
the old one left as it was), `blocked` (an old Cortex still holds files: nothing changed) and
|
|
12
|
+
`error`. A vault move is resumable: `.cortex/migrating` is written before the folder moves (it
|
|
13
|
+
moves along) and `.keepfold/migrated` (the version) replaces it once every step is done, so a
|
|
14
|
+
crash midway finishes on the next open.
|
|
15
|
+
|
|
16
|
+
When it runs: `at_start` (the `keepfold` console entry, before anything reads the home),
|
|
17
|
+
`launch` (the app and the receiver), `on_open` (every Vault(): its first construction per root
|
|
18
|
+
and process), and the `keepfold migrate` command (`everything`). The automatic runs cost one
|
|
19
|
+
stat (the home) and two (a vault) when nothing is left to move, and never run from a source
|
|
20
|
+
checkout: there `keepfold migrate` does it by hand.
|
|
21
|
+
|
|
22
|
+
Old names stay only here, in events.py's read-side renames and in `keepfold undo`'s commit
|
|
23
|
+
search."""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import os
|
|
28
|
+
import sys
|
|
29
|
+
import threading
|
|
30
|
+
import time
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
OLD, NEW = ".cortex", ".keepfold"
|
|
34
|
+
MARKER = "migrated" # in the new folder: the version that finished the move
|
|
35
|
+
DOING = "migrating" # written in the old vault folder before it moves: the move is unfinished
|
|
36
|
+
CLOSE = "Close Cortex and the AI apps using it, then open Keepfold again."
|
|
37
|
+
TRIES = 6 # os.replace attempts on PermissionError (OneDrive, antivirus): ~3 s in all
|
|
38
|
+
BACKOFF = 0.1 # seconds, doubled per attempt; tests set 0
|
|
39
|
+
PEER_WAIT = 10.0 # seconds to wait for another Keepfold process that is moving the vault now
|
|
40
|
+
KEYS = {"cortex_status": "keepfold_status", "cortex_next": "keepfold_next"}
|
|
41
|
+
OLD_IDENTITY, NEW_IDENTITY = ("Cortex", "cortex@localhost"), ("Keepfold", "keepfold@localhost")
|
|
42
|
+
RANK = ("nothing", "done", "both", "blocked", "error") # overall state: the worst one
|
|
43
|
+
|
|
44
|
+
_SEEN: set[str] = set() # vault roots checked in this process (on_open's fast path)
|
|
45
|
+
_MU = threading.RLock() # one move at a time in this process
|
|
46
|
+
_IN = threading.local() # .roots: the vaults this thread is moving (our own Vault() skips them)
|
|
47
|
+
_dev: bool | None = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def source_checkout() -> bool:
|
|
51
|
+
"""Run from a source checkout (an editable dev install: pyproject.toml beside src/keepfold):
|
|
52
|
+
nothing moves by itself there, so dev runs never touch a real ~/.cortex."""
|
|
53
|
+
global _dev
|
|
54
|
+
if _dev is None:
|
|
55
|
+
here = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
56
|
+
_dev = os.path.isfile(os.path.join(here, "pyproject.toml"))
|
|
57
|
+
return _dev
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _version() -> str:
|
|
61
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
62
|
+
try:
|
|
63
|
+
return version("keepfold")
|
|
64
|
+
except PackageNotFoundError:
|
|
65
|
+
return "unknown"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _fresh(lock: Path) -> bool:
|
|
69
|
+
"""`lock` was written in the last LOCK_STALE_S: its process is active."""
|
|
70
|
+
from keepfold.vault import LOCK_STALE_S
|
|
71
|
+
try:
|
|
72
|
+
return time.time() - lock.stat().st_mtime < LOCK_STALE_S
|
|
73
|
+
except OSError:
|
|
74
|
+
return False
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _replace(old: Path, new: Path) -> str:
|
|
78
|
+
"""os.replace(old, new), retried with backoff on PermissionError: "moved", "peer" (another
|
|
79
|
+
Keepfold process moved it first) or "blocked" (a file in it stays open)."""
|
|
80
|
+
for attempt in range(TRIES):
|
|
81
|
+
try:
|
|
82
|
+
os.replace(old, new)
|
|
83
|
+
return "moved"
|
|
84
|
+
except PermissionError:
|
|
85
|
+
pass
|
|
86
|
+
except OSError:
|
|
87
|
+
if new.exists() and not old.exists():
|
|
88
|
+
return "peer"
|
|
89
|
+
raise
|
|
90
|
+
if new.exists() and not old.exists():
|
|
91
|
+
return "peer"
|
|
92
|
+
if attempt < TRIES - 1:
|
|
93
|
+
time.sleep(BACKOFF * 2 ** attempt)
|
|
94
|
+
return "blocked"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _blocked(what: Path) -> dict:
|
|
98
|
+
return {"state": "blocked", "message": f"{what} is in use by an old Cortex. {CLOSE}"}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _both(old: Path, new: Path) -> dict:
|
|
102
|
+
return {"state": "both", "old": str(old), "new": str(new),
|
|
103
|
+
"message": f"Both {old} and {new} exist. Keepfold uses {new} and left {old} as it "
|
|
104
|
+
f"was (nothing is merged). If {old} holds what you want, close Keepfold, "
|
|
105
|
+
f"rename {new}, then open Keepfold again."}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# ---- home ---------------------------------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _old_app(old: Path) -> bool:
|
|
112
|
+
"""The old Cortex app runs: its ~/.cortex/app.json names a port that answers its token."""
|
|
113
|
+
import http.client
|
|
114
|
+
import json
|
|
115
|
+
try:
|
|
116
|
+
s = json.loads((old / "app.json").read_text(encoding="utf-8"))
|
|
117
|
+
port, token = int(s["port"]), str(s["token"])
|
|
118
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
119
|
+
return False
|
|
120
|
+
c = http.client.HTTPConnection("127.0.0.1", port, timeout=2)
|
|
121
|
+
try:
|
|
122
|
+
c.request("GET", "/api/job", headers={"Host": f"127.0.0.1:{port}",
|
|
123
|
+
"X-Cortex-Token": token})
|
|
124
|
+
return c.getresponse().status == 200
|
|
125
|
+
except OSError:
|
|
126
|
+
return False
|
|
127
|
+
finally:
|
|
128
|
+
c.close()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def home() -> dict:
|
|
132
|
+
"""Move ~/.cortex to ~/.keepfold when only the old one exists. No file inside the old home
|
|
133
|
+
has an old name the code looks up (logs, models, tmp, app.json, config.yaml), so none is
|
|
134
|
+
renamed."""
|
|
135
|
+
h = Path.home()
|
|
136
|
+
old, new = h / OLD, h / NEW
|
|
137
|
+
out = {"old": str(old), "new": str(new)}
|
|
138
|
+
if not old.is_dir():
|
|
139
|
+
return {**out, "state": "done" if (new / MARKER).is_file() else "nothing"}
|
|
140
|
+
if new.exists():
|
|
141
|
+
return {**out, **_both(old, new)}
|
|
142
|
+
# on Windows an open file (the old app's log) also fails the move; this catches the rest
|
|
143
|
+
if _fresh(old / "config.lock") or _old_app(old):
|
|
144
|
+
return {**out, **_blocked(old)}
|
|
145
|
+
got = _replace(old, new)
|
|
146
|
+
if got == "blocked":
|
|
147
|
+
return {**out, **_blocked(old)}
|
|
148
|
+
if got == "moved":
|
|
149
|
+
try:
|
|
150
|
+
(new / MARKER).write_text(_version() + "\n", encoding="utf-8")
|
|
151
|
+
except OSError:
|
|
152
|
+
pass # only doctor's "done" reads it
|
|
153
|
+
return {**out, "state": "done"}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
# ---- vault --------------------------------------------------------------------------------
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _take_old(v, lock: Path, wait: float) -> str | None:
|
|
160
|
+
"""The old folder's lock as 0.6.1 takes it (O_EXCL, "pid ts host"), so no Cortex or other
|
|
161
|
+
Keepfold process writes there meanwhile. Unlike Vault._take it never creates the folder (a
|
|
162
|
+
peer may have just moved it). None: the folder is gone, or the lock is still held after
|
|
163
|
+
`wait`."""
|
|
164
|
+
import socket
|
|
165
|
+
deadline = time.monotonic() + wait
|
|
166
|
+
while True:
|
|
167
|
+
token = f"{os.getpid()} {time.time():.3f} {socket.gethostname()}"
|
|
168
|
+
try:
|
|
169
|
+
fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
|
170
|
+
except FileNotFoundError:
|
|
171
|
+
return None
|
|
172
|
+
except (FileExistsError, PermissionError):
|
|
173
|
+
if v._steal_if_stale(lock):
|
|
174
|
+
continue
|
|
175
|
+
if time.monotonic() >= deadline:
|
|
176
|
+
return None
|
|
177
|
+
time.sleep(0.05)
|
|
178
|
+
continue
|
|
179
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
180
|
+
f.write(token)
|
|
181
|
+
return token
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _old_busy(old: Path) -> bool:
|
|
185
|
+
"""A Cortex process is active in the vault's old folder: one of its locks is fresh. While a
|
|
186
|
+
Keepfold process moves it (DOING), its lock is waited for instead (_take_old)."""
|
|
187
|
+
if (old / DOING).exists():
|
|
188
|
+
return False
|
|
189
|
+
return any(_fresh(p) for p in (old / "lock", *old.glob("*.lock"), old / "browse" / "lock"))
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _ignore_text(text: str, final: bool) -> str:
|
|
193
|
+
"""Ignore rules with a `.keepfold` line after each `.cortex` one. `final` (the old folder is
|
|
194
|
+
gone): the `.cortex` lines become the `.keepfold` ones, plus one `.cortex/` line, so a copy
|
|
195
|
+
a stray old process makes again is never committable either."""
|
|
196
|
+
nl = "\r\n" if "\r\n" in text else "\n"
|
|
197
|
+
lines, out = text.splitlines(), []
|
|
198
|
+
for line in lines:
|
|
199
|
+
if OLD not in line:
|
|
200
|
+
out.append(line)
|
|
201
|
+
continue
|
|
202
|
+
if not final:
|
|
203
|
+
out.append(line)
|
|
204
|
+
new = line.replace(OLD, NEW)
|
|
205
|
+
if new not in lines and new not in out:
|
|
206
|
+
out.append(new)
|
|
207
|
+
if final and f"{OLD}/" not in out:
|
|
208
|
+
out.append(f"{OLD}/")
|
|
209
|
+
return nl.join(out) + nl if out else text
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _ignore(v, final: bool) -> None:
|
|
213
|
+
""".gitignore (and .git/info/exclude, if it has them): `.keepfold` lines for `.cortex` ones.
|
|
214
|
+
Called with the old lock held, before the folder moves, so .keepfold/ is ignored from its
|
|
215
|
+
first moment (private browsing data never becomes committable); again at the end."""
|
|
216
|
+
for p in (v.root / ".gitignore", v.root / ".git" / "info" / "exclude"):
|
|
217
|
+
try:
|
|
218
|
+
text = p.read_bytes().decode("utf-8")
|
|
219
|
+
except (OSError, ValueError):
|
|
220
|
+
continue
|
|
221
|
+
if OLD in text and (new := _ignore_text(text, final)) != text:
|
|
222
|
+
v._atomic_write(p, new) # under the old or the vault lock (callers hold one)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _key_change(text: str) -> str:
|
|
226
|
+
"""`cortex_status`/`cortex_next` front-matter keys renamed in place (line by line, so
|
|
227
|
+
nothing else in the front matter changes); when the new key is there already, the old line
|
|
228
|
+
goes."""
|
|
229
|
+
import re
|
|
230
|
+
|
|
231
|
+
from keepfold.vault import _split
|
|
232
|
+
parts = _split(text)
|
|
233
|
+
if parts is None:
|
|
234
|
+
return text
|
|
235
|
+
head, fm, close, body = parts
|
|
236
|
+
for old, new in KEYS.items():
|
|
237
|
+
if re.search(rf"(?m)^{new}\s*:", fm):
|
|
238
|
+
fm = re.sub(rf"(?m)^{old}\s*:.*(?:\r?\n|\Z)", "", fm)
|
|
239
|
+
else:
|
|
240
|
+
fm = re.sub(rf"(?m)^{old}(?=\s*:)", new, fm)
|
|
241
|
+
return head + fm + close + body
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _keys(v) -> tuple[int, int]:
|
|
245
|
+
"""Every note with an old key rewritten through Vault._mutate (lock, temp file, os.replace,
|
|
246
|
+
and an owner's edit meanwhile is reread). (rewritten, skipped: unreadable front matter)."""
|
|
247
|
+
from keepfold.vault import Vault, VaultError
|
|
248
|
+
done = skipped = 0
|
|
249
|
+
for kind in Vault.KIND_DIRS:
|
|
250
|
+
if kind == "browse": # generated site pages carry no tool keys; browse/ is never read
|
|
251
|
+
continue
|
|
252
|
+
for p in v.note_paths(kind):
|
|
253
|
+
try:
|
|
254
|
+
if b"cortex_" in p.read_bytes() and v._mutate(p, _key_change):
|
|
255
|
+
done += 1
|
|
256
|
+
except (OSError, ValueError, VaultError):
|
|
257
|
+
skipped += 1 # the page keeps its old key; nothing is lost
|
|
258
|
+
return done, skipped
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _views(v) -> None:
|
|
262
|
+
"""Keepfold's Obsidian views (views/*.base), graph colours and property types name the keys
|
|
263
|
+
too."""
|
|
264
|
+
def change(text: str) -> str:
|
|
265
|
+
for old, new in KEYS.items():
|
|
266
|
+
text = text.replace(old, new)
|
|
267
|
+
return text
|
|
268
|
+
|
|
269
|
+
from keepfold.vault import VaultError
|
|
270
|
+
for p in [*(v.root / "views").glob("*.base"), v.root / ".obsidian" / "graph.json",
|
|
271
|
+
v.root / ".obsidian" / "types.json"]:
|
|
272
|
+
try:
|
|
273
|
+
if p.is_file() and b"cortex_" in p.read_bytes():
|
|
274
|
+
v._mutate(p, change)
|
|
275
|
+
except (OSError, ValueError, VaultError):
|
|
276
|
+
pass # a view the owner broke stays as it is
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _old_names(v) -> None:
|
|
280
|
+
"""Files in .keepfold/ whose names or contents held the old names: backups `cortex-*.zip`
|
|
281
|
+
(keepfold.backup and forget look for `keepfold-*.zip`) and the X-ray ring, a trimmed cache
|
|
282
|
+
whose rows the X-ray tab filters by tool name (`cortex_find`) and app (`cortex-app`). The
|
|
283
|
+
index, vector stores and other caches have no old names; changed pages are reindexed."""
|
|
284
|
+
new = v.root / NEW
|
|
285
|
+
for p in sorted((new / "backups").glob("cortex-*.zip")):
|
|
286
|
+
dest = p.with_name("keepfold-" + p.name.removeprefix("cortex-"))
|
|
287
|
+
if not dest.exists():
|
|
288
|
+
os.replace(p, dest) # one rename in .keepfold/, under the vault lock
|
|
289
|
+
ring = new / "xray.jsonl"
|
|
290
|
+
try:
|
|
291
|
+
text = ring.read_bytes().decode("utf-8")
|
|
292
|
+
except (OSError, ValueError):
|
|
293
|
+
return
|
|
294
|
+
fixed = text.replace('"tool":"cortex_', '"tool":"keepfold_').replace(
|
|
295
|
+
'"client":"cortex-app"', '"client":"keepfold-app"')
|
|
296
|
+
if fixed != text:
|
|
297
|
+
v.write_text(ring, fixed)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _identity(root: Path) -> None:
|
|
301
|
+
"""The vault repo's own identity: Cortex <cortex@localhost> becomes Keepfold's."""
|
|
302
|
+
from keepfold import session
|
|
303
|
+
if not (root / ".git").is_dir() or session.git_exe() is None:
|
|
304
|
+
return
|
|
305
|
+
if session._git(root, "config", "--local", "user.email").stdout.strip() != OLD_IDENTITY[1]:
|
|
306
|
+
return
|
|
307
|
+
if session._git(root, "config", "--local", "user.name").stdout.strip() == OLD_IDENTITY[0]:
|
|
308
|
+
session._git(root, "config", "--local", "user.name", NEW_IDENTITY[0])
|
|
309
|
+
session._git(root, "config", "--local", "user.email", NEW_IDENTITY[1])
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _finish(v) -> dict:
|
|
313
|
+
"""Every step after the folder move, under the vault lock; each is idempotent, so a rerun
|
|
314
|
+
after a crash finishes the work. Returns counts."""
|
|
315
|
+
from keepfold import session
|
|
316
|
+
new = v.root / NEW
|
|
317
|
+
with v.lock(PEER_WAIT): # another Keepfold process may be finishing it now
|
|
318
|
+
if not (new / DOING).is_file() and (new / MARKER).is_file():
|
|
319
|
+
return {} # another process finished it meanwhile
|
|
320
|
+
_ignore(v, final=not (v.root / OLD).exists())
|
|
321
|
+
_identity(v.root)
|
|
322
|
+
# what is there first gets its own commit, so the key rewrite can be undone
|
|
323
|
+
session._commit(v, "keepfold: before the move from Cortex")
|
|
324
|
+
_old_names(v)
|
|
325
|
+
mark = v.writes
|
|
326
|
+
notes, skipped = _keys(v)
|
|
327
|
+
_views(v)
|
|
328
|
+
session._commit(v, "keepfold: moved from Cortex", v.wrote_since(mark))
|
|
329
|
+
v.write_text(new / MARKER, _version() + "\n")
|
|
330
|
+
if (new / DOING).exists():
|
|
331
|
+
v.remove(new / DOING)
|
|
332
|
+
return {"notes": notes, "skipped": skipped}
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _same(a: Path, b: Path) -> bool:
|
|
336
|
+
return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b))
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def vault(root: Path) -> dict:
|
|
340
|
+
"""Move one vault's .cortex/ to .keepfold/ and finish the steps after it."""
|
|
341
|
+
from keepfold.vault import Vault, VaultError
|
|
342
|
+
root = Path(root).resolve()
|
|
343
|
+
old, new = root / OLD, root / NEW
|
|
344
|
+
out = {"path": str(root)}
|
|
345
|
+
if _same(root, Path.home()): # ~/.cortex there is the settings folder: home() moves it
|
|
346
|
+
return {**out, "state": "nothing"}
|
|
347
|
+
roots = getattr(_IN, "roots", None) or set()
|
|
348
|
+
_IN.roots = roots
|
|
349
|
+
with _MU:
|
|
350
|
+
roots.add(str(root)) # our own Vault(root) below must not start this again
|
|
351
|
+
try:
|
|
352
|
+
return {**out, **_vault(Vault(root), old, new)}
|
|
353
|
+
except Exception as e: # noqa: BLE001 (reported in plain words; nothing is lost)
|
|
354
|
+
if isinstance(e, VaultError) and e.code == "vault_locked":
|
|
355
|
+
return {**out, "state": "blocked", "message": f"{root} is busy: another "
|
|
356
|
+
f"program holds its files. {CLOSE}"}
|
|
357
|
+
return {**out, "state": "error",
|
|
358
|
+
"message": f"Moving {old} failed ({type(e).__name__}); nothing was "
|
|
359
|
+
"deleted. Run `keepfold migrate` to try again."}
|
|
360
|
+
finally:
|
|
361
|
+
roots.discard(str(root))
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _vault(v, old: Path, new: Path) -> dict:
|
|
365
|
+
from keepfold.vault import Vault
|
|
366
|
+
if old.is_dir():
|
|
367
|
+
if new.exists():
|
|
368
|
+
if (new / MARKER).is_file():
|
|
369
|
+
return _both(old, new)
|
|
370
|
+
if _old_busy(old):
|
|
371
|
+
return _blocked(old)
|
|
372
|
+
return {**_both(old, new), **_finish(v)} # keys, ignore lines, identity still apply
|
|
373
|
+
if _old_busy(old):
|
|
374
|
+
return _blocked(old)
|
|
375
|
+
token = _take_old(v, old / "lock", PEER_WAIT)
|
|
376
|
+
if token is None and old.is_dir():
|
|
377
|
+
return _blocked(old)
|
|
378
|
+
if token is not None:
|
|
379
|
+
got = "blocked"
|
|
380
|
+
try:
|
|
381
|
+
v._atomic_write(old / DOING, _version() + "\n")
|
|
382
|
+
_ignore(v, final=False) # before .keepfold/ exists: it is ignored from the start
|
|
383
|
+
got = _replace(old, new)
|
|
384
|
+
finally:
|
|
385
|
+
for p in (old / "lock", new / "lock"): # wherever our lock now is
|
|
386
|
+
Vault._drop(p, token)
|
|
387
|
+
if got != "moved" and old.is_dir():
|
|
388
|
+
(old / DOING).unlink(missing_ok=True)
|
|
389
|
+
if got == "blocked":
|
|
390
|
+
return _blocked(old)
|
|
391
|
+
if (new / DOING).is_file():
|
|
392
|
+
return {"state": "done", **_finish(v)}
|
|
393
|
+
return {"state": "done" if (new / MARKER).is_file() else "nothing"}
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def on_open(root: Path) -> str | None:
|
|
397
|
+
"""Vault()'s check, on its first construction per root in this process: before anything
|
|
398
|
+
reads or writes .keepfold/, so an empty one never blocks the move. Returns why the vault
|
|
399
|
+
cannot open yet (blocked, error), else None. Two stats when nothing is left to move."""
|
|
400
|
+
key = str(root)
|
|
401
|
+
if key in _SEEN or key in (getattr(_IN, "roots", None) or ()):
|
|
402
|
+
return None
|
|
403
|
+
if source_checkout() or (not os.path.isdir(os.path.join(key, OLD))
|
|
404
|
+
and not os.path.isfile(os.path.join(key, NEW, DOING))):
|
|
405
|
+
_SEEN.add(key)
|
|
406
|
+
return None
|
|
407
|
+
r = vault(root)
|
|
408
|
+
if r["state"] in ("blocked", "error"):
|
|
409
|
+
return r["message"]
|
|
410
|
+
_SEEN.add(key)
|
|
411
|
+
return None
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
# ---- entry points ------------------------------------------------------------------------
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
APPS = "apps-migrated" # in ~/.keepfold: the AI apps were repointed (the app's start skips it)
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _apps() -> dict:
|
|
421
|
+
"""The AI-app connections made under the old names, repointed
|
|
422
|
+
(keepfold.app.targets.migrate_old_entries): {state, rows, message}."""
|
|
423
|
+
try:
|
|
424
|
+
from keepfold.app import targets
|
|
425
|
+
rows = targets.migrate_old_entries()
|
|
426
|
+
except Exception as e: # noqa: BLE001 (an app part that fails must not stop the move)
|
|
427
|
+
return {"state": "error", "rows": [], "message": f"Repointing the AI apps failed "
|
|
428
|
+
f"({type(e).__name__}); run `keepfold doctor` to see what is left."}
|
|
429
|
+
errors = [r for r in rows if r["action"] == "error"]
|
|
430
|
+
left = [r for r in rows if r["action"] == "left"]
|
|
431
|
+
message = " ".join(f"{r['app']}: {r['note']}" for r in errors) or (
|
|
432
|
+
"Some AI-app entries were not Keepfold's own and were left as they were; "
|
|
433
|
+
"`keepfold doctor` lists them." if left else "")
|
|
434
|
+
state = "error" if errors else "done" if any(r["action"] == "moved" for r in rows) \
|
|
435
|
+
else "nothing"
|
|
436
|
+
return {"state": state, "rows": rows, "message": message}
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _overall(*states: str) -> str:
|
|
440
|
+
return max(states or ("nothing",), key=RANK.index)
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _summary(state: str, parts: list[dict]) -> str:
|
|
444
|
+
"""One plain line for the installer's window: the first part in the overall state."""
|
|
445
|
+
for p in parts:
|
|
446
|
+
if p.get("state") == state and p.get("message"):
|
|
447
|
+
return p["message"]
|
|
448
|
+
return {"done": "Your Cortex settings, notes and AI-app connections now use Keepfold.",
|
|
449
|
+
"nothing": "Nothing from Cortex was left to move."}.get(state, "")
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def everything(roots: list[Path] | None = None, apps: bool = True) -> dict:
|
|
453
|
+
"""`keepfold migrate` and the app's start: the home, then each vault (default: the
|
|
454
|
+
configured one), then (with `apps`) the AI apps. `exit`: 0 done or nothing to do, 2
|
|
455
|
+
blocked, 1 error; `message`: one plain line."""
|
|
456
|
+
h = home()
|
|
457
|
+
out = {"home": h, "vaults": [], "apps": None}
|
|
458
|
+
if h["state"] not in ("blocked", "error"):
|
|
459
|
+
if roots is None:
|
|
460
|
+
from keepfold import taint
|
|
461
|
+
roots = [r] if (r := taint._vault_root()) else []
|
|
462
|
+
for r in roots:
|
|
463
|
+
if Path(r).is_dir():
|
|
464
|
+
out["vaults"].append(vault(Path(r)))
|
|
465
|
+
else:
|
|
466
|
+
out["vaults"].append({"path": str(r), "state": "nothing",
|
|
467
|
+
"message": f"{r} does not exist."})
|
|
468
|
+
if apps:
|
|
469
|
+
out["apps"] = _apps()
|
|
470
|
+
if out["apps"]["state"] != "error" and (Path.home() / NEW).is_dir():
|
|
471
|
+
try:
|
|
472
|
+
(Path.home() / NEW / APPS).write_text(_version() + "\n", encoding="utf-8")
|
|
473
|
+
except OSError:
|
|
474
|
+
pass # the app's start repoints again next time; a second run finds nothing
|
|
475
|
+
parts = [h, *out["vaults"], *([out["apps"]] if out["apps"] else [])]
|
|
476
|
+
state = _overall(*(p["state"] for p in parts))
|
|
477
|
+
return {"state": state, "exit": {"error": 1, "blocked": 2}.get(state, 0),
|
|
478
|
+
"message": _summary(state, parts), **out}
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def at_start(argv: list[str]) -> int | None:
|
|
482
|
+
"""The `keepfold` console entry, before anything reads the home: one stat when there is no
|
|
483
|
+
~/.cortex. Returns an exit code to stop with (an old Cortex holds the home), else None. The
|
|
484
|
+
hooks never print and stop quietly; `migrate` does the move itself and `doctor` reports it;
|
|
485
|
+
a source checkout only prints a hint."""
|
|
486
|
+
cmd = argv[1] if len(argv) > 1 else ""
|
|
487
|
+
if cmd == "migrate" or not os.path.isdir(os.path.join(Path.home(), OLD)):
|
|
488
|
+
return None
|
|
489
|
+
hook = cmd in ("taint", "prime-hook")
|
|
490
|
+
if source_checkout():
|
|
491
|
+
if not hook and not os.path.exists(os.path.join(Path.home(), NEW)):
|
|
492
|
+
print("keepfold: Cortex settings found in ~/.cortex; run `keepfold migrate` to move "
|
|
493
|
+
"them to ~/.keepfold.", file=sys.stderr)
|
|
494
|
+
return None
|
|
495
|
+
r = home()
|
|
496
|
+
if r["state"] not in ("blocked", "error") or cmd in ("doctor", "", "--help", "--version"):
|
|
497
|
+
return None
|
|
498
|
+
if not hook:
|
|
499
|
+
print(f"keepfold: {r['message']}", file=sys.stderr)
|
|
500
|
+
return 0 if hook else 2
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def launch() -> str | None:
|
|
504
|
+
"""The app's and the receiver's start: the home, the configured vault and the AI apps. The
|
|
505
|
+
message to show when something blocks or fails, else None."""
|
|
506
|
+
if source_checkout():
|
|
507
|
+
return None
|
|
508
|
+
new = Path.home() / NEW
|
|
509
|
+
# the AI apps once, after a move from Cortex (the installer's `migrate` usually did it)
|
|
510
|
+
r = everything(apps=(new / MARKER).is_file() and not (new / APPS).is_file())
|
|
511
|
+
for part in (r["home"], *r["vaults"]): # an AI app that failed is doctor's, not a stop
|
|
512
|
+
if part["state"] in ("blocked", "error"):
|
|
513
|
+
return part["message"]
|
|
514
|
+
return None
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
# ---- doctor and Status ----------------------------------------------------------------------
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def status(root: Path | None) -> tuple[str, str, str]:
|
|
521
|
+
"""(state ok|warn, value, what to do) for doctor's and the Status page's "Moved from Cortex"
|
|
522
|
+
row, read-only: it never moves anything."""
|
|
523
|
+
h = Path.home()
|
|
524
|
+
parts = [("Settings", h / OLD, h / NEW, h / NEW / MARKER, None)]
|
|
525
|
+
if root is not None and not _same(root, h):
|
|
526
|
+
parts.append(("Vault", root / OLD, root / NEW, root / NEW / MARKER, root / NEW / DOING))
|
|
527
|
+
states, notes = [], []
|
|
528
|
+
for name, old, new, marker, doing in parts:
|
|
529
|
+
if doing is not None and doing.is_file():
|
|
530
|
+
states.append("pending")
|
|
531
|
+
notes.append(f"{name}: the move from {old} did not finish. {CLOSE}")
|
|
532
|
+
elif old.is_dir() and new.exists():
|
|
533
|
+
states.append("both")
|
|
534
|
+
notes.append(f"{name}: {_both(old, new)['message']}")
|
|
535
|
+
elif old.is_dir():
|
|
536
|
+
states.append("pending")
|
|
537
|
+
notes.append(f"{name}: {old} is not moved yet. {CLOSE}" + (
|
|
538
|
+
"" if not source_checkout() else " (From a source checkout: `keepfold migrate`.)"))
|
|
539
|
+
else:
|
|
540
|
+
states.append("done" if marker.is_file() else "nothing")
|
|
541
|
+
if "pending" in states:
|
|
542
|
+
return "warn", "not moved yet", " ".join(notes)
|
|
543
|
+
if "both" in states:
|
|
544
|
+
return "warn", "both folders exist", " ".join(notes)
|
|
545
|
+
if "done" in states:
|
|
546
|
+
return "ok", "done", ""
|
|
547
|
+
return "ok", "nothing to move", ""
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def old_env() -> list[str]:
|
|
551
|
+
"""CORTEX_* variables still set: Keepfold reads only KEEPFOLD_* (no fallback)."""
|
|
552
|
+
return sorted(k for k in os.environ if k.upper().startswith("CORTEX_"))
|