flowstatemcp 2.5.0__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.
- flowstate/__init__.py +34 -0
- flowstate/__main__.py +7 -0
- flowstate/activity.py +224 -0
- flowstate/agent_guide.py +251 -0
- flowstate/app_keys.py +141 -0
- flowstate/approvals.py +974 -0
- flowstate/approve_page.py +565 -0
- flowstate/ask.py +107 -0
- flowstate/autosession.py +480 -0
- flowstate/backup.py +201 -0
- flowstate/brief.py +420 -0
- flowstate/card_offer.py +208 -0
- flowstate/card_taps.py +165 -0
- flowstate/card_trust.py +127 -0
- flowstate/claims.py +461 -0
- flowstate/cleanup.py +619 -0
- flowstate/cli.py +728 -0
- flowstate/cli_data.py +434 -0
- flowstate/cli_more.py +302 -0
- flowstate/cli_review.py +459 -0
- flowstate/cloudflared_check.py +49 -0
- flowstate/conflict_card_ui.py +286 -0
- flowstate/conflict_cards.py +1193 -0
- flowstate/conflict_reopen.py +320 -0
- flowstate/conflicts.py +420 -0
- flowstate/connections.py +33 -0
- flowstate/database.py +2191 -0
- flowstate/dbconn.py +308 -0
- flowstate/deletes.py +860 -0
- flowstate/embeddings.py +354 -0
- flowstate/erase.py +1047 -0
- flowstate/extras.py +71 -0
- flowstate/git_capture.py +157 -0
- flowstate/guard.py +224 -0
- flowstate/handoffs.py +168 -0
- flowstate/history.py +755 -0
- flowstate/history_page.py +276 -0
- flowstate/http_app.py +204 -0
- flowstate/identity.py +387 -0
- flowstate/install_name.py +140 -0
- flowstate/ledger.py +272 -0
- flowstate/legacy_args.py +65 -0
- flowstate/links.py +609 -0
- flowstate/markdown_io.py +242 -0
- flowstate/meaning.py +398 -0
- flowstate/memory_import.py +92 -0
- flowstate/migrations/001_auto_sessions.sql +16 -0
- flowstate/migrations/002_review_queue.sql +33 -0
- flowstate/migrations/003_links.sql +47 -0
- flowstate/migrations/004_review_mode.sql +24 -0
- flowstate/migrations/005_history.sql +21 -0
- flowstate/migrations/006_activity.sql +26 -0
- flowstate/migrations/007_meaning_index.sql +16 -0
- flowstate/migrations/008_git_capture.sql +12 -0
- flowstate/migrations/009_hard_rules.sql +13 -0
- flowstate/migrations/010_handoffs.sql +14 -0
- flowstate/migrations/011_record_meta.sql +13 -0
- flowstate/migrations/012_accountability.sql +71 -0
- flowstate/migrations/013_todo_claims.sql +36 -0
- flowstate/migrations/014_decision_conflicts.sql +41 -0
- flowstate/migrations/015_session_runs.sql +17 -0
- flowstate/migrations/016_write_receipts.sql +35 -0
- flowstate/migrations/017_run_views.sql +26 -0
- flowstate/migrations/018_run_views_upto.sql +4 -0
- flowstate/migrations/019_approvals.sql +47 -0
- flowstate/migrations/020_source_stamps.sql +10 -0
- flowstate/migrations/021_review_links.sql +11 -0
- flowstate/migrations/022_review_start_tickets.sql +10 -0
- flowstate/migrations/023_conflict_cards.sql +68 -0
- flowstate/migrations/024_rule_confirmations.sql +7 -0
- flowstate/migrations/025_confirmed_hash.sql +7 -0
- flowstate/migrations/__init__.py +149 -0
- flowstate/models.py +307 -0
- flowstate/names.py +157 -0
- flowstate/offsite.py +386 -0
- flowstate/offsite_crypto.py +272 -0
- flowstate/paths.py +265 -0
- flowstate/popup.py +238 -0
- flowstate/priority.py +66 -0
- flowstate/privatefs.py +476 -0
- flowstate/project_history.py +710 -0
- flowstate/provenance.py +696 -0
- flowstate/receipts.py +377 -0
- flowstate/relay/__init__.py +72 -0
- flowstate/relay/acme.py +271 -0
- flowstate/relay/api.py +164 -0
- flowstate/relay/cli.py +344 -0
- flowstate/relay/crypto.py +137 -0
- flowstate/relay/ct.py +118 -0
- flowstate/relay/runner.py +177 -0
- flowstate/relay/store.py +191 -0
- flowstate/relay/tunnel.py +413 -0
- flowstate/release_signers +14 -0
- flowstate/remote_auth.py +1219 -0
- flowstate/review.py +320 -0
- flowstate/review_apply.py +140 -0
- flowstate/review_card_ui.py +241 -0
- flowstate/review_cards.py +564 -0
- flowstate/review_mode.py +274 -0
- flowstate/review_page.py +1361 -0
- flowstate/review_phone.py +465 -0
- flowstate/review_tunnel.py +338 -0
- flowstate/routing.py +392 -0
- flowstate/rules.py +418 -0
- flowstate/safety.py +98 -0
- flowstate/saves.py +83 -0
- flowstate/scheduler.py +160 -0
- flowstate/schema.sql +713 -0
- flowstate/search.py +355 -0
- flowstate/secret_store.py +271 -0
- flowstate/secrets_scan.py +135 -0
- flowstate/selfupdate.py +1020 -0
- flowstate/server.py +1299 -0
- flowstate/session_contents.py +382 -0
- flowstate/session_records.py +629 -0
- flowstate/site_style.py +46 -0
- flowstate/stored.py +158 -0
- flowstate/story.py +442 -0
- flowstate/surface.py +173 -0
- flowstate/tasks.py +231 -0
- flowstate/term.py +40 -0
- flowstate/tool_labels.py +104 -0
- flowstate/tooldefs.py +383 -0
- flowstate/tools/__init__.py +118 -0
- flowstate/tools/core.py +545 -0
- flowstate/tools/files.py +416 -0
- flowstate/tools/git_ops.py +1081 -0
- flowstate/tools/intelligence.py +376 -0
- flowstate/tools/learning.py +282 -0
- flowstate/tools/problems.py +159 -0
- flowstate/tools/sessions.py +266 -0
- flowstate/tools/story.py +48 -0
- flowstate/tools/todos.py +79 -0
- flowstate/tools/utils.py +71 -0
- flowstate/tools/variables.py +345 -0
- flowstate/updates.py +482 -0
- flowstate/urls.py +7 -0
- flowstate/waiting.py +828 -0
- flowstate/who.py +302 -0
- flowstatemcp-2.5.0.dist-info/METADATA +88 -0
- flowstatemcp-2.5.0.dist-info/RECORD +143 -0
- flowstatemcp-2.5.0.dist-info/WHEEL +4 -0
- flowstatemcp-2.5.0.dist-info/entry_points.txt +3 -0
flowstate/updates.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
"""The quiet daily update check (2.4.0). Standard library only.
|
|
2
|
+
|
|
3
|
+
Once a day, lazily from start_here, ONE background thread asks GitHub for the newest FlowState
|
|
4
|
+
release and writes the answer to `update.json` in the FlowState data folder. The brief then
|
|
5
|
+
reads only that file: when a newer release exists it gets one line on top. Nobody waits for
|
|
6
|
+
the network, and nothing runs when nobody calls start_here.
|
|
7
|
+
|
|
8
|
+
The request: GET https://api.github.com/repos/dialectforge/FlowState/releases/latest with
|
|
9
|
+
`Accept: application/vnd.github+json` and `User-Agent: FlowState-update-check` (no version),
|
|
10
|
+
never an `Authorization` header, TLS 1.2+, no redirects followed, 5 s timeout, body capped at
|
|
11
|
+
256 KB, `If-None-Match` with the saved ETag. It sends nothing about the user or their projects
|
|
12
|
+
(only what any web request reveals: the IP address).
|
|
13
|
+
|
|
14
|
+
Off: `flowstate update check off` (config.json "update_check": false) or the environment
|
|
15
|
+
FLOWSTATE_UPDATE_CHECK=0. Off means no request at all and no line.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import importlib.util
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import ssl
|
|
23
|
+
import threading
|
|
24
|
+
import time
|
|
25
|
+
import urllib.error
|
|
26
|
+
import urllib.request
|
|
27
|
+
from datetime import datetime, timezone
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Callable, Optional
|
|
30
|
+
|
|
31
|
+
from . import paths
|
|
32
|
+
|
|
33
|
+
RELEASES_URL = "https://api.github.com/repos/dialectforge/FlowState/releases/latest"
|
|
34
|
+
HTML_PREFIX = "https://github.com/dialectforge/FlowState/"
|
|
35
|
+
USER_AGENT = "FlowState-update-check"
|
|
36
|
+
TAG_RE = re.compile(r"^v(\d{1,4})\.(\d{1,4})\.(\d{1,4})$")
|
|
37
|
+
VERSION_RE = re.compile(r"^(\d{1,4})\.(\d{1,4})\.(\d{1,4})$")
|
|
38
|
+
TIMEOUT = 5.0
|
|
39
|
+
MAX_BODY = 256 * 1024
|
|
40
|
+
FRESH_SECONDS = 24 * 3600 # check again after a day
|
|
41
|
+
RETRY_SECONDS = 6 * 3600 # ... or after 6 hours when the last check failed
|
|
42
|
+
STAMP_STALE_SECONDS = 120 # a "checking" stamp older than this is ignored
|
|
43
|
+
STATE_NAME = "update.json"
|
|
44
|
+
MANUAL_STEPS = "git fetch --tags, git checkout v{latest}, then setup_flowstate.py --verify with the same options"
|
|
45
|
+
|
|
46
|
+
Fetch = Callable[[str, dict, float], tuple] # (url, headers, timeout) -> (status, headers, body)
|
|
47
|
+
|
|
48
|
+
_lock = threading.Lock()
|
|
49
|
+
_worker: Optional[threading.Thread] = None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# ---------------------------------------------------------------- settings
|
|
53
|
+
def is_on() -> bool:
|
|
54
|
+
"""The check is on unless FLOWSTATE_UPDATE_CHECK=0 or config.json says "update_check": false.
|
|
55
|
+
A config.json that exists but can't be read counts as off (it may say false): a privacy
|
|
56
|
+
setting fails closed."""
|
|
57
|
+
env = (os.environ.get("FLOWSTATE_UPDATE_CHECK") or "").strip().lower()
|
|
58
|
+
if env in ("0", "false", "off", "no"):
|
|
59
|
+
return False
|
|
60
|
+
try:
|
|
61
|
+
return paths.load_config(strict=True).get("update_check") is not False
|
|
62
|
+
except Exception: # noqa: BLE001
|
|
63
|
+
return False
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def set_on(on: bool) -> Path:
|
|
67
|
+
return paths.update_config(lambda cfg: cfg.__setitem__("update_check", bool(on)))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def self_update_allowed() -> bool:
|
|
71
|
+
"""config.json "self_update": false opts this computer out of `flowstate update`. A
|
|
72
|
+
config.json that exists but can't be read counts as opted out (it may say false)."""
|
|
73
|
+
try:
|
|
74
|
+
return paths.load_config(strict=True).get("self_update") is not False
|
|
75
|
+
except Exception: # noqa: BLE001
|
|
76
|
+
return False
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
SELF_UPDATE_SCOPE = "config:self_update"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def set_self_update(allowed: bool, db_path: Optional[Path] = None, who: str = "command-line",
|
|
83
|
+
how: Optional[str] = None) -> dict:
|
|
84
|
+
"""config.json "self_update": allowed -> the key is removed (the default), else false, and
|
|
85
|
+
one review_mode_log row in `db_path` (when that database has the table) saying `who` changed
|
|
86
|
+
it and `how`. Only the user's terminal (`flowstate update self-update on|off`, cli_self_update
|
|
87
|
+
below) and the local review page (review_page.py) call this; no MCP tool reads or writes it."""
|
|
88
|
+
old = "allowed" if self_update_allowed() else "by hand"
|
|
89
|
+
|
|
90
|
+
def change(cfg: dict) -> None:
|
|
91
|
+
if allowed:
|
|
92
|
+
cfg.pop("self_update", None)
|
|
93
|
+
else:
|
|
94
|
+
cfg["self_update"] = False
|
|
95
|
+
path = paths.update_config(change)
|
|
96
|
+
new = "allowed" if self_update_allowed() else "by hand"
|
|
97
|
+
from . import approvals
|
|
98
|
+
approvals.log_setting(db_path, SELF_UPDATE_SCOPE, old, new, who, how)
|
|
99
|
+
return {"old": old, "now": new, "path": path}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def opt_out_file() -> Optional[Path]:
|
|
103
|
+
"""The FlowState folder's `.flowstate-no-self-update` file if it is there, else None."""
|
|
104
|
+
try:
|
|
105
|
+
from .selfupdate import FOLDER, OPT_OUT_FILE
|
|
106
|
+
except ImportError:
|
|
107
|
+
return None
|
|
108
|
+
f = FOLDER / OPT_OUT_FILE
|
|
109
|
+
return f if f.exists() else None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def self_update_status() -> dict:
|
|
113
|
+
"""What `flowstate update self-update` shows: allowed or not, and why."""
|
|
114
|
+
file = opt_out_file()
|
|
115
|
+
try:
|
|
116
|
+
in_config = "self_update" in paths.load_config()
|
|
117
|
+
except Exception: # noqa: BLE001
|
|
118
|
+
in_config = False
|
|
119
|
+
allowed = self_update_allowed()
|
|
120
|
+
if file is not None:
|
|
121
|
+
source = "file"
|
|
122
|
+
elif not allowed:
|
|
123
|
+
source = "config.json"
|
|
124
|
+
else:
|
|
125
|
+
source = "config.json" if in_config else "default"
|
|
126
|
+
return {"allowed": allowed and file is None, "config_allowed": allowed, "source": source,
|
|
127
|
+
"file": file, "config": paths.config_file()}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def has_update_command() -> bool:
|
|
131
|
+
"""Does the code running now have `flowstate update` (the self-updater module)?"""
|
|
132
|
+
try:
|
|
133
|
+
return importlib.util.find_spec(f"{__package__}.selfupdate") is not None
|
|
134
|
+
except (ImportError, ValueError):
|
|
135
|
+
return False
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# ---------------------------------------------------------------- versions
|
|
139
|
+
def parse_version(v) -> Optional[tuple]:
|
|
140
|
+
m = VERSION_RE.fullmatch(str(v or ""))
|
|
141
|
+
return tuple(int(x) for x in m.groups()) if m else None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def newer(a, b) -> bool:
|
|
145
|
+
"""Is version a strictly newer than version b? False when either is not X.Y.Z."""
|
|
146
|
+
pa, pb = parse_version(a), parse_version(b)
|
|
147
|
+
return bool(pa and pb and pa > pb)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
# ---------------------------------------------------------------- the state file
|
|
151
|
+
def state_file() -> Path:
|
|
152
|
+
return paths.data_root() / STATE_NAME
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def read_state(path: Optional[Path] = None) -> dict:
|
|
156
|
+
try:
|
|
157
|
+
data = json.loads(Path(path or state_file()).read_text(encoding="utf-8"))
|
|
158
|
+
return data if isinstance(data, dict) else {}
|
|
159
|
+
except (OSError, ValueError):
|
|
160
|
+
return {}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def write_state(changes: dict, path: Optional[Path] = None) -> dict:
|
|
164
|
+
"""Merge `changes` into update.json (atomic replace) and return the new state."""
|
|
165
|
+
from .privatefs import private_dir
|
|
166
|
+
p = Path(path or state_file())
|
|
167
|
+
private_dir(p.parent)
|
|
168
|
+
state = {**read_state(p), **changes}
|
|
169
|
+
tmp = p.with_name(f"{p.name}.{os.getpid()}.{threading.get_ident()}.tmp")
|
|
170
|
+
tmp.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
|
|
171
|
+
paths.replace_file(tmp, p)
|
|
172
|
+
return state
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _iso(ts: float) -> str:
|
|
176
|
+
return datetime.fromtimestamp(ts, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _epoch(iso) -> Optional[float]:
|
|
180
|
+
try:
|
|
181
|
+
return datetime.strptime(str(iso), "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).timestamp()
|
|
182
|
+
except (TypeError, ValueError):
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def local_time(iso) -> str:
|
|
187
|
+
ts = _epoch(iso)
|
|
188
|
+
return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M") if ts is not None else "never"
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def due(state: dict, now: Optional[float] = None) -> bool:
|
|
192
|
+
last = _epoch(state.get("checked_at"))
|
|
193
|
+
if last is None:
|
|
194
|
+
return True
|
|
195
|
+
wait = RETRY_SECONDS if state.get("last_error") else FRESH_SECONDS
|
|
196
|
+
return (now if now is not None else time.time()) - last >= wait
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# ---------------------------------------------------------------- the request
|
|
200
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
201
|
+
def redirect_request(self, *a, **kw): # a 3xx comes back as a status, never followed
|
|
202
|
+
return None
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _context() -> ssl.SSLContext:
|
|
206
|
+
ctx = ssl.create_default_context()
|
|
207
|
+
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
208
|
+
return ctx
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _http_get(url: str, headers: dict, timeout: float) -> tuple:
|
|
212
|
+
"""The real request: (status, headers, body). Reads at most MAX_BODY + 1 bytes."""
|
|
213
|
+
req = urllib.request.Request(url, method="GET", headers=headers)
|
|
214
|
+
opener = urllib.request.build_opener(urllib.request.HTTPSHandler(context=_context()), _NoRedirect())
|
|
215
|
+
try:
|
|
216
|
+
with opener.open(req, timeout=timeout) as r:
|
|
217
|
+
return r.status, dict(r.headers), r.read(MAX_BODY + 1)
|
|
218
|
+
except urllib.error.HTTPError as e:
|
|
219
|
+
with e:
|
|
220
|
+
return e.code, dict(e.headers or {}), b""
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def request_headers(etag: Optional[str] = None) -> dict:
|
|
224
|
+
h = {"Accept": "application/vnd.github+json", "User-Agent": USER_AGENT}
|
|
225
|
+
if etag:
|
|
226
|
+
h["If-None-Match"] = etag
|
|
227
|
+
return h
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _release(data) -> Optional[dict]:
|
|
231
|
+
"""The fields we keep from a 'latest release' answer, or None when it isn't one we trust."""
|
|
232
|
+
if not isinstance(data, dict):
|
|
233
|
+
return None
|
|
234
|
+
tag, url = data.get("tag_name"), data.get("html_url")
|
|
235
|
+
if not isinstance(tag, str) or not TAG_RE.fullmatch(tag):
|
|
236
|
+
return None
|
|
237
|
+
if data.get("draft") is not False or data.get("prerelease") is not False:
|
|
238
|
+
return None
|
|
239
|
+
if not isinstance(url, str) or not url.startswith(HTML_PREFIX):
|
|
240
|
+
return None
|
|
241
|
+
published = data.get("published_at")
|
|
242
|
+
return {"latest": tag[1:], "tag": tag, "url": url,
|
|
243
|
+
"published_at": published if isinstance(published, str) and len(published) <= 40 else None}
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def fetch_latest(fetch: Optional[Fetch] = None, etag: Optional[str] = None) -> dict:
|
|
247
|
+
"""Ask GitHub for the newest release. Never raises. One of:
|
|
248
|
+
{"ok": True, "latest", "tag", "url", "published_at", "etag"}
|
|
249
|
+
{"ok": True, "not_modified": True} (304 for our ETag: nothing new)
|
|
250
|
+
{"ok": False, "error": "<short reason>"} (offline, 403/429, odd answer, ...)"""
|
|
251
|
+
fetch = fetch or _http_get
|
|
252
|
+
try:
|
|
253
|
+
status, headers, body = fetch(RELEASES_URL, request_headers(etag), TIMEOUT)
|
|
254
|
+
except (TimeoutError, ssl.SSLError, urllib.error.URLError, OSError, ValueError) as e:
|
|
255
|
+
if isinstance(e, TimeoutError) or "timed out" in str(e):
|
|
256
|
+
return {"ok": False, "error": "GitHub did not answer within 5 seconds"}
|
|
257
|
+
return {"ok": False, "error": f"can't reach GitHub ({type(e).__name__})"}
|
|
258
|
+
except Exception as e: # noqa: BLE001 - a check must never break anything
|
|
259
|
+
return {"ok": False, "error": f"check failed ({type(e).__name__})"}
|
|
260
|
+
if status == 304:
|
|
261
|
+
return {"ok": True, "not_modified": True}
|
|
262
|
+
if status in (403, 429):
|
|
263
|
+
return {"ok": False, "error": f"GitHub refused the check for now ({status}, rate limit)"}
|
|
264
|
+
if status != 200:
|
|
265
|
+
return {"ok": False, "error": f"GitHub answered {status}"}
|
|
266
|
+
body = body or b""
|
|
267
|
+
if len(body) > MAX_BODY:
|
|
268
|
+
return {"ok": False, "error": "GitHub's answer was too large"}
|
|
269
|
+
try:
|
|
270
|
+
data = json.loads(body.decode("utf-8"))
|
|
271
|
+
except (UnicodeDecodeError, ValueError):
|
|
272
|
+
return {"ok": False, "error": "GitHub's answer was not JSON"}
|
|
273
|
+
rel = _release(data)
|
|
274
|
+
if rel is None:
|
|
275
|
+
return {"ok": False, "error": "GitHub's answer was not a FlowState release"}
|
|
276
|
+
tag_etag = {k.lower(): v for k, v in (headers or {}).items()}.get("etag")
|
|
277
|
+
rel["etag"] = tag_etag if isinstance(tag_etag, str) and len(tag_etag) <= 200 else None
|
|
278
|
+
return {"ok": True, **rel}
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def check_now(fetch: Optional[Fetch] = None, path: Optional[Path] = None,
|
|
282
|
+
now: Optional[float] = None) -> dict:
|
|
283
|
+
"""Fetch in the foreground and save the result. Returns the new state. Never raises."""
|
|
284
|
+
state = read_state(path)
|
|
285
|
+
res = fetch_latest(fetch, state.get("etag") if state.get("latest") else None)
|
|
286
|
+
stamp = {"checked_at": _iso(now if now is not None else time.time())}
|
|
287
|
+
if not res["ok"]:
|
|
288
|
+
stamp["last_error"] = res["error"]
|
|
289
|
+
elif res.get("not_modified"):
|
|
290
|
+
stamp["last_error"] = None
|
|
291
|
+
else:
|
|
292
|
+
stamp.update({k: res.get(k) for k in ("latest", "tag", "url", "published_at", "etag")},
|
|
293
|
+
last_error=None)
|
|
294
|
+
try:
|
|
295
|
+
return write_state(stamp, path)
|
|
296
|
+
except OSError as e:
|
|
297
|
+
return {**state, **stamp, "last_error": stamp.get("last_error") or f"could not save ({type(e).__name__})"}
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
# ---------------------------------------------------------------- the lazy background check
|
|
301
|
+
def _stamp_file(path: Optional[Path]) -> Path:
|
|
302
|
+
p = Path(path or state_file())
|
|
303
|
+
return p.with_name(p.name + ".checking")
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _take_stamp(stamp: Path, now: float) -> bool:
|
|
307
|
+
"""Only one process checks at a time; a stamp older than 2 minutes is a leftover."""
|
|
308
|
+
stamp.parent.mkdir(parents=True, exist_ok=True)
|
|
309
|
+
for _ in range(2):
|
|
310
|
+
try:
|
|
311
|
+
fd = os.open(stamp, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
|
312
|
+
os.write(fd, _iso(now).encode())
|
|
313
|
+
os.close(fd)
|
|
314
|
+
return True
|
|
315
|
+
except FileExistsError:
|
|
316
|
+
try:
|
|
317
|
+
if now - stamp.stat().st_mtime < STAMP_STALE_SECONDS:
|
|
318
|
+
return False
|
|
319
|
+
stamp.unlink()
|
|
320
|
+
except OSError:
|
|
321
|
+
return False
|
|
322
|
+
return False
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def maybe_refresh(fetch: Optional[Fetch] = None, path: Optional[Path] = None,
|
|
326
|
+
now: Optional[float] = None) -> bool:
|
|
327
|
+
"""If the check is on and the saved answer is old, start ONE daemon thread that checks.
|
|
328
|
+
Returns at once (True when a thread was started). Never raises."""
|
|
329
|
+
global _worker
|
|
330
|
+
try:
|
|
331
|
+
if not is_on():
|
|
332
|
+
return False
|
|
333
|
+
now = now if now is not None else time.time()
|
|
334
|
+
path = Path(path or state_file())
|
|
335
|
+
if not due(read_state(path), now):
|
|
336
|
+
return False
|
|
337
|
+
with _lock:
|
|
338
|
+
if _worker is not None and _worker.is_alive():
|
|
339
|
+
return False
|
|
340
|
+
stamp = _stamp_file(path)
|
|
341
|
+
if not _take_stamp(stamp, now):
|
|
342
|
+
return False
|
|
343
|
+
|
|
344
|
+
def run():
|
|
345
|
+
try:
|
|
346
|
+
check_now(fetch, path)
|
|
347
|
+
finally:
|
|
348
|
+
try:
|
|
349
|
+
stamp.unlink()
|
|
350
|
+
except OSError:
|
|
351
|
+
pass
|
|
352
|
+
_worker = threading.Thread(target=run, name="flowstate-update-check", daemon=True)
|
|
353
|
+
_worker.start()
|
|
354
|
+
return True
|
|
355
|
+
except Exception: # noqa: BLE001 - never into a tool
|
|
356
|
+
return False
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
# ---------------------------------------------------------------- the brief line
|
|
360
|
+
def restart_line(running_version: str, state: dict) -> Optional[str]:
|
|
361
|
+
"""After `flowstate update`, processes still running the old code say so."""
|
|
362
|
+
last = state.get("last_update") or {}
|
|
363
|
+
if last.get("result") == "ok" and newer(last.get("to"), running_version):
|
|
364
|
+
return (f"FlowState was updated to {last['to']}; this app still runs {running_version}. "
|
|
365
|
+
f"Ask the user to restart it.")
|
|
366
|
+
return None
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def brief_line(running_version: str, path: Optional[Path] = None) -> Optional[str]:
|
|
370
|
+
"""One line when the saved answer names a release newer than the running code (or when
|
|
371
|
+
this process runs older code than `flowstate update` installed), else None.
|
|
372
|
+
Reads only update.json. Never raises."""
|
|
373
|
+
try:
|
|
374
|
+
st = read_state(path)
|
|
375
|
+
restart = restart_line(running_version, st)
|
|
376
|
+
if restart:
|
|
377
|
+
return restart
|
|
378
|
+
if not is_on():
|
|
379
|
+
return None
|
|
380
|
+
latest = st.get("latest")
|
|
381
|
+
if not newer(latest, running_version):
|
|
382
|
+
return None
|
|
383
|
+
url = st.get("url") if str(st.get("url") or "").startswith(HTML_PREFIX) else HTML_PREFIX + "releases"
|
|
384
|
+
head = f"FlowState {latest} is out (this computer has {running_version}). Tell the user once"
|
|
385
|
+
if has_update_command() and self_update_allowed():
|
|
386
|
+
how = (f"; if they want it, run flowstate update --dry-run and show them the plan "
|
|
387
|
+
f"({url}).")
|
|
388
|
+
else:
|
|
389
|
+
how = f"; if they want it: {MANUAL_STEPS.format(latest=latest)} ({url})."
|
|
390
|
+
line = head + how + " Never update without being asked."
|
|
391
|
+
return line if len(line) < 300 else head + f" ({url}). Never update without being asked."
|
|
392
|
+
except Exception: # noqa: BLE001
|
|
393
|
+
return None
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def brief_lines(running_version: str) -> Optional[str]:
|
|
397
|
+
"""What start_here puts on top: starts the lazy check if due, then the line(s). Never raises."""
|
|
398
|
+
maybe_refresh()
|
|
399
|
+
return brief_line(running_version)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
# ---------------------------------------------------------------- `flowstate update check`
|
|
403
|
+
CHECK_SCOPE = "config:update_check"
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def cli_check(sub: Optional[str], say=print, db_path: Optional[Path] = None) -> int:
|
|
407
|
+
if sub in ("on", "off"):
|
|
408
|
+
old = "on" if is_on() else "off"
|
|
409
|
+
p = set_on(sub == "on")
|
|
410
|
+
from . import approvals
|
|
411
|
+
approvals.log_setting(db_path, CHECK_SCOPE, old, "on" if is_on() else "off")
|
|
412
|
+
say(f"Update check is {sub} (saved in {p})."
|
|
413
|
+
+ ("" if sub == "on" else " FlowState makes no request to GitHub now."))
|
|
414
|
+
if sub == "on" and not is_on():
|
|
415
|
+
say("Note: FLOWSTATE_UPDATE_CHECK=0 is set in this environment, which keeps it off here.")
|
|
416
|
+
return 0
|
|
417
|
+
if sub == "now":
|
|
418
|
+
if not is_on():
|
|
419
|
+
say("The update check is off (flowstate update check on to turn it on). Nothing was asked.")
|
|
420
|
+
return 1
|
|
421
|
+
st = check_now()
|
|
422
|
+
_show(st, say)
|
|
423
|
+
return 0 if not st.get("last_error") else 1
|
|
424
|
+
_show(read_state(), say)
|
|
425
|
+
return 0
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
# ---------------------------------------------------------------- `flowstate update self-update`
|
|
429
|
+
def cli_self_update(sub: Optional[str], db_path: Optional[Path], say=print) -> int:
|
|
430
|
+
"""on / off: config.json "self_update", logged like the review page's Settings. No argument:
|
|
431
|
+
the value now and where it comes from. No confirm prompt (as on the page). The
|
|
432
|
+
.flowstate-no-self-update file is never deleted here; `on` says it still keeps updates off."""
|
|
433
|
+
if sub in ("on", "off"):
|
|
434
|
+
res = set_self_update(sub == "on", db_path)
|
|
435
|
+
if sub == "off":
|
|
436
|
+
say(f"This computer is now updated by hand: `flowstate update` refuses to run "
|
|
437
|
+
f"(saved in {res['path']}). `flowstate update self-update on` allows it again.")
|
|
438
|
+
return 0
|
|
439
|
+
say(f"config.json allows `flowstate update` again (saved in {res['path']}).")
|
|
440
|
+
file = opt_out_file()
|
|
441
|
+
if file is not None:
|
|
442
|
+
say(f"But the file {file} still keeps this folder updated by hand, so "
|
|
443
|
+
"`flowstate update` still refuses. To allow it, delete that file yourself "
|
|
444
|
+
f"(macOS / Linux: rm \"{file}\"; Windows: del \"{file}\"). FlowState leaves it "
|
|
445
|
+
"where it is.")
|
|
446
|
+
return 0
|
|
447
|
+
if sub is not None:
|
|
448
|
+
say("Use `flowstate update self-update on`, `off`, or no word to see the value.")
|
|
449
|
+
return 2
|
|
450
|
+
st = self_update_status()
|
|
451
|
+
word = "allowed" if st["allowed"] else "by hand"
|
|
452
|
+
if st["source"] == "file":
|
|
453
|
+
why = (f"the file {st['file']} keeps this folder updated by hand"
|
|
454
|
+
+ ("" if st["config_allowed"] else
|
|
455
|
+
f"; config.json also says \"self_update\": false, in {st['config']}"))
|
|
456
|
+
elif st["source"] == "config.json":
|
|
457
|
+
why = (f"config.json says \"self_update\": false, in {st['config']}" if not st["allowed"]
|
|
458
|
+
else f"set in config.json, {st['config']}")
|
|
459
|
+
else:
|
|
460
|
+
why = "the default; config.json has no \"self_update\""
|
|
461
|
+
say(f"Updates by `flowstate update`: {word} ({why}).")
|
|
462
|
+
say("Change it with `flowstate update self-update on|off`"
|
|
463
|
+
+ (" (the file wins until you delete it)." if st["source"] == "file" else "."))
|
|
464
|
+
return 0
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def _show(st: dict, say) -> None:
|
|
468
|
+
from . import __version__
|
|
469
|
+
try:
|
|
470
|
+
paths.load_config(strict=True)
|
|
471
|
+
why = ""
|
|
472
|
+
except paths.ConfigUnreadable:
|
|
473
|
+
why = ", because FlowState's settings file can't be read"
|
|
474
|
+
say(f"Update check: {'on' if is_on() else 'off' + why} (once a day, from GitHub; "
|
|
475
|
+
f"flowstate update check on|off|now).")
|
|
476
|
+
say(f"This computer runs FlowState {__version__}.")
|
|
477
|
+
say(f"Last check: {local_time(st.get('checked_at'))}"
|
|
478
|
+
+ (f"; newest release seen: {st['latest']} ({st.get('url')})" if st.get("latest") else ""))
|
|
479
|
+
if st.get("last_error"):
|
|
480
|
+
say(f"Last error: {st['last_error']}")
|
|
481
|
+
if newer(st.get("latest"), __version__):
|
|
482
|
+
say(f"A newer release is out: {st['latest']}.")
|
flowstate/urls.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""One spelling for URL and issuer strings that are compared or joined: no trailing '/'."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def no_trailing_slash(url: str) -> str:
|
|
5
|
+
"""`url` without any trailing '/' (all of them, like str.rstrip). Not for request paths or
|
|
6
|
+
file paths: those strip '/' for their own reasons where they are used."""
|
|
7
|
+
return url.rstrip("/")
|