Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
feat(pocket): decision digest — action preview + A/B/C options (#387)
Aurora Capital1c9cd024a31b
diff --git a/claude-ops/scripts/ops-pocket-approvals.py b/claude-ops/scripts/ops-pocket-approvals.pyindex 7218b463..973ed32e 100644--- a/claude-ops/scripts/ops-pocket-approvals.py+++ b/claude-ops/scripts/ops-pocket-approvals.py@@ -8,180 +8,466 @@ Modes:email-bridge SES backend. Idempotent: only emails when the openset changed.--replies poll the owner's Gmail (gog) for "APPROVE <code|id>" /- "REJECT <code|id>" and act: APPROVE -> append the task to- tasks.jsonl (executor runs it; the worker keeps its own Rule-6- staging for any 3rd-party send); REJECT -> record dropped.+ "REJECT <code|id>" / "<code> <letter>" and act:+ APPROVE -> append the task to tasks.jsonl (executor runs it; the+ worker keeps its own Rule-6 staging for any 3rd-party send);+ REJECT -> record dropped;+ <code> <letter> -> choice-item selection, promotes with+ chosen_option/chosen_option_label fields.Idempotent via approval-resolved.jsonl.+ASK schema (additive fields, all optional — no regression on old records):+ action_preview : str — one sentence: what APPROVE concretely does.+ decision_question : str — the actual question for choice items.+ options : list — [{"key": "a", "label": "<text>"}, ...]+ When present, item is a CHOICE not a yes/no.+Recipient is locked to email-config.self_address. Self-notification to theowner only.Requires the SES email backend in ops-pocket-email-bridge.py (send_email's`backend`/`ses_cfg` kwargs) — see the related "SES email backend" PR."""+from __future__ import annotations-import json, os, re, sys, time, subprocess+import hashlib, json, os, re, sys, time, subprocessfrom pathlib import Path-STATE = Path(os.environ.get("POCKET_STATE_DIR", str(Path.home() / ".claude/state/pocket")))+STATE = Path(+ os.environ.get("POCKET_STATE_DIR", str(Path.home() / ".claude/state/pocket"))+)REVIEW = STATE / "review.jsonl"DRAFTS = STATE / "drafts.jsonl"TASKS = STATE / "tasks.jsonl"-RESOLVED = STATE / "approval-resolved.jsonl" # ids approved/rejected-CODEMAP = STATE / "approval-codemap.json" # code -> {id,kind,title}-NOTIFIED = STATE / "approval-notified.json" # hash of last-digested open set+RESOLVED = STATE / "approval-resolved.jsonl" # ids approved/rejected+CODEMAP = STATE / "approval-codemap.json" # code -> {id,kind,title,...}+NOTIFIED = STATE / "approval-notified.json" # hash of last-digested open setLOG = STATE / "approvals.log"CFG = STATE / "email-config.json"# Sibling scripts dir: env override, else this file's own directory.-SCRIPTS = Path(os.environ.get("POCKET_SCRIPTS_DIR", str(Path(__file__).resolve().parent)))+SCRIPTS = Path(+ os.environ.get("POCKET_SCRIPTS_DIR", str(Path(__file__).resolve().parent))+)GOG = os.environ.get("POCKET_GOG_BIN", "gog")+# Context preview length in digest (word-boundary truncated).+CTX_PREVIEW_CHARS = int(os.environ.get("POCKET_DIGEST_CTX_CHARS", "600"))++def log(m):- line=f"{time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())} [approvals] {m}"+ line = f"{time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())} [approvals] {m}"print(line, file=sys.stderr)- try: open(LOG,"a").write(line+"\n")- except OSError: pass+ try:+ open(LOG, "a").write(line + "\n")+ except OSError:+ pass+def _load_jsonl(p):- out=[]+ out = []if p.exists():for line in p.read_text().splitlines():- line=line.strip()- if not line: continue- try: out.append(json.loads(line))- except: pass+ line = line.strip()+ if not line:+ continue+ try:+ out.append(json.loads(line))+ except Exception:+ passreturn out++def _truncate_words(text: str, max_chars: int) -> str:+ """Truncate text at a word boundary, appending '...' when cut."""+ if len(text) <= max_chars:+ return text+ cut = text[:max_chars].rsplit(" ", 1)[0]+ return cut.rstrip(",;:") + "..."++def _norm(item):"""Return (id, kind, title, ctx, raw) from a review/draft row (raw or wrapped)."""t = item.get("task", item)- return (t.get("id") or item.get("id"),- t.get("kind") or item.get("kind","action_item"),- (t.get("title") or item.get("title") or "")[:120],- (t.get("context") or item.get("context") or "")[:600], t)+ return (+ t.get("id") or item.get("id"),+ t.get("kind") or item.get("kind", "action_item"),+ (t.get("title") or item.get("title") or "")[:120],+ (t.get("context") or item.get("context") or "")[:600],+ t,+ )+++def _extract_option_fields(raw: dict) -> tuple[str, str, list]:+ """Pull action_preview, decision_question, options from an ASK raw record.++ Looks in both the top-level dict and a nested 'triage' sub-dict so records+ written by ops-pocket-triage.py (which puts everything in 'triage') and+ records written directly are both handled.+ """+ triage = raw.get("triage") or {}+ action_preview = raw.get("action_preview") or triage.get("action_preview") or ""+ decision_question = (+ raw.get("decision_question") or triage.get("decision_question") or ""+ )+ options = raw.get("options") or triage.get("options") or []+ return action_preview, decision_question, options+def _resolved_ids():return {r.get("id") for r in _load_jsonl(RESOLVED)}+def open_items():- res=_resolved_ids()- items=[]- for src,tag in ((REVIEW,"ASK"),(DRAFTS,"DRAFT")):+ res = _resolved_ids()+ items = []+ for src, tag in ((REVIEW, "ASK"), (DRAFTS, "DRAFT")):for it in _load_jsonl(src):- iid,kind,title,ctx,raw=_norm(it)- if not iid or iid in res: continue- if any(x["id"]==iid for x in items): continue- items.append({"id":iid,"bucket":tag,"kind":kind,"title":title,"ctx":ctx,"raw":raw})+ iid, kind, title, ctx, raw = _norm(it)+ if not iid or iid in res:+ continue+ if any(x["id"] == iid for x in items):+ continue+ action_preview, decision_question, options = _extract_option_fields(raw)+ items.append(+ {+ "id": iid,+ "bucket": tag,+ "kind": kind,+ "title": title,+ "ctx": ctx,+ "raw": raw,+ "action_preview": action_preview,+ "decision_question": decision_question,+ "options": options,+ }+ )return items+def send_via_bridge(subject, body):"""Reuse email-bridge send_email (SES backend) to mail the owner."""- sys.path.insert(0,str(SCRIPTS))+ sys.path.insert(0, str(SCRIPTS))import importlib.util- spec=importlib.util.spec_from_file_location("ebridge", SCRIPTS/"ops-pocket-email-bridge.py")- eb=importlib.util.module_from_spec(spec); spec.loader.exec_module(eb)- cfg=json.loads(CFG.read_text())- to=cfg.get("self_address")- ok,info=eb.send_email(to, subject, body, backend=cfg.get("backend","gog"), ses_cfg=cfg)- return ok,info,to++ spec = importlib.util.spec_from_file_location(+ "ebridge", SCRIPTS / "ops-pocket-email-bridge.py"+ )+ eb = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(eb)+ cfg = json.loads(CFG.read_text())+ to = cfg.get("self_address")+ ok, info = eb.send_email(+ to, subject, body, backend=cfg.get("backend", "gog"), ses_cfg=cfg+ )+ return ok, info, to+++def _render_item(code: str, it: dict) -> list[str]:+ """Return digest lines for one item. Choice items get option list + letter instruction."""+ lines = []+ is_choice = bool(it.get("options"))++ lines.append(f"[{code}] ({it['bucket']}) {it['title']}")++ # Context preview — word-boundary truncated+ ctx = it.get("ctx") or ""+ if ctx:+ lines.append(f" {_truncate_words(ctx, CTX_PREVIEW_CHARS)}")++ # Action preview (what APPROVE actually does)+ ap = it.get("action_preview") or ""+ if ap:+ lines.append(f" -> Approve = {ap}")++ if is_choice:+ dq = it.get("decision_question") or ""+ if dq:+ lines.append(f" Q: {dq}")+ for opt in it["options"]:+ lines.append(f" {opt['key']}) {opt['label']}")+ lines.append(+ f" Reply: {code} <letter> (e.g. {code} {it['options'][0]['key']})"+ )+ else:+ lines.append(f" Reply: APPROVE {code} or REJECT {code}")++ lines.append("")+ return lines+def cmd_digest():- items=open_items()+ items = open_items()if not items:- log("digest: no open items"); return 0- codemap={}- a=d=0- lines=["Pending Pocket items need your decision. Reply to this email with one line per item:",- " APPROVE <code> (run it)"," REJECT <code> (drop it)","",]+ log("digest: no open items")+ return 0++ codemap = {}+ a = d = 0++ # Header: explain both reply styles+ header_lines = [+ "Pending Pocket items need your decision.",+ "Reply to this email with one line per item:",+ " Yes/No items: APPROVE <code> or REJECT <code>",+ " Choice items: <code> <letter> (e.g. A1 b)",+ "",+ ]++ item_lines: list[str] = []for it in items:- if it["bucket"]=="ASK": a+=1; code=f"A{a}"- else: d+=1; code=f"D{d}"- codemap[code]={"id":it["id"],"kind":it["kind"],"title":it["title"],"bucket":it["bucket"],"raw":it["raw"]}- lines.append(f"[{code}] ({it['bucket']}) {it['title']}")- if it["ctx"]: lines.append(f" {it['ctx'][:240]}")- lines.append("")- body="\n".join(lines)- # idempotency: skip if same open set already notified- import hashlib- h=hashlib.sha256(json.dumps([(it["id"], it["bucket"]) for it in items]).encode()).hexdigest()- prev=json.loads(NOTIFIED.read_text()).get("hash") if NOTIFIED.exists() else None- if h==prev:+ if it["bucket"] == "ASK":+ a += 1+ code = f"A{a}"+ else:+ d += 1+ code = f"D{d}"+ codemap[code] = {+ "id": it["id"],+ "kind": it["kind"],+ "title": it["title"],+ "bucket": it["bucket"],+ "raw": it["raw"],+ "options": it["options"],+ }+ item_lines.extend(_render_item(code, it))++ body = "\n".join(header_lines + item_lines)++ # Idempotency: skip if same open set already notified+ h = hashlib.sha256(+ json.dumps([(it["id"], it["bucket"]) for it in items]).encode()+ ).hexdigest()+ prev = json.loads(NOTIFIED.read_text()).get("hash") if NOTIFIED.exists() else None+ if h == prev:log(f"digest: open set unchanged ({len(items)} items) — not re-emailing")if not CODEMAP.exists():CODEMAP.write_text(json.dumps(codemap, indent=2))log("digest: wrote missing approval-codemap.json for unchanged open set")return 0- ok,info,to=send_via_bridge(f"[Pocket] {len(items)} item(s) need approval", body)- CODEMAP.write_text(json.dumps(codemap,indent=2))++ ok, info, to = send_via_bridge(f"[Pocket] {len(items)} item(s) need approval", body)+ CODEMAP.write_text(json.dumps(codemap, indent=2))if ok:- NOTIFIED.write_text(json.dumps({"hash":h,"ts":time.time(),"count":len(items)}))+ NOTIFIED.write_text(+ json.dumps({"hash": h, "ts": time.time(), "count": len(items)})+ )log(f"digest: emailed {len(items)} items to {to} ok={ok} info={info}")return 0 if ok else 1+def _gog_search_replies():"""Find recent emails from the owner replying to approval digests."""try:- r=subprocess.run([GOG,"gmail","search","from:me subject:[Pocket] newer_than:2d","--max","15","-j","--results-only","--no-input"],- capture_output=True,text=True,timeout=60,env=os.environ)- if r.returncode!=0:- log(f"gog search rc={r.returncode}: {r.stderr[:150]}"); return []+ r = subprocess.run(+ [+ GOG,+ "gmail",+ "search",+ "from:me subject:[Pocket] newer_than:2d",+ "--max",+ "15",+ "-j",+ "--results-only",+ "--no-input",+ ],+ capture_output=True,+ text=True,+ timeout=60,+ env=os.environ,+ )+ if r.returncode != 0:+ log(f"gog search rc={r.returncode}: {r.stderr[:150]}")+ return []return json.loads(r.stdout or "[]")except Exception as e:- log(f"gog search err {e}"); return []+ log(f"gog search err {e}")+ return []+def _gog_body_and_subject(msg_id):try:- r=subprocess.run([GOG,"gmail","get",msg_id,"-j","--no-input"],capture_output=True,text=True,timeout=60,env=os.environ)- d=json.loads(r.stdout or "{}")+ r = subprocess.run(+ [GOG, "gmail", "get", msg_id, "-j", "--no-input"],+ capture_output=True,+ text=True,+ timeout=60,+ env=os.environ,+ )+ d = json.loads(r.stdout or "{}")return (d.get("body") or d.get("snippet") or ""), (d.get("subject") or "")- except Exception: return "", ""+ except Exception:+ return "", ""+def _is_digest_outbound_subject(subject):"""Sent digest uses '[Pocket] N item(s) need approval' without a Re: prefix; skip those."""s = (subject or "").strip()if re.match(r"(?i)^re:\s*", s):return False- return re.match(r"^\[Pocket\]\s+\d+\s+item\(s\)\s+need\s+approval\s*$", s) is not None+ return (+ re.match(r"^\[Pocket\]\s+\d+\s+item\(s\)\s+need\s+approval\s*$", s) is not None+ )+++# ---------------------------------------------------------------------------+# Reply patterns+# Classic: APPROVE A1 / REJECT A1 / APPROVE <uuid>+# Choice: A1 b / A1: b / APPROVE A1 b+# ---------------------------------------------------------------------------+_RE_CLASSIC = re.compile(r"\b(APPROVE|REJECT)\s+([A-Za-z]\d+|[a-z0-9\-]{6,})\b", re.I)+# Choice: optional "APPROVE " prefix, then code, then colon-or-space, then letter.+# Captured groups: (opt_approve, code, letter)+_RE_CHOICE = re.compile(r"(?:APPROVE\s+)?([A-Za-z]\d+)[:\s]+([a-z])\b", re.I)+_RE_DIGEST_CHOICE_EXAMPLE = re.compile(r"\(e\.g\.[\s:]*$", re.I)+++def _choice_match_is_digest_example(body: str, mt: re.Match) -> bool:+ """True when the match is inside a digest '(e.g. CODE letter)' example in quoted text."""+ prefix = body[max(0, mt.start() - 24) : mt.start()]+ return _RE_DIGEST_CHOICE_EXAMPLE.search(prefix) is not None+++def _resolve_code(codemap: dict, ref: str):+ """Look up a codemap entry by short code (A1) or raw id."""+ ent = codemap.get(ref) or codemap.get(ref.upper())+ if ent:+ return ent+ # Fall back to raw id match+ return next((c for c in codemap.values() if c.get("id") == ref), None)+def cmd_replies():- if not CODEMAP.exists(): log("replies: no codemap yet"); return 0- codemap=json.loads(CODEMAP.read_text())- res=_resolved_ids()- acted=0- self_addr=json.loads(CFG.read_text()).get("self_address","")+ if not CODEMAP.exists():+ log("replies: no codemap yet")+ return 0+ codemap = json.loads(CODEMAP.read_text())+ res = _resolved_ids()+ acted = 0+ self_addr = json.loads(CFG.read_text()).get("self_address", "")+for m in _gog_search_replies():- frm=(m.get("from") or "").lower()- if not self_addr or self_addr.lower() not in frm: # only the owner's own replies+ frm = (m.get("from") or "").lower()+ if not self_addr or self_addr.lower() not in frm:continuebody, subj = _gog_body_and_subject(m.get("id", ""))if _is_digest_outbound_subject(subj):continue- for mt in re.finditer(r"\b(APPROVE|REJECT)\s+([A-Za-z]\d+|[a-z0-9\-]{6,})\b", body, re.I):- verb=mt.group(1).upper(); ref=mt.group(2)- ent=codemap.get(ref) or codemap.get(ref.upper())- tid=ent["id"] if ent else (ref if any(c["id"]==ref for c in codemap.values()) else None)- if not ent and tid:- ent=next((c for c in codemap.values() if c["id"]==tid),None)- if not ent: continue- if ent["id"] in res: continue # already resolved- if verb=="APPROVE":- task=ent["raw"].get("task",ent["raw"]) if isinstance(ent["raw"],dict) else {}- task=dict(task); task["id"]=ent["id"]- if ent.get("bucket")=="DRAFT":- task["kind"]="action_item"++ # Track which ids we've already acted on in this message so we don't+ # process the same id twice (choice regex may also match classic).+ handled_in_msg: set[str] = set()++ # --- Choice replies first (higher specificity) ---+ for mt in _RE_CHOICE.finditer(body):+ if _choice_match_is_digest_example(body, mt):+ continue+ ref = mt.group(1)+ letter = mt.group(2).lower()+ ent = _resolve_code(codemap, ref)+ if not ent:+ continue+ tid = ent["id"]+ if tid in res or tid in handled_in_msg:+ continue+ options = ent.get("options") or []+ if not options:+ # Not a choice item — let classic handler decide+ continue+ valid_keys = {o["key"].lower() for o in options}+ if letter not in valid_keys:+ log(+ f"choice reply {ref} {letter}: invalid key (valid: {valid_keys}) — skipping"+ )+ continue+ chosen_opt = next(o for o in options if o["key"].lower() == letter)+ task = (+ ent["raw"].get("task", ent["raw"])+ if isinstance(ent["raw"], dict)+ else {}+ )+ task = dict(task)+ task["id"] = tid+ task.setdefault("kind", "action_item")+ task["approved_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())+ task["chosen_option"] = letter+ task["chosen_option_label"] = chosen_opt["label"]+ open(TASKS, "a").write(json.dumps(task) + "\n")+ open(RESOLVED, "a").write(+ json.dumps(+ {+ "id": tid,+ "decision": "CHOOSE",+ "chosen": letter,+ "ts": time.time(),+ }+ )+ + "\n"+ )+ log(+ f"CHOOSE {ref} {letter} -> promoted {tid} (option: {chosen_opt['label']}) to tasks.jsonl"+ )+ acted += 1+ res.add(tid)+ handled_in_msg.add(tid)++ # --- Classic APPROVE/REJECT ---+ for mt in _RE_CLASSIC.finditer(body):+ verb = mt.group(1).upper()+ ref = mt.group(2)+ ent = _resolve_code(codemap, ref)+ if not ent:+ continue+ tid = ent["id"]+ if tid in res or tid in handled_in_msg:+ continue++ # A bare APPROVE on a choice item is ambiguous — leave unresolved.+ if verb == "APPROVE" and (ent.get("options") or []):+ log(+ f"APPROVE {ref}: choice item needs a letter (e.g. {ref} a) — leaving unresolved"+ )+ continue++ if verb == "APPROVE":+ task = (+ ent["raw"].get("task", ent["raw"])+ if isinstance(ent["raw"], dict)+ else {}+ )+ task = dict(task)+ task["id"] = tid+ if ent.get("bucket") == "DRAFT":+ task["kind"] = "action_item"else:- task.setdefault("kind","action_item")- task["approved_at"]=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())- open(TASKS,"a").write(json.dumps(task)+"\n")- open(RESOLVED,"a").write(json.dumps({"id":ent["id"],"decision":"APPROVE","ts":time.time()})+"\n")- log(f"APPROVE {ref} -> promoted {ent['id']} to tasks.jsonl"); acted+=1+ task.setdefault("kind", "action_item")+ task["approved_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())+ open(TASKS, "a").write(json.dumps(task) + "\n")+ open(RESOLVED, "a").write(+ json.dumps({"id": tid, "decision": "APPROVE", "ts": time.time()})+ + "\n"+ )+ log(f"APPROVE {ref} -> promoted {tid} to tasks.jsonl")+ acted += 1else:- open(RESOLVED,"a").write(json.dumps({"id":ent["id"],"decision":"REJECT","ts":time.time()})+"\n")- log(f"REJECT {ref} -> dropped {ent['id']}"); acted+=1- res.add(ent["id"])+ open(RESOLVED, "a").write(+ json.dumps({"id": tid, "decision": "REJECT", "ts": time.time()})+ + "\n"+ )+ log(f"REJECT {ref} -> dropped {tid}")+ acted += 1+ res.add(tid)+ handled_in_msg.add(tid)+log(f"replies: acted={acted}")return 0-if __name__=="__main__":- mode=sys.argv[1] if len(sys.argv)>1 else "--digest"- sys.exit(cmd_digest() if mode=="--digest" else cmd_replies() if mode=="--replies" else 2)++if __name__ == "__main__":+ mode = sys.argv[1] if len(sys.argv) > 1 else "--digest"+ sys.exit(+ cmd_digest()+ if mode == "--digest"+ else cmd_replies()+ if mode == "--replies"+ else 2+ )diff --git a/claude-ops/scripts/ops-pocket-triage.py b/claude-ops/scripts/ops-pocket-triage.pyindex cf912a83..aa13ae4a 100755--- a/claude-ops/scripts/ops-pocket-triage.py+++ b/claude-ops/scripts/ops-pocket-triage.py@@ -182,9 +182,17 @@ Return STRICT JSON, no markdown, no prose outside the JSON:"confidence": 0.0-1.0,"reasoning": "<2-4 sentence summary of why — distill your extended thinking>","scoped_task_description": "<if ACT: a tightened, executable version of the task; if DRAFT: what the draft should cover; else: empty>",- "concerns": ["<any specific risks the executing agent should know>"]+ "concerns": ["<any specific risks the executing agent should know>"],+ "action_preview": "<ASK only — one concrete sentence: what will happen if the owner approves this item. E.g. 'Creates a GitHub issue in your-org/your-repo with the given title and assigns it to you.' Leave empty string for non-ASK verdicts.>",+ "decision_question": "<ASK only, and only when the item is a genuine multi-choice decision — the single question being decided. E.g. 'Which environment should this deploy target?' Leave empty string when it is a simple yes/no.>",+ "options": [+ {{"key": "a", "label": "<concrete option text — what choosing this means>"}},+ {{"key": "b", "label": "<concrete option text>"}}+ ]}}+For the options array: include 2–4 options only when decision_question is non-empty. Use keys a/b/c/d in order. When the item is a plain yes/no ASK, set options to an empty array []. Non-ASK verdicts must also set options to [].+Owner context (NEVER assume otherwise):• Owner name: {owner_name}• Known team members: {team_members}@@ -383,6 +391,24 @@ def route(task: dict, decision: dict) -> str:"model": decision.get("_model"),"decided_at": now_iso(),}+ # Populate decision-digest fields on ASK records so the approval digest can+ # show the owner exactly what approving does and, for multi-choice items,+ # enumerate the options. These fields are optional — old records without them+ # render as plain yes/no items (backward-compatible).+ if verdict == "ASK":+ ap = (decision.get("action_preview") or "").strip()+ dq = (decision.get("decision_question") or "").strip()+ opts = decision.get("options") or []+ if ap:+ routed["action_preview"] = ap+ if dq:+ routed["decision_question"] = dq+ if opts and isinstance(opts, list):+ routed["options"] = [+ {"key": str(o.get("key", "")).lower(), "label": str(o.get("label", ""))}+ for o in opts+ if o.get("key") and o.get("label")+ ]if verdict == "ACT":# Promote: use scoped description if provided, keep original contextif decision.get("scoped_task_description"):diff --git a/claude-ops/tests/test-pocket-approvals-digest.py b/claude-ops/tests/test-pocket-approvals-digest.pynew file mode 100644index 00000000..e6002f84--- /dev/null+++ b/claude-ops/tests/test-pocket-approvals-digest.py@@ -0,0 +1,527 @@+#!/usr/bin/env python3+"""test-pocket-approvals-digest.py — unit tests for the decision-digest and+choice-reply features added to ops-pocket-approvals.py.++Tests run without any external services (no email bridge, no gog).+Run with: python3 tests/test-pocket-approvals-digest.py+"""++from __future__ import annotations++import json+import os+import sys+import time+import types+import importlib.util+from pathlib import Path+from unittest.mock import MagicMock, patch++# ---------------------------------------------------------------------------+# Locate scripts dir relative to this test file+# ---------------------------------------------------------------------------+TESTS_DIR = Path(__file__).resolve().parent+SCRIPTS_DIR = TESTS_DIR.parent / "scripts"++pass_count = 0+fail_count = 0+++def ok(label: str) -> None:+ global pass_count+ print(f" PASS: {label}")+ pass_count += 1+++def err(label: str, detail: str = "") -> None:+ global fail_count+ print(f" FAIL: {label}" + (f" — {detail}" if detail else ""))+ fail_count += 1+++# ---------------------------------------------------------------------------+# Load the module under test with STATE_DIR redirected to a tmp dir+# ---------------------------------------------------------------------------+def _load_approvals(tmp_dir: Path):+ """Import ops-pocket-approvals with POCKET_STATE_DIR pointing at tmp_dir."""+ os.environ["POCKET_STATE_DIR"] = str(tmp_dir)+ spec = importlib.util.spec_from_file_location(+ "approvals", SCRIPTS_DIR / "ops-pocket-approvals.py"+ )+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++# ---------------------------------------------------------------------------+# Synthetic ASK records+# ---------------------------------------------------------------------------++CHOICE_ASK = {+ "id": "ask-choice-001",+ "kind": "action_item",+ "title": "Choose deployment target for the upcoming release",+ "context": (+ "The team discussed three possible deployment targets in the planning session. "+ "Each has different cost and risk profiles. A decision is needed before the "+ "CI pipeline can be configured. The release is scheduled for next Monday."+ ),+ "action_preview": "Configures the CI pipeline to deploy to the chosen environment.",+ "decision_question": "Which environment should the release deploy to?",+ "options": [+ {"key": "a", "label": "Staging only — run integration tests, no prod traffic"},+ {"key": "b", "label": "Canary — 5% prod traffic alongside staging"},+ {"key": "c", "label": "Full production — immediate 100% rollout"},+ ],+ "triage": {+ "verdict": "ASK",+ "confidence": 0.9,+ "reasoning": "Multi-choice deployment decision requiring owner input.",+ "scoped": "",+ "concerns": [],+ "model": "claude-sonnet-4-6",+ "decided_at": "2026-05-30T00:00:00Z",+ },+}++YESNO_ASK = {+ "id": "ask-yesno-002",+ "kind": "action_item",+ "title": "Book assessment call with vendor",+ "context": (+ "Vendor reached out offering a 30-minute product assessment. Scheduling "+ "requires sending a calendar invite via the owner's Google Calendar."+ ),+ "action_preview": (+ "Books a 30-min assessment call with the vendor and sends the calendar invite."+ ),+ "triage": {+ "verdict": "ASK",+ "confidence": 0.85,+ "reasoning": "Outbound calendar action requires owner approval.",+ "scoped": "",+ "concerns": ["touches external calendar"],+ "model": "claude-sonnet-4-6",+ "decided_at": "2026-05-30T00:00:00Z",+ },+}+++# ---------------------------------------------------------------------------+# Helper: write synthetic items to review.jsonl, build a codemap, return mod+# ---------------------------------------------------------------------------+++def _setup_state(tmp: Path, items: list[dict]) -> tuple:+ """Write items to review.jsonl, return (mod, codemap_dict)."""+ review = tmp / "review.jsonl"+ with review.open("w") as f:+ for item in items:+ f.write(json.dumps(item) + "\n")++ mod = _load_approvals(tmp)++ # Build codemap the same way cmd_digest() would+ open_items = mod.open_items()+ codemap = {}+ a = 0+ for it in open_items:+ if it["bucket"] == "ASK":+ a += 1+ code = f"A{a}"+ codemap[code] = {+ "id": it["id"],+ "kind": it["kind"],+ "title": it["title"],+ "bucket": it["bucket"],+ "raw": it["raw"],+ "options": it["options"],+ }+ return mod, codemap, open_items+++# ===========================================================================+# Test group 1: digest rendering+# ===========================================================================+++def test_digest_rendering():+ import tempfile++ tmp = Path(tempfile.mkdtemp())++ mod, codemap, open_items = _setup_state(tmp, [CHOICE_ASK, YESNO_ASK])++ # Render item lines via _render_item+ a_item = next(it for it in open_items if it["id"] == "ask-choice-001")+ b_item = next(it for it in open_items if it["id"] == "ask-yesno-002")++ a_lines = mod._render_item("A1", a_item)+ b_lines = mod._render_item("A2", b_item)++ a_block = "\n".join(a_lines)+ b_block = "\n".join(b_lines)++ # --- Choice item assertions ---+ if "a) Staging only" in a_block:+ ok("choice item: option a listed")+ else:+ err("choice item: option a listed", f"block={a_block!r}")++ if "b) Canary" in a_block:+ ok("choice item: option b listed")+ else:+ err("choice item: option b listed", f"block={a_block!r}")++ if "c) Full production" in a_block:+ ok("choice item: option c listed")+ else:+ err("choice item: option c listed", f"block={a_block!r}")++ if "-> Approve =" in a_block and "Configures the CI pipeline" in a_block:+ ok("choice item: action_preview rendered")+ else:+ err("choice item: action_preview rendered", f"block={a_block!r}")++ if "A1 <letter>" in a_block or "Reply: A1" in a_block:+ ok("choice item: reply instruction shows <code> <letter>")+ else:+ err(+ "choice item: reply instruction shows <code> <letter>", f"block={a_block!r}"+ )++ if "Which environment" in a_block:+ ok("choice item: decision_question rendered")+ else:+ err("choice item: decision_question rendered", f"block={a_block!r}")++ # --- Yes/no item assertions ---+ if "-> Approve =" in b_block and "Books a 30-min" in b_block:+ ok("yes/no item: action_preview rendered")+ else:+ err("yes/no item: action_preview rendered", f"block={b_block!r}")++ if "APPROVE A2" in b_block and "REJECT A2" in b_block:+ ok("yes/no item: APPROVE/REJECT instruction present")+ else:+ err("yes/no item: APPROVE/REJECT instruction present", f"block={b_block!r}")++ # Choice block must NOT show plain APPROVE/REJECT as the primary instruction+ if "APPROVE A1" not in a_block or "Reply: A1" in a_block:+ ok("choice item: no plain APPROVE instruction (letter expected)")+ else:+ err(+ "choice item: no plain APPROVE instruction (letter expected)",+ f"block={a_block!r}",+ )++ # Context should appear+ if "deployment targets in the planning session" in a_block:+ ok("choice item: context shown in digest")+ else:+ err("choice item: context shown in digest", f"block={a_block!r}")+++# ===========================================================================+# Test group 2: _truncate_words+# ===========================================================================+++def test_truncate_words():+ import tempfile++ tmp = Path(tempfile.mkdtemp())+ mod = _load_approvals(tmp)++ short = "Hello world"+ result = mod._truncate_words(short, 20)+ if result == short:+ ok("truncate_words: short string unchanged")+ else:+ err("truncate_words: short string unchanged", repr(result))++ long_text = "The quick brown fox jumped over the lazy dog and kept running."+ result = mod._truncate_words(long_text, 20)+ if result.endswith("...") and len(result) <= 23: # room for "..."+ ok("truncate_words: long string truncated with ellipsis")+ else:+ err("truncate_words: long string truncated with ellipsis", repr(result))++ # Must not cut mid-word: the text before "..." must end with a complete word,+ # i.e. the last char before the ellipsis suffix is not in the middle of a word.+ # Strip the "..." suffix, then verify the remainder ends on a word boundary+ # (ends with an alphanumeric char that matches a word from the original).+ before_ellipsis = result[:-3] if result.endswith("...") else result+ last_word = before_ellipsis.split()[-1] if before_ellipsis.split() else ""+ if last_word and last_word in long_text.split():+ ok("truncate_words: cut on word boundary")+ else:+ err("truncate_words: cut on word boundary", repr(result))+++# ===========================================================================+# Test group 3: reply parser — choice reply promotes with chosen_option+# ===========================================================================+++def test_reply_parser_choice():+ import tempfile++ tmp = Path(tempfile.mkdtemp())+ mod = _load_approvals(tmp)++ # Synthesize codemap with the choice item at A1+ codemap = {+ "A1": {+ "id": "ask-choice-001",+ "kind": "action_item",+ "title": "Choose deployment target",+ "bucket": "ASK",+ "raw": {+ "id": "ask-choice-001",+ "kind": "action_item",+ "title": "Choose deployment target",+ },+ "options": [+ {"key": "a", "label": "Staging only"},+ {"key": "b", "label": "Canary"},+ {"key": "c", "label": "Full production"},+ ],+ }+ }+ (tmp / "approval-codemap.json").write_text(json.dumps(codemap))+ (tmp / "email-config.json").write_text(+ json.dumps({"self_address": "[email protected]"})+ )++ tasks_file = tmp / "tasks.jsonl"+ resolved_file = tmp / "approval-resolved.jsonl"++ # Mock gog to return one email with "A1 b"+ fake_msgs = [{"id": "msg-001", "from": "[email protected] <[email protected]>"}]+ fake_body = "A1 b"+ fake_subj = "Re: [Pocket] 2 item(s) need approval"++ with (+ patch.object(mod, "_gog_search_replies", return_value=fake_msgs),+ patch.object(mod, "_gog_body_and_subject", return_value=(fake_body, fake_subj)),+ ):+ mod.cmd_replies()++ # Verify task was written with chosen_option+ if tasks_file.exists():+ task_line = tasks_file.read_text().strip()+ if task_line:+ task = json.loads(task_line)+ if task.get("chosen_option") == "b":+ ok("choice reply: chosen_option='b' written to tasks.jsonl")+ else:+ err("choice reply: chosen_option='b'", f"task={task}")+ if task.get("chosen_option_label") == "Canary":+ ok("choice reply: chosen_option_label='Canary' written")+ else:+ err("choice reply: chosen_option_label", f"task={task}")+ else:+ err("choice reply: tasks.jsonl written but empty")+ else:+ err("choice reply: tasks.jsonl not created")++ # Verify resolved record+ if resolved_file.exists():+ rec = json.loads(resolved_file.read_text().strip())+ if rec.get("decision") == "CHOOSE" and rec.get("chosen") == "b":+ ok("choice reply: resolved record decision=CHOOSE chosen=b")+ else:+ err("choice reply: resolved record", f"rec={rec}")+ else:+ err("choice reply: approval-resolved.jsonl not created")+++# ===========================================================================+# Test group 4: reply parser — invalid choice letter is rejected+# ===========================================================================+++def test_reply_parser_invalid_letter():+ import tempfile++ tmp = Path(tempfile.mkdtemp())+ mod = _load_approvals(tmp)++ codemap = {+ "A1": {+ "id": "ask-choice-001",+ "kind": "action_item",+ "title": "Choose something",+ "bucket": "ASK",+ "raw": {"id": "ask-choice-001"},+ "options": [+ {"key": "a", "label": "Option A"},+ {"key": "b", "label": "Option B"},+ ],+ }+ }+ (tmp / "approval-codemap.json").write_text(json.dumps(codemap))+ (tmp / "email-config.json").write_text(+ json.dumps({"self_address": "[email protected]"})+ )++ fake_msgs = [{"id": "msg-002", "from": "[email protected]"}]+ with (+ patch.object(mod, "_gog_search_replies", return_value=fake_msgs),+ patch.object(+ mod,+ "_gog_body_and_subject",+ return_value=("A1 z", "Re: [Pocket] 1 item(s) need approval"),+ ),+ ):+ mod.cmd_replies()++ tasks_file = tmp / "tasks.jsonl"+ if not tasks_file.exists() or not tasks_file.read_text().strip():+ ok("invalid letter: task NOT promoted (correctly rejected)")+ else:+ err("invalid letter: task should not be promoted", tasks_file.read_text())+++# ===========================================================================+# Test group 5: reply parser — plain APPROVE on choice item is ambiguous+# ===========================================================================+++def test_reply_parser_approve_on_choice_is_ambiguous():+ import tempfile++ tmp = Path(tempfile.mkdtemp())+ mod = _load_approvals(tmp)++ codemap = {+ "A1": {+ "id": "ask-choice-001",+ "kind": "action_item",+ "title": "Choose something",+ "bucket": "ASK",+ "raw": {"id": "ask-choice-001"},+ "options": [+ {"key": "a", "label": "Option A"},+ {"key": "b", "label": "Option B"},+ ],+ }+ }+ (tmp / "approval-codemap.json").write_text(json.dumps(codemap))+ (tmp / "email-config.json").write_text(+ json.dumps({"self_address": "[email protected]"})+ )++ fake_msgs = [{"id": "msg-003", "from": "[email protected]"}]+ with (+ patch.object(mod, "_gog_search_replies", return_value=fake_msgs),+ patch.object(+ mod,+ "_gog_body_and_subject",+ return_value=("APPROVE A1", "Re: [Pocket] 1 item(s) need approval"),+ ),+ ):+ mod.cmd_replies()++ tasks_file = tmp / "tasks.jsonl"+ if not tasks_file.exists() or not tasks_file.read_text().strip():+ ok("bare APPROVE on choice item: left unresolved (ambiguous)")+ else:+ err(+ "bare APPROVE on choice item: should be ambiguous, not promoted",+ tasks_file.read_text(),+ )+++# ===========================================================================+# Test group 6: reply parser — plain APPROVE on yes/no item still works+# ===========================================================================+++def test_reply_parser_approve_yesno():+ import tempfile++ tmp = Path(tempfile.mkdtemp())+ mod = _load_approvals(tmp)++ codemap = {+ "A2": {+ "id": "ask-yesno-002",+ "kind": "action_item",+ "title": "Book vendor call",+ "bucket": "ASK",+ "raw": {+ "id": "ask-yesno-002",+ "kind": "action_item",+ "title": "Book vendor call",+ },+ "options": [],+ }+ }+ (tmp / "approval-codemap.json").write_text(json.dumps(codemap))+ (tmp / "email-config.json").write_text(+ json.dumps({"self_address": "[email protected]"})+ )++ fake_msgs = [{"id": "msg-004", "from": "[email protected]"}]+ with (+ patch.object(mod, "_gog_search_replies", return_value=fake_msgs),+ patch.object(+ mod,+ "_gog_body_and_subject",+ return_value=("APPROVE A2", "Re: [Pocket] 2 item(s) need approval"),+ ),+ ):+ mod.cmd_replies()++ tasks_file = tmp / "tasks.jsonl"+ if tasks_file.exists() and tasks_file.read_text().strip():+ task = json.loads(tasks_file.read_text().strip())+ if task.get("id") == "ask-yesno-002":+ ok("yes/no APPROVE: task promoted to tasks.jsonl")+ else:+ err("yes/no APPROVE: wrong id in task", str(task))+ if "chosen_option" not in task:+ ok("yes/no APPROVE: no chosen_option field (correct)")+ else:+ err("yes/no APPROVE: should not have chosen_option", str(task))+ else:+ err("yes/no APPROVE: tasks.jsonl not created or empty")+++# ===========================================================================+# Run all tests+# ===========================================================================++if __name__ == "__main__":+ print("Testing ops-pocket-approvals digest + choice-reply features")+ print("")++ print("--- Digest rendering ---")+ test_digest_rendering()+ print("")++ print("--- _truncate_words ---")+ test_truncate_words()+ print("")++ print("--- Reply parser: choice reply ---")+ test_reply_parser_choice()+ print("")++ print("--- Reply parser: invalid letter rejected ---")+ test_reply_parser_invalid_letter()+ print("")++ print("--- Reply parser: bare APPROVE on choice item is ambiguous ---")+ test_reply_parser_approve_on_choice_is_ambiguous()+ print("")++ print("--- Reply parser: APPROVE on yes/no item still works ---")+ test_reply_parser_approve_yesno()+ print("")++ print("---")+ print(f"Results: {pass_count} passed, {fail_count} failed")+ sys.exit(0 if fail_count == 0 else 1)