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/backup.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""Local backups and restore. Standard library only.
|
|
2
|
+
|
|
3
|
+
backup_now: SQLite online backup API from a read-only connection (safe while the
|
|
4
|
+
servers are running), `PRAGMA integrity_check` on the copy, then retention: the newest
|
|
5
|
+
backup of each of the last 14 days that have one, plus the newest of each of the last 8
|
|
6
|
+
ISO weeks. Safety copies (labelled pre-restore, pre-migration, pre-bulk or pre-update) are
|
|
7
|
+
also kept for at least SAFETY_KEEP_DAYS whatever those limits say, so a later backup the same
|
|
8
|
+
day can't remove the copy taken just before a restore. Only files named like FlowState backups are
|
|
9
|
+
ever deleted.
|
|
10
|
+
|
|
11
|
+
restore: verify the backup, copy it into a NEW file, verify the result. Writing over an
|
|
12
|
+
existing database needs force=True and first takes a verified pre-restore backup.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
import sqlite3
|
|
17
|
+
from datetime import datetime, timedelta
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Optional
|
|
20
|
+
|
|
21
|
+
from . import paths
|
|
22
|
+
from .privatefs import private_dir, private_file
|
|
23
|
+
|
|
24
|
+
KEEP_DAILY = 14
|
|
25
|
+
KEEP_WEEKLY = 8
|
|
26
|
+
SAFETY_KEEP_DAYS = 7
|
|
27
|
+
SAFETY_LABELS = ("pre-restore", "pre-migration", "pre-bulk", "pre-update")
|
|
28
|
+
PREFIX = "flowstate-"
|
|
29
|
+
_BACKUP_NAME = re.compile(r"^flowstate-(\d{8})-(\d{6})(?:-([a-z0-9-]+))?\.db$")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class BackupError(Exception):
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _ro(path: Path) -> sqlite3.Connection:
|
|
37
|
+
uri = Path(path).resolve().as_uri() + "?mode=ro"
|
|
38
|
+
conn = sqlite3.connect(uri, uri=True, timeout=30)
|
|
39
|
+
conn.execute("PRAGMA busy_timeout = 30000")
|
|
40
|
+
return conn
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def integrity(path: Path) -> str:
|
|
44
|
+
"""'ok' or the first problem integrity_check reports."""
|
|
45
|
+
conn = _ro(path)
|
|
46
|
+
try:
|
|
47
|
+
rows = [r[0] for r in conn.execute("PRAGMA integrity_check")]
|
|
48
|
+
return "ok" if rows == ["ok"] else "; ".join(rows[:3])
|
|
49
|
+
finally:
|
|
50
|
+
conn.close()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def table_counts(path: Path) -> dict:
|
|
54
|
+
conn = _ro(path)
|
|
55
|
+
try:
|
|
56
|
+
names = [r[0] for r in conn.execute(
|
|
57
|
+
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' "
|
|
58
|
+
"AND name NOT LIKE 'memory_fts%' ORDER BY name")]
|
|
59
|
+
return {n: conn.execute(f'SELECT COUNT(*) FROM "{n}"').fetchone()[0] for n in names}
|
|
60
|
+
finally:
|
|
61
|
+
conn.close()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _copy(src: Path, dst: Path) -> None:
|
|
65
|
+
"""Online backup src -> dst (dst may be an existing database: it is replaced)."""
|
|
66
|
+
s = _ro(src)
|
|
67
|
+
try:
|
|
68
|
+
d = sqlite3.connect(str(dst), timeout=30)
|
|
69
|
+
try:
|
|
70
|
+
d.execute("PRAGMA busy_timeout = 30000")
|
|
71
|
+
s.backup(d)
|
|
72
|
+
finally:
|
|
73
|
+
d.close()
|
|
74
|
+
finally:
|
|
75
|
+
s.close()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def backup_now(db_path: Path, dest_dir: Optional[Path] = None, prune: bool = True,
|
|
79
|
+
label: Optional[str] = None, now: Optional[datetime] = None) -> dict:
|
|
80
|
+
db_path = Path(db_path)
|
|
81
|
+
if not db_path.is_file():
|
|
82
|
+
raise BackupError(f"database not found: {db_path}")
|
|
83
|
+
dest_dir = Path(dest_dir) if dest_dir else paths.backup_dir()
|
|
84
|
+
private_dir(dest_dir) # owner-only when FlowState makes it (audit D9)
|
|
85
|
+
now = now or datetime.now()
|
|
86
|
+
name = f"{PREFIX}{now:%Y%m%d-%H%M%S}" + (f"-{label}" if label else "") + ".db"
|
|
87
|
+
final = dest_dir / name
|
|
88
|
+
n = 1
|
|
89
|
+
while final.exists():
|
|
90
|
+
final = dest_dir / name.replace(".db", f"-{n}.db")
|
|
91
|
+
n += 1
|
|
92
|
+
partial = final.with_name(final.name + ".partial")
|
|
93
|
+
try:
|
|
94
|
+
partial.unlink(missing_ok=True)
|
|
95
|
+
private_file(partial) # each copy owner-only from the start
|
|
96
|
+
_copy(db_path, partial)
|
|
97
|
+
check = integrity(partial)
|
|
98
|
+
except Exception as e: # noqa: BLE001
|
|
99
|
+
partial.unlink(missing_ok=True)
|
|
100
|
+
raise BackupError(f"backup failed: {type(e).__name__}: {e}") from e
|
|
101
|
+
if check != "ok":
|
|
102
|
+
partial.unlink(missing_ok=True)
|
|
103
|
+
raise BackupError(f"backup copy failed its integrity check ({check}); nothing kept")
|
|
104
|
+
partial.replace(final)
|
|
105
|
+
removed = prune_backups(dest_dir, now, also_keep=final) if prune else []
|
|
106
|
+
return {"path": final, "integrity": check, "size": final.stat().st_size, "removed": removed}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def list_backups(dest_dir: Path) -> list[tuple[datetime, Path]]:
|
|
110
|
+
out = []
|
|
111
|
+
for p in Path(dest_dir).glob(PREFIX + "*.db"):
|
|
112
|
+
m = _BACKUP_NAME.match(p.name)
|
|
113
|
+
if m:
|
|
114
|
+
out.append((datetime.strptime(m.group(1) + m.group(2), "%Y%m%d%H%M%S"), p))
|
|
115
|
+
return sorted(out, reverse=True)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def is_safety_copy(path: Path) -> bool:
|
|
119
|
+
"""A copy taken right before a restore, a migration or a bulk / approved change."""
|
|
120
|
+
m = _BACKUP_NAME.match(Path(path).name)
|
|
121
|
+
label = (m.group(3) or "") if m else ""
|
|
122
|
+
return any(label == s or label.startswith(s + "-") for s in SAFETY_LABELS)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def retention_keep(items: list[tuple[datetime, Path]], daily: int = KEEP_DAILY,
|
|
126
|
+
weekly: int = KEEP_WEEKLY, now: Optional[datetime] = None) -> set[Path]:
|
|
127
|
+
"""Which backups to keep: newest per day (last `daily` days that have backups)
|
|
128
|
+
plus newest per ISO week (last `weekly` weeks that have backups), plus every safety copy
|
|
129
|
+
younger than SAFETY_KEEP_DAYS."""
|
|
130
|
+
now = now or datetime.now()
|
|
131
|
+
keep = {p for ts, p in items
|
|
132
|
+
if is_safety_copy(p) and now - ts < timedelta(days=SAFETY_KEEP_DAYS)}
|
|
133
|
+
days, weeks = [], []
|
|
134
|
+
for ts, p in sorted(items, reverse=True):
|
|
135
|
+
d = ts.date()
|
|
136
|
+
if d not in days:
|
|
137
|
+
days.append(d)
|
|
138
|
+
if len(days) <= daily:
|
|
139
|
+
keep.add(p)
|
|
140
|
+
w = ts.isocalendar()[:2]
|
|
141
|
+
if w not in weeks:
|
|
142
|
+
weeks.append(w)
|
|
143
|
+
if len(weeks) <= weekly:
|
|
144
|
+
keep.add(p)
|
|
145
|
+
return keep
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def prune_backups(dest_dir: Path, now: Optional[datetime] = None,
|
|
149
|
+
also_keep: Optional[Path] = None) -> list[Path]:
|
|
150
|
+
"""Delete backups the retention rule doesn't keep (never `also_keep`, the copy just made:
|
|
151
|
+
two backups in the same second used to let the newer one remove itself)."""
|
|
152
|
+
items = list_backups(dest_dir)
|
|
153
|
+
keep = retention_keep(items, now=now) | ({also_keep} if also_keep else set())
|
|
154
|
+
removed = []
|
|
155
|
+
for _ts, p in items:
|
|
156
|
+
if p not in keep:
|
|
157
|
+
p.unlink()
|
|
158
|
+
removed.append(p)
|
|
159
|
+
return removed
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def verify_db(path: Path, expected_counts: Optional[dict] = None) -> None:
|
|
163
|
+
check = integrity(path)
|
|
164
|
+
if check != "ok":
|
|
165
|
+
raise BackupError(f"{path.name} failed its integrity check ({check})")
|
|
166
|
+
counts = table_counts(path)
|
|
167
|
+
if "projects" not in counts:
|
|
168
|
+
raise BackupError(f"{path.name} is not a FlowState database (no projects table)")
|
|
169
|
+
if expected_counts is not None and counts != expected_counts:
|
|
170
|
+
diff = sorted(k for k in set(counts) | set(expected_counts)
|
|
171
|
+
if counts.get(k) != expected_counts.get(k))
|
|
172
|
+
raise BackupError(f"restored copy differs from the backup in: {', '.join(diff[:8])}")
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def restore(backup_file: Path, target: Path, force: bool = False,
|
|
176
|
+
backup_dir: Optional[Path] = None) -> dict:
|
|
177
|
+
backup_file, target = Path(backup_file), Path(target)
|
|
178
|
+
if not backup_file.is_file():
|
|
179
|
+
raise BackupError(f"backup not found: {backup_file}")
|
|
180
|
+
if backup_file.resolve() == target.resolve():
|
|
181
|
+
raise BackupError("backup and target are the same file")
|
|
182
|
+
verify_db(backup_file)
|
|
183
|
+
expected = table_counts(backup_file)
|
|
184
|
+
pre = None
|
|
185
|
+
if target.exists():
|
|
186
|
+
if not force:
|
|
187
|
+
raise BackupError(
|
|
188
|
+
f"{target} already exists. Restore into a new file (use --to with a new "
|
|
189
|
+
f"name), or add --force to replace it (a backup of it is taken first).")
|
|
190
|
+
pre = backup_now(target, backup_dir, prune=False, label="pre-restore")["path"]
|
|
191
|
+
_copy(backup_file, target)
|
|
192
|
+
else:
|
|
193
|
+
private_dir(target.parent)
|
|
194
|
+
partial = target.with_name(target.name + ".partial")
|
|
195
|
+
partial.unlink(missing_ok=True)
|
|
196
|
+
private_file(partial)
|
|
197
|
+
_copy(backup_file, partial)
|
|
198
|
+
partial.replace(target)
|
|
199
|
+
verify_db(target, expected)
|
|
200
|
+
return {"restored_to": target, "pre_restore_backup": pre,
|
|
201
|
+
"tables": len(expected), "projects": expected.get("projects", 0)}
|
flowstate/brief.py
ADDED
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
"""Project resolution and the start-of-conversation brief (standard cap 4,000 characters;
|
|
2
|
+
quick 1,500, deep 12,000; hard rules are never cut)."""
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
import sqlite3
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Optional, Union
|
|
8
|
+
|
|
9
|
+
from . import dbconn
|
|
10
|
+
from .autosession import SKIP_TAG
|
|
11
|
+
|
|
12
|
+
BRIEF_CAP = 4000
|
|
13
|
+
|
|
14
|
+
_PRIORITY = "CASE priority WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 ELSE 3 END"
|
|
15
|
+
_SEVERITY = "CASE severity WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 ELSE 3 END"
|
|
16
|
+
_OPEN_TODO = "(status IS NULL OR status IN ('pending', 'in_progress', 'blocked'))"
|
|
17
|
+
_OPEN_PROBLEM = "(status IS NULL OR status NOT IN ('solved', 'wont_fix', 'closed'))"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _conn(db_path: Path) -> sqlite3.Connection:
|
|
21
|
+
conn = dbconn.connect(str(db_path), timeout=5.0)
|
|
22
|
+
conn.row_factory = sqlite3.Row
|
|
23
|
+
conn.execute("PRAGMA busy_timeout = 5000")
|
|
24
|
+
return conn
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _norm(s: str) -> str:
|
|
28
|
+
return re.sub(r"[^a-z0-9]", "", (s or "").lower())
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _one_line(s: Optional[str], n: int) -> str:
|
|
32
|
+
s = " ".join((s or "").split())
|
|
33
|
+
return s if len(s) <= n else s[: n - 3].rstrip() + "..."
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ---------------------------------------------------------------- projects
|
|
37
|
+
def resolve_project(db_path: Path, project: Union[str, int, None] = None,
|
|
38
|
+
folder: Optional[str] = None, fuzzy: bool = True) -> dict:
|
|
39
|
+
"""Find one project. Returns {"project": row-dict} or {"candidates": [...], "reason": ...}.
|
|
40
|
+
|
|
41
|
+
Order: numeric id -> exact name (case-insensitive) -> normalised name ->
|
|
42
|
+
folder basename (normalised) -> (fuzzy only) unique substring match.
|
|
43
|
+
"""
|
|
44
|
+
conn = _conn(db_path)
|
|
45
|
+
try:
|
|
46
|
+
rows = [dict(r) for r in conn.execute(
|
|
47
|
+
"SELECT id, name, status, description FROM projects ORDER BY updated_at DESC, id DESC")]
|
|
48
|
+
finally:
|
|
49
|
+
conn.close()
|
|
50
|
+
|
|
51
|
+
def pick(matches: list, why: str) -> Optional[dict]:
|
|
52
|
+
if len(matches) == 1:
|
|
53
|
+
return {"project": matches[0]}
|
|
54
|
+
if len(matches) > 1:
|
|
55
|
+
return {"candidates": [m["name"] for m in matches], "reason": f"ambiguous {why}"}
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
wanted = project
|
|
59
|
+
if isinstance(wanted, str) and wanted.strip().lstrip("#").isdigit():
|
|
60
|
+
wanted = int(wanted.strip().lstrip("#"))
|
|
61
|
+
if isinstance(wanted, int) and not isinstance(wanted, bool):
|
|
62
|
+
hit = [r for r in rows if r["id"] == wanted]
|
|
63
|
+
return pick(hit, "id") or {"candidates": _active_names(rows),
|
|
64
|
+
"reason": f"no project with id {wanted}"}
|
|
65
|
+
|
|
66
|
+
keys = []
|
|
67
|
+
if isinstance(wanted, str) and wanted.strip():
|
|
68
|
+
keys.append(("name", wanted.strip()))
|
|
69
|
+
if folder and str(folder).strip():
|
|
70
|
+
base = re.split(r"[\\/]+", str(folder).strip().rstrip("\\/"))[-1]
|
|
71
|
+
if base:
|
|
72
|
+
keys.append(("folder", base))
|
|
73
|
+
if not keys:
|
|
74
|
+
return {"candidates": _active_names(rows), "reason": "no project given"}
|
|
75
|
+
|
|
76
|
+
for kind, key in keys:
|
|
77
|
+
r = (pick([x for x in rows if x["name"].lower() == key.lower()], kind)
|
|
78
|
+
or pick([x for x in rows if _norm(x["name"]) == _norm(key)], kind))
|
|
79
|
+
if r:
|
|
80
|
+
return r
|
|
81
|
+
if fuzzy and len(_norm(key)) >= 3:
|
|
82
|
+
r = pick([x for x in rows if _norm(key) in _norm(x["name"])], kind)
|
|
83
|
+
if r:
|
|
84
|
+
return r
|
|
85
|
+
return {"candidates": _active_names(rows), "reason": f"no project matches '{keys[0][1]}'"}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _active_names(rows: list, limit: int = 60) -> list:
|
|
89
|
+
active = [r["name"] for r in rows if r.get("status") in (None, "active")]
|
|
90
|
+
rest = [r["name"] for r in rows if r.get("status") not in (None, "active")]
|
|
91
|
+
return (active + rest)[:limit]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ---------------------------------------------------------------- brief
|
|
95
|
+
class _Budget:
|
|
96
|
+
def __init__(self, cap: int):
|
|
97
|
+
self.cap = cap
|
|
98
|
+
self.lines: list[str] = []
|
|
99
|
+
self.used = 0
|
|
100
|
+
|
|
101
|
+
def add(self, line: str) -> bool:
|
|
102
|
+
need = len(line) + 1
|
|
103
|
+
if self.used + need > self.cap:
|
|
104
|
+
return False
|
|
105
|
+
self.lines.append(line)
|
|
106
|
+
self.used += need
|
|
107
|
+
return True
|
|
108
|
+
|
|
109
|
+
def remaining(self) -> int:
|
|
110
|
+
return self.cap - self.used
|
|
111
|
+
|
|
112
|
+
def text(self) -> str:
|
|
113
|
+
return "\n".join(self.lines)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# Brief sizes (E4). standard is the brief as it always was; quick is for a fast check-in;
|
|
117
|
+
# deep is for picking a project back up after a long break. Section = (max items, max chars).
|
|
118
|
+
SIZES = {
|
|
119
|
+
"quick": {"cap": 1500, "todos": (5, 520), "problems": (3, 260), "changes": (0, 0),
|
|
120
|
+
"decisions": (2, 260), "learnings": (0, 0), "linked": False, "stale": False},
|
|
121
|
+
"standard": {"cap": BRIEF_CAP, "todos": (15, 1100), "problems": (6, 500), "changes": (8, 900),
|
|
122
|
+
"decisions": (5, 450), "learnings": (8, 900), "linked": True, "stale": True},
|
|
123
|
+
"deep": {"cap": 12000, "todos": (40, 3600), "problems": (15, 1500), "changes": (20, 2200),
|
|
124
|
+
"decisions": (12, 1500), "learnings": (20, 2600), "linked": True, "stale": True},
|
|
125
|
+
}
|
|
126
|
+
SIZE_NAMES = tuple(SIZES)
|
|
127
|
+
_MORE = " ...(handoff list shows it all)"
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _exposure_lines() -> list:
|
|
131
|
+
try:
|
|
132
|
+
from .remote_auth import exposure_lines
|
|
133
|
+
return exposure_lines()
|
|
134
|
+
except Exception: # noqa: BLE001 - a warning line never breaks the brief
|
|
135
|
+
return []
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def build_brief(db_path: Path, project: dict, session: Optional[dict] = None,
|
|
139
|
+
cap: Optional[int] = None, size: str = "standard",
|
|
140
|
+
shown: Optional[list] = None, since: Optional[str] = None,
|
|
141
|
+
remind: Optional[str] = None) -> str:
|
|
142
|
+
"""Plain-text brief: hard rules, handoff notes, open todos, open problems, recent changes
|
|
143
|
+
and decisions, key learnings. Sections are filled within budgets; the result never
|
|
144
|
+
exceeds the size's cap, except that the hard rules are never cut: if they alone would not
|
|
145
|
+
fit, the cap grows just enough to show them (they are bounded at 2,000 characters).
|
|
146
|
+
`shown` (a list) receives "type:id" of every record the brief shows (the run ledger);
|
|
147
|
+
`since` is the one "since your last visit" line (ledger.since_line), if any.
|
|
148
|
+
`remind` is the one line when the previous session read this project and saved nothing."""
|
|
149
|
+
shown = shown if shown is not None else []
|
|
150
|
+
from . import claims, conflicts, handoffs, links, priority, provenance, review_mode, rules
|
|
151
|
+
size = size if size in SIZES else "standard"
|
|
152
|
+
prof = SIZES[size]
|
|
153
|
+
cap = cap or prof["cap"]
|
|
154
|
+
pid, name = project["id"], project["name"]
|
|
155
|
+
conn = _conn(db_path)
|
|
156
|
+
try:
|
|
157
|
+
q = lambda sql, *a: [dict(r) for r in conn.execute(sql, a)]
|
|
158
|
+
n_todo, n_prob, n_chg, n_dec, n_learn = (prof[k][0] for k in
|
|
159
|
+
("todos", "problems", "changes", "decisions", "learnings"))
|
|
160
|
+
rule_lines = rules.brief_lines(conn, pid)
|
|
161
|
+
handoff_lines = handoffs.brief_lines(conn, pid)
|
|
162
|
+
todo_total = q(f"SELECT COUNT(*) n FROM todos WHERE project_id=? AND {_OPEN_TODO}", pid)[0]["n"]
|
|
163
|
+
todos = q(f"""SELECT id, title, priority, status FROM todos WHERE project_id=? AND {_OPEN_TODO}
|
|
164
|
+
ORDER BY {_PRIORITY}, CASE status WHEN 'in_progress' THEN 0 ELSE 1 END, id DESC
|
|
165
|
+
LIMIT ?""", pid, n_todo)
|
|
166
|
+
claimed = claims.active(conn, [t["id"] for t in todos])
|
|
167
|
+
if claimed:
|
|
168
|
+
mine, now = claims.me()["holder"], claims.utcnow()
|
|
169
|
+
claimed = {k: claims.describe(r, mine, now) for k, r in claimed.items()}
|
|
170
|
+
prob_total = q(f"""SELECT COUNT(*) n FROM problems p JOIN components c ON c.id=p.component_id
|
|
171
|
+
WHERE c.project_id=? AND {_OPEN_PROBLEM.replace('status', 'p.status')}""",
|
|
172
|
+
pid)[0]["n"]
|
|
173
|
+
problems = q(f"""SELECT p.id, p.title, p.severity FROM problems p
|
|
174
|
+
JOIN components c ON c.id=p.component_id
|
|
175
|
+
WHERE c.project_id=? AND {_OPEN_PROBLEM.replace('status', 'p.status')}
|
|
176
|
+
ORDER BY {_SEVERITY.replace('severity', 'p.severity')}, p.id DESC LIMIT ?""",
|
|
177
|
+
pid, n_prob)
|
|
178
|
+
changes = q("""SELECT ch.id, ch.created_at, c.name comp, ch.field_name, ch.new_value, ch.reason
|
|
179
|
+
FROM changes ch JOIN components c ON c.id=ch.component_id
|
|
180
|
+
WHERE c.project_id=? ORDER BY ch.created_at DESC, ch.id DESC LIMIT ?""",
|
|
181
|
+
pid, n_chg)
|
|
182
|
+
decisions = q("""SELECT id, created_at, user_prompt_summary, key_decisions FROM conversations
|
|
183
|
+
WHERE project_id=? AND key_decisions IS NOT NULL
|
|
184
|
+
ORDER BY created_at DESC, id DESC LIMIT ?""", pid, n_dec + 20)
|
|
185
|
+
# A decision replaced by a newer one is no longer true: show only the current one.
|
|
186
|
+
replaced = links.superseded_decisions(conn)
|
|
187
|
+
replaces = {new: old for old, (new, _since) in replaced.items()}
|
|
188
|
+
decisions = [d for d in decisions if d["id"] not in replaced][:n_dec]
|
|
189
|
+
# An open possible conflict: neither side is settled. The newer one stays, tagged;
|
|
190
|
+
# the older one's text is left out (one pointer per older one, which search reaches).
|
|
191
|
+
disputed, against = {}, {} # older id -> newer ids; newer id -> older ids
|
|
192
|
+
pairs = [(r["new_id"], r["old_id"]) for r in conflicts.open_pairs(conn, pid)]
|
|
193
|
+
pairs += [p for p in conflicts.card_pairs(conn, pid) if p not in pairs] # N-F16
|
|
194
|
+
for new_id, old_id in pairs:
|
|
195
|
+
disputed.setdefault(old_id, []).append(new_id)
|
|
196
|
+
against.setdefault(new_id, []).append(old_id)
|
|
197
|
+
linked = links.brief_lines(conn, pid) if prof["linked"] else []
|
|
198
|
+
alerts = links.alert_lines(conn, pid)
|
|
199
|
+
conflict_line = conflicts.brief_line(conn, pid)
|
|
200
|
+
from . import conflict_cards
|
|
201
|
+
card_line = conflict_cards.brief_line(conn, pid)
|
|
202
|
+
card_hint = conflict_cards.brief_hint(conn, pid, name)
|
|
203
|
+
from . import review_cards
|
|
204
|
+
card_hint = review_cards.brief_hint(conn, pid, name, card_hint)
|
|
205
|
+
mode_line = review_mode.brief_line(db_path, pid) if review_mode.available(conn) else None
|
|
206
|
+
from .deletes import recent_line
|
|
207
|
+
deleted_line = recent_line(conn, pid, name)
|
|
208
|
+
learnings = q("""SELECT id, category, insight, verified FROM learnings WHERE project_id=?
|
|
209
|
+
ORDER BY verified DESC, created_at DESC, id DESC LIMIT ?""", pid, n_learn)
|
|
210
|
+
meta = {k: provenance.get(conn, k, [r["id"] for r in rows]) for k, rows in
|
|
211
|
+
(("todo", todos), ("change", changes), ("decision", decisions), ("learning", learnings))}
|
|
212
|
+
# Auto-captured summaries aren't final until the user approves them; a session that
|
|
213
|
+
# saved nothing new (autosession.SKIP_TAG) isn't worth a line.
|
|
214
|
+
last = q("""SELECT started_at, ended_at, summary FROM sessions
|
|
215
|
+
WHERE project_id=? AND ended_at IS NOT NULL AND summary IS NOT NULL
|
|
216
|
+
AND summary NOT LIKE '[auto-captured%' AND summary NOT LIKE ?
|
|
217
|
+
ORDER BY ended_at DESC, id DESC LIMIT 1""", pid, SKIP_TAG + "%")
|
|
218
|
+
has_queue = conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' "
|
|
219
|
+
"AND name='review_items'").fetchone() is not None
|
|
220
|
+
pending = q("SELECT COUNT(*) n FROM review_items WHERE project_id=? AND status='pending'",
|
|
221
|
+
pid)[0]["n"] if has_queue else None
|
|
222
|
+
has_meta = provenance.available(conn)
|
|
223
|
+
finally:
|
|
224
|
+
conn.close()
|
|
225
|
+
stale_line = None
|
|
226
|
+
if prof["stale"] and has_meta:
|
|
227
|
+
try:
|
|
228
|
+
stale_line = provenance.brief_line(db_path, pid)
|
|
229
|
+
except Exception: # noqa: BLE001 - a nice-to-have line never breaks the brief
|
|
230
|
+
stale_line = None
|
|
231
|
+
|
|
232
|
+
head = f"FlowState brief: {name} (project #{pid}, {project.get('status') or 'active'})"
|
|
233
|
+
if size != "standard":
|
|
234
|
+
head += f" [{size}]"
|
|
235
|
+
rules_len = sum(len(x) + 1 for x in [head] + rule_lines)
|
|
236
|
+
# Hard rules are never cut; everything else gives way. If the rules alone don't fit the
|
|
237
|
+
# size, the cap grows just enough for them plus a little (a handoff note, the footer).
|
|
238
|
+
cap = max(cap, rules_len + 600)
|
|
239
|
+
b = _Budget(cap - 40) # room for the final "(truncated)" marker, just in case
|
|
240
|
+
b.add(head)
|
|
241
|
+
for line in rule_lines: # always, in full (bounded when they are added)
|
|
242
|
+
b.lines.append(line)
|
|
243
|
+
b.used += len(line) + 1
|
|
244
|
+
_note(shown, "rule", _RULE_ID.match(line))
|
|
245
|
+
if handoff_lines:
|
|
246
|
+
# right after the rules; trimmed only so that some room is left for the rest, but
|
|
247
|
+
# never squeezed out entirely
|
|
248
|
+
room = max(b.remaining() - min(1200, b.cap // 3), min(b.remaining(), 500))
|
|
249
|
+
for line in handoff_lines:
|
|
250
|
+
if len(line) + 1 > room:
|
|
251
|
+
cut = room - 1 - len(_MORE)
|
|
252
|
+
if cut > 60:
|
|
253
|
+
b.add(line[:cut].rstrip() + _MORE)
|
|
254
|
+
break
|
|
255
|
+
if b.add(line):
|
|
256
|
+
_note(shown, "handoff", _HANDOFF_ID.match(line))
|
|
257
|
+
room -= len(line) + 1
|
|
258
|
+
for line in _exposure_lines(): # a remote token sent over the plain LAN (audit N-F27)
|
|
259
|
+
b.add(line)
|
|
260
|
+
if session:
|
|
261
|
+
b.add(f"Session #{session['session_id']} is open for you (opened automatically; "
|
|
262
|
+
f"closes itself when idle). Log as you work: "
|
|
263
|
+
f"log_work(project=\"{name}\", kind=decision|change|problem|learning|todo, summary=...).")
|
|
264
|
+
if remind:
|
|
265
|
+
b.add(remind)
|
|
266
|
+
if since:
|
|
267
|
+
b.add(since)
|
|
268
|
+
if pending is not None:
|
|
269
|
+
where = ""
|
|
270
|
+
if pending: # the local page (started on first need) and the phone link (waiting.py)
|
|
271
|
+
from .waiting import where_line
|
|
272
|
+
where = where_line(db_path)
|
|
273
|
+
b.add(f"Review queue: {pending} item{'s' if pending != 1 else ''} waiting for the user's OK"
|
|
274
|
+
+ (" (manage_review action=list shows them; approve or reject only when the user asks)."
|
|
275
|
+
+ where if pending else "."))
|
|
276
|
+
if mode_line:
|
|
277
|
+
b.add(mode_line)
|
|
278
|
+
if deleted_line:
|
|
279
|
+
b.add(deleted_line)
|
|
280
|
+
if conflict_line:
|
|
281
|
+
b.add(conflict_line)
|
|
282
|
+
if card_hint:
|
|
283
|
+
b.add(card_hint)
|
|
284
|
+
if stale_line:
|
|
285
|
+
b.add(_one_line(stale_line, 300))
|
|
286
|
+
|
|
287
|
+
def section(title: str, items: list, total: int, fmt, share: int, kind: str):
|
|
288
|
+
if not items:
|
|
289
|
+
return
|
|
290
|
+
stop = b.used + share
|
|
291
|
+
header = f"\n{title} ({len(items)} of {total}):" if total > len(items) else f"\n{title}:"
|
|
292
|
+
if not b.add(header):
|
|
293
|
+
return
|
|
294
|
+
for it in items:
|
|
295
|
+
line = fmt(it)
|
|
296
|
+
if b.used + len(line) + 1 > stop or not b.add(line):
|
|
297
|
+
break
|
|
298
|
+
if not it.get("_left_out"):
|
|
299
|
+
shown.append(f"{kind}:{it['id']}")
|
|
300
|
+
|
|
301
|
+
tag = lambda kind, rid: provenance.tag(meta[kind].get(rid))
|
|
302
|
+
from .stored import END, START
|
|
303
|
+
# Lines apps wrote (the project's description, linked-project alerts, the last session's
|
|
304
|
+
# summary) sit inside the fence with the records (task 56, N7), after the card line
|
|
305
|
+
written = ([_one_line(project["description"], 200)] if project.get("description") else []) \
|
|
306
|
+
+ list(alerts) + ([f"Last session ({(last[0]['ended_at'] or '')[:10]}): "
|
|
307
|
+
f"{_one_line(last[0]['summary'], 280)}"] if last else [])
|
|
308
|
+
marked = any((todos, problems, changes, decisions, learnings, card_line, written)) \
|
|
309
|
+
and b.add("\n" + START) # audit D6: stored text is data, not instructions
|
|
310
|
+
fence = (len(b.lines) - 1,) if marked else ()
|
|
311
|
+
if marked and card_line: # its topic is an app's words: inside the fence (N-F16)
|
|
312
|
+
b.add(_one_line(card_line, 240))
|
|
313
|
+
for line in written if marked else ():
|
|
314
|
+
b.add(line)
|
|
315
|
+
section("Open todos", todos, todo_total,
|
|
316
|
+
lambda t: f"- [{priority.label(t['priority'])}] #{t['id']} {_one_line(t['title'], 90)}"
|
|
317
|
+
+ (f" ({t['status']})" if t["status"] in ("in_progress", "blocked") else "")
|
|
318
|
+
+ (f" ({claimed[t['id']]})" if t["id"] in claimed else "")
|
|
319
|
+
+ tag("todo", t["id"]),
|
|
320
|
+
prof["todos"][1], "todo")
|
|
321
|
+
section("Open problems", problems, prob_total,
|
|
322
|
+
lambda p: f"- [{p['severity'] or 'medium'}] #{p['id']} {_one_line(p['title'], 90)}",
|
|
323
|
+
prof["problems"][1], "problem")
|
|
324
|
+
section("Recent changes", changes, len(changes),
|
|
325
|
+
lambda c: f"- {(c['created_at'] or '')[:10]} {_one_line(c['comp'], 30)}: "
|
|
326
|
+
f"{_one_line(c['field_name'], 70)}"
|
|
327
|
+
+ (f" - {_one_line(c['reason'] or c['new_value'], 90)}" if (c['reason'] or c['new_value']) else "")
|
|
328
|
+
+ tag("change", c["id"]),
|
|
329
|
+
prof["changes"][1], "change")
|
|
330
|
+
listed, pointed = {d["id"] for d in decisions}, set()
|
|
331
|
+
for d in decisions:
|
|
332
|
+
day = (d["created_at"] or "")[:10]
|
|
333
|
+
if d["id"] in disputed:
|
|
334
|
+
pointed.add(d["id"])
|
|
335
|
+
d["_left_out"] = True
|
|
336
|
+
d["_line"] = (f"- {day} #{d['id']} in dispute with {_ids(disputed[d['id']])}, "
|
|
337
|
+
f"text left out: {_lookup(d['id'])}")
|
|
338
|
+
continue
|
|
339
|
+
extra = ""
|
|
340
|
+
if d["id"] in against:
|
|
341
|
+
far = [o for o in against[d["id"]] if o not in listed and o not in pointed]
|
|
342
|
+
pointed.update(far[:1]) # one pointer per line; the Possible conflicts line has all
|
|
343
|
+
extra = (f" (unsettled: may conflict with {_ids(against[d['id']])}"
|
|
344
|
+
+ "".join(f"; #{o} in dispute: {_lookup(o)}" for o in far[:1]) + ")")
|
|
345
|
+
d["_line"] = (f"- {day} #{d['id']} {_one_line(_first_decision(d), 100 if extra else 140)}"
|
|
346
|
+
+ (f" (replaces #{replaces[d['id']]})" if d["id"] in replaces else "")
|
|
347
|
+
+ extra + tag("decision", d["id"]))
|
|
348
|
+
section("Recent decisions", decisions, len(decisions), lambda d: d["_line"],
|
|
349
|
+
prof["decisions"][1], "decision")
|
|
350
|
+
section("Key learnings", learnings, len(learnings),
|
|
351
|
+
lambda l: f"- [{l['category'] or 'other'}{', verified' if l['verified'] else ''}] "
|
|
352
|
+
f"{_one_line(l['insight'], 160)}" + tag("learning", l["id"]),
|
|
353
|
+
prof["learnings"][1], "learning")
|
|
354
|
+
if marked and b.add(END):
|
|
355
|
+
fence += (len(b.lines) - 1,)
|
|
356
|
+
footer = ("\nMore detail: manage_todos(action=list), manage_problems(action=list), "
|
|
357
|
+
"search (answer=true to ask).")
|
|
358
|
+
if size != "deep":
|
|
359
|
+
footer += " Longer brief: start_here(size=\"deep\")."
|
|
360
|
+
# Linked projects last, from whatever is left: this is what gets trimmed, never the
|
|
361
|
+
# project's own items above.
|
|
362
|
+
if linked and b.remaining() > len(footer) + 80:
|
|
363
|
+
room = _Budget(b.remaining() - len(footer) - 1)
|
|
364
|
+
if room.add("\nLinked projects:") and any([room.add(ln) for ln in linked]):
|
|
365
|
+
for ln in room.lines:
|
|
366
|
+
b.add(ln)
|
|
367
|
+
b.add(footer)
|
|
368
|
+
|
|
369
|
+
from .stored import unfence # a fake START / END in stored text can't move the fence (N-F29)
|
|
370
|
+
text = "\n".join(ln if i in fence else unfence(ln) for i, ln in enumerate(b.lines))
|
|
371
|
+
if len(text) > cap: # cannot happen by construction; belt and braces
|
|
372
|
+
text = text[: cap - 16] + "\n...(truncated)"
|
|
373
|
+
return text
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
_RULE_ID = re.compile(r"^- R(\d+)[ :]")
|
|
377
|
+
_HANDOFF_ID = re.compile(r"^- H(\d+) \(")
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _ids(ids: list) -> str:
|
|
381
|
+
"""#12, #9 (+2 more): at most two, so a tag stays short."""
|
|
382
|
+
more = f" (+{len(ids) - 2} more)" if len(ids) > 2 else ""
|
|
383
|
+
return ", ".join(f"#{i}" for i in ids[:2]) + more
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _lookup(rid: int) -> str:
|
|
387
|
+
return f'search(query="D{rid}")'
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _note(shown: list, kind: str, m) -> None:
|
|
391
|
+
if m:
|
|
392
|
+
shown.append(f"{kind}:{m.group(1)}")
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _first_decision(d: dict) -> str:
|
|
396
|
+
import json
|
|
397
|
+
try:
|
|
398
|
+
items = json.loads(d.get("key_decisions") or "[]")
|
|
399
|
+
if items:
|
|
400
|
+
return str(items[0])
|
|
401
|
+
except (ValueError, TypeError):
|
|
402
|
+
pass
|
|
403
|
+
return d.get("user_prompt_summary") or ""
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def candidates_text(resolution: dict, cap: int = BRIEF_CAP) -> str:
|
|
407
|
+
"""Brief-sized reply when no single project matched."""
|
|
408
|
+
b = _Budget(cap - 40)
|
|
409
|
+
b.add(f"FlowState: {resolution.get('reason', 'no project chosen')}.")
|
|
410
|
+
names = resolution.get("candidates", [])
|
|
411
|
+
if not names:
|
|
412
|
+
b.add("There are no projects yet. Create one with manage_projects(action=\"create\", "
|
|
413
|
+
"name=\"<name>\") when the user starts new work.")
|
|
414
|
+
return b.text()
|
|
415
|
+
b.add("Call start_here again with project=\"<name>\" (or manage_projects(action=\"create\") if this is new work).")
|
|
416
|
+
b.add("Projects:")
|
|
417
|
+
for n in names:
|
|
418
|
+
if not b.add(f"- {n}"):
|
|
419
|
+
break
|
|
420
|
+
return b.text()
|