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.
Files changed (143) hide show
  1. flowstate/__init__.py +34 -0
  2. flowstate/__main__.py +7 -0
  3. flowstate/activity.py +224 -0
  4. flowstate/agent_guide.py +251 -0
  5. flowstate/app_keys.py +141 -0
  6. flowstate/approvals.py +974 -0
  7. flowstate/approve_page.py +565 -0
  8. flowstate/ask.py +107 -0
  9. flowstate/autosession.py +480 -0
  10. flowstate/backup.py +201 -0
  11. flowstate/brief.py +420 -0
  12. flowstate/card_offer.py +208 -0
  13. flowstate/card_taps.py +165 -0
  14. flowstate/card_trust.py +127 -0
  15. flowstate/claims.py +461 -0
  16. flowstate/cleanup.py +619 -0
  17. flowstate/cli.py +728 -0
  18. flowstate/cli_data.py +434 -0
  19. flowstate/cli_more.py +302 -0
  20. flowstate/cli_review.py +459 -0
  21. flowstate/cloudflared_check.py +49 -0
  22. flowstate/conflict_card_ui.py +286 -0
  23. flowstate/conflict_cards.py +1193 -0
  24. flowstate/conflict_reopen.py +320 -0
  25. flowstate/conflicts.py +420 -0
  26. flowstate/connections.py +33 -0
  27. flowstate/database.py +2191 -0
  28. flowstate/dbconn.py +308 -0
  29. flowstate/deletes.py +860 -0
  30. flowstate/embeddings.py +354 -0
  31. flowstate/erase.py +1047 -0
  32. flowstate/extras.py +71 -0
  33. flowstate/git_capture.py +157 -0
  34. flowstate/guard.py +224 -0
  35. flowstate/handoffs.py +168 -0
  36. flowstate/history.py +755 -0
  37. flowstate/history_page.py +276 -0
  38. flowstate/http_app.py +204 -0
  39. flowstate/identity.py +387 -0
  40. flowstate/install_name.py +140 -0
  41. flowstate/ledger.py +272 -0
  42. flowstate/legacy_args.py +65 -0
  43. flowstate/links.py +609 -0
  44. flowstate/markdown_io.py +242 -0
  45. flowstate/meaning.py +398 -0
  46. flowstate/memory_import.py +92 -0
  47. flowstate/migrations/001_auto_sessions.sql +16 -0
  48. flowstate/migrations/002_review_queue.sql +33 -0
  49. flowstate/migrations/003_links.sql +47 -0
  50. flowstate/migrations/004_review_mode.sql +24 -0
  51. flowstate/migrations/005_history.sql +21 -0
  52. flowstate/migrations/006_activity.sql +26 -0
  53. flowstate/migrations/007_meaning_index.sql +16 -0
  54. flowstate/migrations/008_git_capture.sql +12 -0
  55. flowstate/migrations/009_hard_rules.sql +13 -0
  56. flowstate/migrations/010_handoffs.sql +14 -0
  57. flowstate/migrations/011_record_meta.sql +13 -0
  58. flowstate/migrations/012_accountability.sql +71 -0
  59. flowstate/migrations/013_todo_claims.sql +36 -0
  60. flowstate/migrations/014_decision_conflicts.sql +41 -0
  61. flowstate/migrations/015_session_runs.sql +17 -0
  62. flowstate/migrations/016_write_receipts.sql +35 -0
  63. flowstate/migrations/017_run_views.sql +26 -0
  64. flowstate/migrations/018_run_views_upto.sql +4 -0
  65. flowstate/migrations/019_approvals.sql +47 -0
  66. flowstate/migrations/020_source_stamps.sql +10 -0
  67. flowstate/migrations/021_review_links.sql +11 -0
  68. flowstate/migrations/022_review_start_tickets.sql +10 -0
  69. flowstate/migrations/023_conflict_cards.sql +68 -0
  70. flowstate/migrations/024_rule_confirmations.sql +7 -0
  71. flowstate/migrations/025_confirmed_hash.sql +7 -0
  72. flowstate/migrations/__init__.py +149 -0
  73. flowstate/models.py +307 -0
  74. flowstate/names.py +157 -0
  75. flowstate/offsite.py +386 -0
  76. flowstate/offsite_crypto.py +272 -0
  77. flowstate/paths.py +265 -0
  78. flowstate/popup.py +238 -0
  79. flowstate/priority.py +66 -0
  80. flowstate/privatefs.py +476 -0
  81. flowstate/project_history.py +710 -0
  82. flowstate/provenance.py +696 -0
  83. flowstate/receipts.py +377 -0
  84. flowstate/relay/__init__.py +72 -0
  85. flowstate/relay/acme.py +271 -0
  86. flowstate/relay/api.py +164 -0
  87. flowstate/relay/cli.py +344 -0
  88. flowstate/relay/crypto.py +137 -0
  89. flowstate/relay/ct.py +118 -0
  90. flowstate/relay/runner.py +177 -0
  91. flowstate/relay/store.py +191 -0
  92. flowstate/relay/tunnel.py +413 -0
  93. flowstate/release_signers +14 -0
  94. flowstate/remote_auth.py +1219 -0
  95. flowstate/review.py +320 -0
  96. flowstate/review_apply.py +140 -0
  97. flowstate/review_card_ui.py +241 -0
  98. flowstate/review_cards.py +564 -0
  99. flowstate/review_mode.py +274 -0
  100. flowstate/review_page.py +1361 -0
  101. flowstate/review_phone.py +465 -0
  102. flowstate/review_tunnel.py +338 -0
  103. flowstate/routing.py +392 -0
  104. flowstate/rules.py +418 -0
  105. flowstate/safety.py +98 -0
  106. flowstate/saves.py +83 -0
  107. flowstate/scheduler.py +160 -0
  108. flowstate/schema.sql +713 -0
  109. flowstate/search.py +355 -0
  110. flowstate/secret_store.py +271 -0
  111. flowstate/secrets_scan.py +135 -0
  112. flowstate/selfupdate.py +1020 -0
  113. flowstate/server.py +1299 -0
  114. flowstate/session_contents.py +382 -0
  115. flowstate/session_records.py +629 -0
  116. flowstate/site_style.py +46 -0
  117. flowstate/stored.py +158 -0
  118. flowstate/story.py +442 -0
  119. flowstate/surface.py +173 -0
  120. flowstate/tasks.py +231 -0
  121. flowstate/term.py +40 -0
  122. flowstate/tool_labels.py +104 -0
  123. flowstate/tooldefs.py +383 -0
  124. flowstate/tools/__init__.py +118 -0
  125. flowstate/tools/core.py +545 -0
  126. flowstate/tools/files.py +416 -0
  127. flowstate/tools/git_ops.py +1081 -0
  128. flowstate/tools/intelligence.py +376 -0
  129. flowstate/tools/learning.py +282 -0
  130. flowstate/tools/problems.py +159 -0
  131. flowstate/tools/sessions.py +266 -0
  132. flowstate/tools/story.py +48 -0
  133. flowstate/tools/todos.py +79 -0
  134. flowstate/tools/utils.py +71 -0
  135. flowstate/tools/variables.py +345 -0
  136. flowstate/updates.py +482 -0
  137. flowstate/urls.py +7 -0
  138. flowstate/waiting.py +828 -0
  139. flowstate/who.py +302 -0
  140. flowstatemcp-2.5.0.dist-info/METADATA +88 -0
  141. flowstatemcp-2.5.0.dist-info/RECORD +143 -0
  142. flowstatemcp-2.5.0.dist-info/WHEEL +4 -0
  143. flowstatemcp-2.5.0.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,564 @@
1
+ """In-chat review cards for what waits in the review queue (2.4.4).
2
+
3
+ The disagreement card (conflict_cards.py) for every other kind: session summaries,
4
+ suggestions, imports, clean-ups, markdown edits, possible conflicts, settings, "did you say
5
+ this?" checks and deletes. Each card says what the item is, what saving it would do, which app
6
+ wrote it and when, with Approve and Reject (Reject asks for a short optional reason in the
7
+ card itself). Disagreements keep their own card: show_review_card points to
8
+ show_conflict_card for them.
9
+
10
+ The same two tools as the disagreement card, built the same way and listed only to hosts that
11
+ advertise MCP Apps (conflict_cards.with_app_tool): show_review_card (model-visible, read-only;
12
+ its definition names ui://flowstate/review-card.html) and resolve_review_card (app-only, the
13
+ buttons). The safety rules are the disagreement card's:
14
+
15
+ - resolve_review_card refuses chat text (user_request, message, text, reason; only the card's
16
+ own reject_reason is taken) and clients without MCP Apps (not_a_card_tap);
17
+ - only apps on the user's card list get the cards and their tap tool (card_trust.py); over
18
+ the relay that is the connector's own sign-in name, added by the user. A tap with the
19
+ card's one-use code then counts as on this computer or the tunnel (task 65): chat approvals
20
+ (default phone only) gate the AI's manage_review approve / reject, not the card's buttons;
21
+ - an item only the user decides (approvals.user_only: a delete or turning review off queued
22
+ with approvals on, every "did you say this?" check), and every delete, is shown without
23
+ buttons, with the phone or review-page link, and refused if resolve is called anyway;
24
+ - a decision goes through the same apply functions as manage_review (review_apply.py) and
25
+ is logged in approval_log with path "card", whatever the kind;
26
+ - a session summary's records each have Keep / Remove / Bring back (session_records.py):
27
+ the same tool with decision keep_record / remove_record / restore_record and `record`,
28
+ after the same checks, recorded as a tap on the card ("card (<app>)", card_trust.label),
29
+ as Approve / Reject / Keep all are.
30
+
31
+ Card taps are not cryptographically proven to be a person, as with the disagreement card.
32
+ """
33
+
34
+ import json
35
+ from pathlib import Path
36
+ from typing import Callable, Optional
37
+
38
+ from . import approvals, identity, review
39
+ from .conflict_cards import _connect, _pretty, client_has_ui, own_refusal, taps_for, tap_refusal
40
+
41
+ SHOW_MAX = 5
42
+ REASON_MAX = 300
43
+ DETAILS_MAX = 600
44
+ DEFAULT_REASON = "Rejected on the review card."
45
+ _SUGGESTED = {"decision": "decision", "change": "change", "problem": "problem",
46
+ "learning": "learning", "todo": "todo"}
47
+ NOT_TAP = "A review card is decided by its buttons, not by chat text."
48
+
49
+
50
+ def _payload(it: dict) -> dict:
51
+ try:
52
+ p = json.loads(it.get("payload") or "{}")
53
+ return p if isinstance(p, dict) else {}
54
+ except ValueError:
55
+ return {}
56
+
57
+
58
+ def locked(it: dict) -> bool:
59
+ """No buttons in the chat: only the user decides it (approvals.user_only), and every
60
+ delete (a whole project needs its name typed; the review page and phone ask for that)."""
61
+ if it.get("kind") == "reopen_conflict": # the user's alone, but a card tap is theirs too
62
+ return False
63
+ return approvals.user_only(it) or it.get("kind") == "delete"
64
+
65
+
66
+ def _cut(text, n: int) -> str:
67
+ text = " ".join(str(text or "").split())
68
+ return text if len(text) <= n else text[:n - 3].rstrip() + "..."
69
+
70
+
71
+ def _who(it: dict) -> str:
72
+ if it.get("app"):
73
+ return identity.shown_row(it)
74
+ src = str(it.get("source") or "")
75
+ if src.startswith("import:"):
76
+ return "an import from " + (src.split(":", 1)[1] or "a file")
77
+ return src or "an app"
78
+
79
+
80
+ def _sentence(text: str) -> str:
81
+ text = (text or "").strip()
82
+ return (text[:1].upper() + text[1:]) if text else text
83
+
84
+
85
+ def _words(it: dict, project: str, db_path: Path) -> dict:
86
+ """title, kind label, what approving / rejecting does, and the two button labels."""
87
+ kind, p = it["kind"], _payload(it)
88
+ reject = "Reject marks it rejected and saves nothing; it stays listed as rejected."
89
+ if kind == "session_summary": # Keep all once records are listed (view())
90
+ return {"title": review.KEEP_QUESTION, "kind_label": "Session summary",
91
+ "does": review.KEEP_HOW, "approve_label": review.KEEP,
92
+ "reject_label": review.DONT_KEEP}
93
+ if kind in _SUGGESTED:
94
+ what = _SUGGESTED[kind]
95
+ src = str(it.get("source") or "")
96
+ imported = src.startswith("import:") or p.get("imported_from")
97
+ title = f"Save this imported {what}?" if imported else f"Save this suggested {what}?"
98
+ return {"title": title, "kind_label": ("Imported " if imported else "Suggested ") + what,
99
+ "does": f"Approve saves it in {project} as a {what}, as written. {reject}",
100
+ "approve_label": "Approve", "reject_label": "Reject"}
101
+ if kind == "cleanup":
102
+ from . import cleanup
103
+ return {"title": _sentence(cleanup.ask(p, project, db_path)) + "?",
104
+ "kind_label": "Clean-up idea",
105
+ "does": "Approve does it, after a safety copy (undo with the edit history). "
106
+ "Reject leaves everything as it is.",
107
+ "approve_label": "Approve", "reject_label": "Reject"}
108
+ if kind == "edit":
109
+ return {"title": "Apply this edit from a markdown file?", "kind_label": "Markdown edit",
110
+ "does": "Approve changes the record as shown, after a safety copy (undo with "
111
+ "the edit history). Reject leaves the record as it is.",
112
+ "approve_label": "Approve", "reject_label": "Reject"}
113
+ if kind == "conflict":
114
+ return {"title": "Do these two decisions really conflict?",
115
+ "kind_label": "Possible conflict",
116
+ "does": "They conflict: both stay flagged in the brief until one replaces the "
117
+ "other. They fit together: the flag is dismissed. Neither decision is "
118
+ "changed.",
119
+ "approve_label": "They conflict", "reject_label": "They fit together"}
120
+ if kind == "reopen_conflict": # conflict_reopen.py: FlowState's question after an undo
121
+ return {"title": _sentence(it.get("summary") or "Reopen these possible conflicts?"),
122
+ "kind_label": "Reopen possible conflict?",
123
+ "does": "Reopen puts them back in the brief and the conflict list, and asks you "
124
+ "again whether they conflict. Leave closed changes nothing.",
125
+ "approve_label": "Reopen", "reject_label": "Leave closed"}
126
+ label = {"setting": "Review setting", "source": "Did you say this?", "rule": "Hard rule",
127
+ "delete": "Delete request", "card_offer": "Allow cards?"}.get(kind, kind.replace("_", " ").capitalize())
128
+ return {"title": _sentence(approvals.describe(it, project, db_path)) + "?",
129
+ "kind_label": label, "does": "", "approve_label": "Approve", "reject_label": "Reject"}
130
+
131
+
132
+ def _where(db_path: Path, it: dict) -> tuple:
133
+ """(link, note) for an item the user decides outside the chat."""
134
+ from . import waiting
135
+ try:
136
+ link = approvals.phone_link(db_path, it["id"])
137
+ except Exception: # noqa: BLE001 - no phone link
138
+ link = None
139
+ if link:
140
+ return link, "Only you decide this one, on your phone, not in the chat:"
141
+ try:
142
+ ways = waiting.links(db_path)
143
+ except Exception: # noqa: BLE001 - no links, the note still says where
144
+ ways = {}
145
+ if ways.get("review_page"):
146
+ return ways["review_page"], ("Only you decide this one, on the review page on this "
147
+ "computer, not in the chat:")
148
+ if ways.get("phone", "").startswith("https://"):
149
+ return ways["phone"], "Only you decide this one, on your phone, not in the chat:"
150
+ if ways.get("phone"): # an app elsewhere: a sentence, no link with the handle (D19)
151
+ return "", f"Only you decide this one, not in the chat. {ways['phone']}"
152
+ return "", (f"Only you decide this one, not in the chat: {waiting.ELSEWHERE}, or with "
153
+ f"`flowstate approve {it['id']}` in a terminal.")
154
+
155
+
156
+ def _outcome(it: dict) -> str:
157
+ if it["status"] == "approved":
158
+ if it["kind"] == "session_summary":
159
+ return "Kept as the session's record."
160
+ rid = it.get("result_id")
161
+ return "Approved" + (f": saved as #{rid}." if rid is not None and it["kind"] in _SUGGESTED
162
+ else ".")
163
+ reason = _cut(it.get("reject_reason"), 200)
164
+ if reason and reason != DEFAULT_REASON:
165
+ return f"Rejected: {reason if reason.endswith(('.', '!', '?')) else reason + '.'} " \
166
+ "Nothing was deleted."
167
+ return "Rejected. Nothing was deleted."
168
+
169
+
170
+ def view(db_path: Path, it: dict, project: str) -> dict:
171
+ """What the card shows for one review item (also the plain text, via plain())."""
172
+ from .review import strip_tag
173
+ words = _words(it, project, db_path)
174
+ out = {"item_id": it["id"], "project": project, "kind": it["kind"],
175
+ "text": _cut(strip_tag(it.get("summary")), 500),
176
+ "details": _cut(it.get("details"), DETAILS_MAX), "who": _who(it),
177
+ "when": _pretty(it.get("created_at")), "when_utc": str(it.get("created_at") or "")[:19],
178
+ "resolved": it["status"] != "pending",
179
+ "decide_here": False, "link": "", "locked_note": "", "detail": "", **words}
180
+ if it["kind"] == "session_summary": # what the session saved, not just its counts
181
+ from . import session_contents
182
+ c = session_contents.for_item(db_path, {**it, "project": project})
183
+ if c is not None:
184
+ out["contents"] = session_contents.public(c)
185
+ from .who import local_time # the plain text in this computer's time, as the card (L15)
186
+ out["contents_text"] = [x for x in [session_contents.when_line(c, local_time)] if x] \
187
+ + session_contents.lines(c)
188
+ if c["entries"]: # each record has its own Keep / Remove; Keep keeps all
189
+ out.update(approve_label=review.KEEP_ALL, does=review.KEEP_ALL_HOW)
190
+ if out["contents"].get("explain"):
191
+ out["contents_text"].append(out["contents"]["explain"])
192
+ if it["kind"] == "cleanup" and not out["resolved"]: # its exact list (task 77), and
193
+ from . import cleanup # whether it changed (task 76)
194
+ try:
195
+ got = cleanup.preview(db_path, it)
196
+ except Exception: # noqa: BLE001 - the card still shows, without the list
197
+ got = None
198
+ if got:
199
+ out["would_change"] = got["listed"]
200
+ if got["warning"]:
201
+ out["warning"] = got["warning"]
202
+ if out["resolved"]:
203
+ out["detail"] = _outcome(it)
204
+ elif locked(it):
205
+ out["link"], out["locked_note"] = _where(db_path, it)
206
+ else:
207
+ out["decide_here"] = True
208
+ return out
209
+
210
+
211
+ def plain(v: dict) -> str:
212
+ lines = [v["title"], f"{v['kind_label']} #{v['item_id']} in {v['project']}: {v['text']}"]
213
+ if v.get("details"):
214
+ lines.append(v["details"])
215
+ if v.get("would_change"):
216
+ lines.append(v["would_change"])
217
+ if v.get("warning"):
218
+ lines.append(v["warning"])
219
+ lines.extend(v.get("contents_text") or [])
220
+ lines.append("From " + v["who"] + (f", {v['when']}" if v.get("when") else ""))
221
+ if v.get("does"):
222
+ lines.append(v["does"])
223
+ if v["resolved"]:
224
+ lines.append(v["detail"])
225
+ elif not v["decide_here"]:
226
+ lines.append(v["locked_note"] + (f" {v['link']}" if v.get("link") else ""))
227
+ else:
228
+ lines.append(f"Buttons: {v['approve_label']} / {v['reject_label']}"
229
+ + (", and Keep / Remove on each record" if any(
230
+ e.get("actions") for e in (v.get("contents") or {}).get("entries", []))
231
+ else "") + ".")
232
+ return "\n".join(lines)
233
+
234
+
235
+ def _items(conn, where: str, params: list, limit: Optional[int] = None) -> list:
236
+ sql = (f"SELECT r.*, p.name AS project FROM review_items r JOIN projects p ON p.id = r.project_id "
237
+ f"WHERE {where} ORDER BY r.id" + (" LIMIT ?" if limit else ""))
238
+ return [dict(r) for r in conn.execute(sql, (*params, limit) if limit else params)]
239
+
240
+
241
+ # ---------------------------------------------------------------- pointers in other answers
242
+ def show_call(project: str, item_ids: list) -> str:
243
+ ids = sorted({int(i) for i in item_ids if i is not None})
244
+ one = f", item_id={ids[0]}" if len(ids) == 1 else ""
245
+ return f'show_review_card(project="{project}"{one})'
246
+
247
+
248
+ def pointer(project: Optional[str], item_ids: list) -> dict:
249
+ """{show_card, card_note} for answers that list waiting non-disagreement items, on MCP Apps
250
+ hosts only (elsewhere the text is all there is)."""
251
+ if not item_ids or not project:
252
+ return {}
253
+ if not client_has_ui(): # a network sign-in not allowed yet: offered once (card_offer.py)
254
+ from . import conflict_cards
255
+ return conflict_cards.offered(project)
256
+ call = show_call(project, item_ids)
257
+ return {"show_card": call,
258
+ "card_note": f"This app can show what's waiting as cards the user taps (Approve or "
259
+ f"Reject): call {call} now if they want to decide here. Don't choose "
260
+ f"for them."}
261
+
262
+
263
+ def both(conflict: dict, rest: dict) -> dict:
264
+ """Both kinds wait: both calls, one short note."""
265
+ if not (conflict and rest):
266
+ return conflict or rest
267
+ if "show_card" not in conflict or "show_card" not in rest: # no cards here: the offer note
268
+ return {**rest, **conflict}
269
+ calls = [conflict["show_card"], rest["show_card"]]
270
+ return {"show_card": calls,
271
+ "card_note": f"This app can show these as cards the user taps: call {calls[0]} for the "
272
+ f"disagreement(s) and {calls[1]} for the rest. Don't choose for them."}
273
+
274
+
275
+ def brief_hint(conn, pid: int, project: str, card_hint: Optional[str] = None) -> Optional[str]:
276
+ """On MCP Apps hosts, when non-disagreement items wait in the project: how many, and the
277
+ call that shows them as cards. `card_hint` is the disagreement card's own hint
278
+ (conflict_cards.brief_hint); when both wait, one line names both calls."""
279
+ if not review.available(conn):
280
+ return card_hint
281
+ n = conn.execute("SELECT COUNT(*) FROM review_items WHERE project_id = ? AND status = 'pending' "
282
+ "AND kind != 'disagreement'", (pid,)).fetchone()[0]
283
+ if not client_has_ui(): # card_hint is then the offer note (card_offer.py), if any
284
+ if card_hint or not n:
285
+ return card_hint
286
+ from . import conflict_cards
287
+ return conflict_cards.offered(pid).get("cards_off")
288
+ if not n:
289
+ return card_hint
290
+ items = f"{n} item{'s' if n != 1 else ''}"
291
+ call = show_call(project, [])
292
+ if card_hint:
293
+ dis, k = conflict_call(conn, pid, project)
294
+ return (f"Cards waiting: call {dis} for the disagreement{'s' if k > 1 else ''} and "
295
+ f"{call} for the other {items}, to show them in the chat.")
296
+ return (f"Review cards: {items} wait{'s' if n == 1 else ''} for the user; call {call} to "
297
+ f"show them as cards in the chat.")
298
+
299
+
300
+ def conflict_call(conn, pid: int, project: str) -> tuple:
301
+ from . import conflict_cards
302
+ ids = [r[0] for r in conn.execute("""SELECT review_item_id FROM conflict_cards WHERE project_id = ?
303
+ AND status = 'open' AND review_item_id IS NOT NULL""", (pid,))]
304
+ return conflict_cards.show_call(project, ids), len(ids)
305
+
306
+
307
+ # ---------------------------------------------------------------- show_review_card
308
+ def show(db_path: Path, args: dict, pid: Optional[int]) -> dict:
309
+ """One item (item_id, any status) or up to SHOW_MAX waiting ones, oldest first (in a
310
+ project, else all). Disagreements are left to show_conflict_card, with a pointer."""
311
+ from . import conflict_cards
312
+ if args.get("project") not in (None, "") and pid is None:
313
+ return {"error": "project_not_found", "message": f"No single project matches "
314
+ f"{args.get('project')!r}."}
315
+ conn = _connect(db_path)
316
+ try:
317
+ if not review.available(conn):
318
+ return {"error": "review_queue_unavailable", "message": "The review queue isn't set "
319
+ "up in this database yet."}
320
+ dis_ids, dis_project = [], None
321
+ if args.get("item_id") is not None:
322
+ try:
323
+ item_id = int(args["item_id"])
324
+ except (TypeError, ValueError):
325
+ return {"error": "bad_request", "message": "item_id must be a number."}
326
+ rows = _items(conn, "r.id = ?", [item_id])
327
+ if not rows or (pid is not None and rows[0]["project_id"] != pid):
328
+ return {"error": "record_not_found",
329
+ "message": f"No review item #{item_id}" + (" in this project." if pid else ".")}
330
+ if rows[0]["kind"] == "disagreement":
331
+ call = conflict_cards.show_call(rows[0]["project"], [item_id])
332
+ note = f"Review item #{item_id} is a disagreement; it has its own card: call {call}."
333
+ return {"shown": 0, "disagreement": item_id, "show_card": call, "note": note,
334
+ "_ui": {"structured": {"cards": [], "note": "This is a disagreement: it "
335
+ "has its own card."}}}
336
+ total = 1
337
+ else:
338
+ where, params = "r.status = 'pending'", []
339
+ if pid is not None:
340
+ where, params = where + " AND r.project_id = ?", [pid]
341
+ rest = where + " AND r.kind != 'disagreement'"
342
+ total = conn.execute(f"SELECT COUNT(*) FROM review_items r WHERE {rest}", params).fetchone()[0]
343
+ rows = _items(conn, rest, params, SHOW_MAX)
344
+ dis = _items(conn, where + " AND r.kind = 'disagreement'", params)
345
+ if dis:
346
+ dis_project = dis[0]["project"]
347
+ dis_ids = [d["id"] for d in dis if d["project"] == dis_project]
348
+ finally:
349
+ conn.close()
350
+ views = [view(db_path, it, it["project"]) for it in rows]
351
+ for it, v in zip(rows, views): # the app that queued it doesn't decide it on its card
352
+ if v["decide_here"] and own_refusal(it, it["id"]):
353
+ link, _note = _where(db_path, it)
354
+ v.update(decide_here=False, link=link, locked_note=OWN_NOTE)
355
+ for e in (v.get("contents") or {}).get("entries", []):
356
+ e["actions"] = []
357
+ out: dict = {"shown": len(views)}
358
+ if views:
359
+ out["review_cards"] = [{"review_item_id": v["item_id"], "text": plain(v)} for v in views]
360
+ if total > len(views):
361
+ out["more"] = total - len(views)
362
+ structured = {"cards": views, "more": out.get("more", 0)}
363
+ if dis_ids:
364
+ call = conflict_cards.show_call(dis_project, dis_ids)
365
+ n = len(dis_ids)
366
+ out["disagreements"] = {"waiting": n, "show_card": call}
367
+ structured["also"] = (f"{n} disagreement{'s' if n > 1 else ''} also wait"
368
+ f"{'' if n > 1 else 's'} on {'their' if n > 1 else 'its'} own card.")
369
+ open_ = [v for v in views if not v["resolved"]]
370
+ if not views:
371
+ out["note"] = structured["note"] = "Nothing else is waiting for the user's OK." if dis_ids \
372
+ else "Nothing is waiting for the user's OK."
373
+ elif any(v["decide_here"] for v in open_) and client_has_ui():
374
+ out["note"] = ("The cards are on screen: the user taps Approve or Reject. Don't choose "
375
+ "for them or ask them to type it.")
376
+ elif open_:
377
+ out["note"] = "Show the user this text; they decide on the review page or their phone."
378
+ else:
379
+ out["note"] = "Already decided."
380
+ if dis_ids:
381
+ out["note"] += f" A disagreement waits too: call {out['disagreements']['show_card']}."
382
+ out["_ui"] = {"structured": structured, "taps": taps_for(views, "review", _has_buttons)}
383
+ return out
384
+
385
+
386
+ OWN_NOTE = "This app queued it itself, so it isn't decided on this app's card. Decide it here:"
387
+
388
+
389
+ def _has_buttons(v: dict) -> bool:
390
+ return bool(v.get("decide_here")) and not v.get("resolved")
391
+
392
+
393
+ # ---------------------------------------------------------------- resolve_review_card (the buttons)
394
+ def resolve_card(db_path: Path, args: dict, pid: Optional[int], client: str,
395
+ decide: Callable[[dict, str, str], dict]) -> dict:
396
+ from . import card_taps
397
+ return card_taps.resolve(_resolve, db_path, args, pid, client, decide)
398
+
399
+
400
+ def _resolve(db_path: Path, args: dict, pid: Optional[int], client: str,
401
+ decide: Callable[[dict, str, str], dict]) -> dict:
402
+ """A tap on Approve or Reject. `decide(item, decision, reason)` runs the same approve /
403
+ reject as manage_review (review_apply.for_card). Not a chat sentence, not
404
+ for clients without MCP Apps or off the card list, never for an item only the user decides
405
+ elsewhere. Logged with path "card"."""
406
+ for key in ("user_request", "message", "text", "reason"):
407
+ if args.get(key) not in (None, ""):
408
+ return {"error": "not_a_card_tap", "message": NOT_TAP}
409
+ decision = args.get("decision")
410
+ if decision not in ("approve", "reject") + RECORD_DECISIONS:
411
+ return {"error": "decision_required", "message": 'decision is "approve" or "reject" '
412
+ '(or a record\'s keep_record / remove_record / restore_record).'}
413
+ if (decision in RECORD_DECISIONS) != isinstance(args.get("record"), str):
414
+ return {"error": "bad_request", "message": "record (type:id) goes with keep_record / "
415
+ "remove_record / restore_record only."}
416
+ if args.get("item_id") is None:
417
+ return {"error": "item_id_required", "message": "Name the review item (item_id)."}
418
+ why = args.get("reject_reason")
419
+ if why not in (None, "") and (not isinstance(why, str) or decision != "reject"):
420
+ return {"error": "bad_request", "message": "reject_reason is a short text, with reject only."}
421
+ why = " ".join((why or "").split())[:REASON_MAX]
422
+ if not client_has_ui(): # no MCP Apps host, no card: the call can only be the model's
423
+ return {"error": "not_a_card_tap", "message": "This app can't show review cards. The "
424
+ "user decides on the review page or their phone."}
425
+ from . import waiting
426
+ try:
427
+ item_id = int(args["item_id"])
428
+ except (TypeError, ValueError):
429
+ return {"error": "bad_request", "message": "item_id must be a number."}
430
+ it = waiting._item_view(db_path, item_id)
431
+ if not it or (pid is not None and it["project_id"] != pid):
432
+ return {"error": "record_not_found", "message": f"No review item #{item_id}"
433
+ + (" in this project." if pid is not None else ".")}
434
+ if it["kind"] == "disagreement":
435
+ from . import conflict_cards
436
+ return {"error": "use_conflict_card", "message": "This is a disagreement: it has its own "
437
+ "card (" + conflict_cards.show_call(it["project"], [item_id]) + ")."}
438
+ if it["status"] != "pending":
439
+ return {"error": "already_decided", "message": f"Review item #{item_id} is already "
440
+ f"{it['status']}."}
441
+ if locked(it):
442
+ link, note = _where(db_path, it)
443
+ return {"error": "user_only", "message": f"Nothing was decided on review item #{item_id}. "
444
+ + note + (f" {link}" if link else ""), **({"link": link} if link else {})}
445
+ no = own_refusal(it, item_id) or tap_refusal(args, item_id, "review", client)
446
+ if no:
447
+ return no
448
+ if decision in RECORD_DECISIONS:
449
+ return _record_tap(db_path, it, args["record"], decision, client)
450
+ out = decide(it, decision, why or DEFAULT_REASON)
451
+ if isinstance(out, dict) and "error" in out:
452
+ return out
453
+ from . import card_trust
454
+ approvals.log_decision(db_path, it, "card", card_trust.label(client),
455
+ "approved" if decision == "approve" else "rejected")
456
+ fresh = waiting._item_view(db_path, item_id) or it
457
+ v = view(db_path, fresh, fresh["project"])
458
+ text = plain(v)
459
+ res = {"resolved": item_id, "decision": decision, "text": text, "note": v["detail"] or text,
460
+ "review_cards": [{"review_item_id": item_id, "text": text}],
461
+ "_ui": {"structured": {"cards": [v]}}}
462
+ res.update({k: val for k, val in (out or {}).items() if k not in res})
463
+ return res
464
+
465
+
466
+ RECORD_DECISIONS = ("keep_record", "remove_record", "restore_record")
467
+
468
+
469
+ def _record_tap(db_path: Path, it: dict, record: str, decision: str, client: str) -> dict:
470
+ """A tap on one record's Keep / Remove / Bring back (session_records.py), after the same
471
+ checks as Approve / Reject. Remove and Bring back follow the delete rules: not for callers
472
+ that may not delete (remote tokens, LAN keys, OAuth apps, the relay), and with approvals on
473
+ only on the review page or the phone. Recorded as a tap on the card (card_trust.label:
474
+ "card (<app>)", plus the sign-in over the network), path card."""
475
+ from . import card_trust, session_records
476
+ by = card_trust.label(client) # read before the identity is cleared below
477
+ if decision != "keep_record":
478
+ no = record_delete_refusal(db_path, it)
479
+ if no:
480
+ return no
481
+ tok = identity.set_current(None)
482
+ try:
483
+ res = session_records.decide(db_path, it["id"], record, decision.split("_")[0],
484
+ by, path="card")
485
+ except session_records.RecordError as e:
486
+ return e.payload
487
+ finally:
488
+ identity.reset(tok)
489
+ from . import waiting
490
+ fresh = waiting._item_view(db_path, it["id"]) or it
491
+ v = view(db_path, fresh, fresh["project"])
492
+ text = plain(v)
493
+ return {"record_decided": res["record"], "now": res["now"] or "undecided",
494
+ "note": res["message"], "text": text,
495
+ "review_cards": [{"review_item_id": it["id"], "text": text}],
496
+ "_ui": {"structured": {"cards": [v]}, "taps": taps_for([v], "review", _has_buttons)},
497
+ **{k: res[k] for k in ("safety_copy", "undo") if k in res}}
498
+
499
+
500
+ def record_delete_refusal(db_path: Path, it: dict) -> Optional[dict]:
501
+ """A record's Remove / Bring back from the chat card deletes (or restores) for the user,
502
+ so it keeps the delete rules (remote_auth.may_delete; approvals.is_on). None = allowed."""
503
+ from .remote_auth import DELETE_REFUSAL, may_delete
504
+ from .server import _caller
505
+ if not may_delete(_caller()[1]) or getattr(identity.current(), "credential", None):
506
+ return {"error": DELETE_REFUSAL[0], "message": "Remove and Bring back on a card delete "
507
+ "or restore records, which only an app on the FlowState computer may do. "
508
+ "Nothing changed. Decide them on the review page or your phone."}
509
+ if approvals.is_on(db_path, it.get("project_id")):
510
+ link, _note = _where(db_path, {**it, "kind": "delete"})
511
+ return {"error": "user_only", "message": "Approvals are on, so Remove and Bring back are "
512
+ "decided only on the review page or your phone, not in the chat. Nothing changed."
513
+ + (f" {link}" if link else ""), **({"link": link} if link else {})}
514
+ return None
515
+
516
+
517
+ # ---------------------------------------------------------------- tool definitions
518
+ def app_tool():
519
+ """Hidden from the model (visibility app). Hosts that advertise MCP Apps still receive it."""
520
+ from mcp.types import Tool
521
+
522
+ from .review_card_ui import UI_URI
523
+ tool = Tool(
524
+ name="resolve_review_card",
525
+ description="Save the user's tap on a review card (Approve, or Reject with an optional "
526
+ "reason typed in the card; on a session summary also one record's Keep / "
527
+ "Remove / Bring back). Apps call this from the card. A person decides; "
528
+ "chat text is refused. Returns the saved outcome.",
529
+ inputSchema={"type": "object", "properties": {
530
+ "item_id": {"type": "integer", "description": "The review item the card is showing."},
531
+ "decision": {"type": "string", "enum": ["approve", "reject", *RECORD_DECISIONS]},
532
+ "record": {"type": "string", "description": "keep_record / remove_record / "
533
+ "restore_record only: the session summary's record (type:id)."},
534
+ "project": {"type": "string", "description": "The project name the card is showing."},
535
+ "reject_reason": {"type": "string", "maxLength": REASON_MAX,
536
+ "description": "Reject only: the reason typed in the card."},
537
+ "tap": {"type": "string", "description": "The card's one-use code for this tap."},
538
+ }, "required": ["item_id", "decision", "project"]})
539
+ return tool.model_copy(update={"meta": {"ui": {"resourceUri": UI_URI, "visibility": ["app"]}}})
540
+
541
+
542
+ def show_tool():
543
+ """Model-visible and read-only; its definition names the card's ui:// resource."""
544
+ from mcp.types import Tool, ToolAnnotations
545
+
546
+ from .review_card_ui import UI_URI
547
+ tool = Tool(
548
+ name="show_review_card",
549
+ title="Show review cards",
550
+ description="Show the user what waits in the review queue as cards in this chat (session "
551
+ "summaries, suggestions, imports, clean-ups...), so they tap Approve or Reject "
552
+ "themselves. Call it when a FlowState answer has show_card naming it, or when "
553
+ "the user asks to see what's waiting. Read-only: you never choose. item_id: "
554
+ f"one item; without it, the project's waiting items (oldest first, at most "
555
+ f"{SHOW_MAX}). Disagreements use show_conflict_card. Returns the card text; "
556
+ "the app draws the cards.",
557
+ inputSchema={"type": "object", "properties": {
558
+ "project": {"type": ["string", "integer"], "description": "Name or id."},
559
+ "item_id": {"type": "integer", "description": "One review item's id."},
560
+ }},
561
+ annotations=ToolAnnotations(title="Show review cards", readOnlyHint=True,
562
+ idempotentHint=True, openWorldHint=False))
563
+ return tool.model_copy(update={"meta": {"ui": {"resourceUri": UI_URI,
564
+ "visibility": ["model", "app"]}}})