Skip to content

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.

fix(inbox): reopen forgotten unanswered asks, scan accounts in parallel (#961)

Aurora Capitald051365a8e6b
diff --git a/claude-ops/bin/ops-inbox-archive-set b/claude-ops/bin/ops-inbox-archive-set
index f0a08bf7..d4619922 100755
--- a/claude-ops/bin/ops-inbox-archive-set
+++ b/claude-ops/bin/ops-inbox-archive-set
@@ -536,7 +536,12 @@ def main():
for e in extra:
for row in e["archive"]:
swept.extend([row.get("jid")] + list(row.get("alt_jids") or []))
- stores = [(scan or {}).get("whatsapp_account", {}).get("store")]
+ stores = []
+ if (scan or {}).get("whatsapp_account", {}).get("store"):
+ stores.append(scan["whatsapp_account"]["store"])
+ for acct in (scan or {}).get("whatsapp_accounts", []):
+ if acct.get("store"):
+ stores.append(acct["store"])
stores += list(args.wa_store or [])
write_sweep_watermarks([j for j in swept if j], stores)
result["applied"] = True
diff --git a/claude-ops/bin/ops-inbox-scan b/claude-ops/bin/ops-inbox-scan
index 531d77cf..c658b412 100755
--- a/claude-ops/bin/ops-inbox-scan
+++ b/claude-ops/bin/ops-inbox-scan
@@ -24,21 +24,25 @@
# READ-ONLY: opens every sqlite db in immutable/read-only mode; never sends,
# archives, or mutates anything. All sending stays in the skill under Rule 6.
#
-# FULL INBOX, ALWAYS. Both channels scan everything that is not archived, never
-# just the unread. WhatsApp's working set is `archived=0`; email's is `in:inbox`.
-# Neither is sliced by a recency window, because an unanswered ask from three
-# weeks ago is still an unanswered ask. --days sizes only the WhatsApp send-log
-# lookback used for reconciliation; it never hides a chat or a mail.
+# FULL INBOX, ALWAYS. Unread is a DISPLAY state — never the working set.
+# WhatsApp open set is `archived=0`; email open set is `in:inbox`. On top of
+# that, --debt-days (default 90) reopens FORGOTTEN unanswered asks that were
+# archived, read, or otherwise put away while the other person still holds the
+# ball: last inbound is a real question, we never answered (or they asked
+# again after us), inside the debt window. History older than --debt-days
+# stays shut so a sweep cannot drag 2025 back in.
#
# FLAGS:
# --whatsapp-only / --email-only limit to one channel
# --days N send-log lookback, in days (default 7)
+# --debt-days N forgotten-ask window, in days (default 90)
# --email-query Q Gmail working set (default "in:inbox")
# --email-max N max Gmail results (default 400)
# --gmail-account ADDR override Gmail account (default: gog default)
# --wa-store DB WhatsApp messages.db to scan
# --bridge-port N bridge REST port for that store
# --all-accounts scan EVERY agent-enabled account, not one
+# (default when no --wa-store is given)
# --peer-store DB another account's store, read ONLY to see
# whether a person was already answered there
# (repeatable; auto-discovered by default)
@@ -54,6 +58,7 @@
set -euo pipefail
DAYS=7
+DEBT_DAYS=90
DO_WA=1
DO_EMAIL=1
GMAIL_ACCOUNT="${GMAIL_ACCOUNT:-}"
@@ -73,6 +78,9 @@ while [ $# -gt 0 ]; do
--days)
[ $# -ge 2 ] || { echo "ops-inbox-scan: --days requires a value" >&2; exit 2; }
DAYS="$2"; shift 2 ;;
+ --debt-days)
+ [ $# -ge 2 ] || { echo "ops-inbox-scan: --debt-days requires a value" >&2; exit 2; }
+ DEBT_DAYS="$2"; shift 2 ;;
--email-query)
[ $# -ge 2 ] || { echo "ops-inbox-scan: --email-query requires a value" >&2; exit 2; }
EMAIL_QUERY="$2"; shift 2 ;;
@@ -107,6 +115,10 @@ done
# an `unread` listing — and `unread` is a DISPLAY state, empty for every thread
# the owner already opened on their phone. A person's real unanswered ask does
# not have to be unread. So: scan EVERY enabled account and merge, labelled.
+# Default: when the caller did not pin a store, scan every enabled account.
+if [ "$ALL_ACCOUNTS" = 0 ] && [ -z "$WA_STORE_OVERRIDE$BRIDGE_PORT_OVERRIDE" ] && [ "$DO_WA" = 1 ]; then
+ ALL_ACCOUNTS=1
+fi
if [ "$ALL_ACCOUNTS" = 1 ]; then
[ -n "$WA_STORE_OVERRIDE$BRIDGE_PORT_OVERRIDE" ] && {
echo "ops-inbox-scan: --all-accounts cannot be combined with --wa-store/--bridge-port" >&2
@@ -115,10 +127,11 @@ if [ "$ALL_ACCOUNTS" = 1 ]; then
_resolver="$(dirname "$0")/ops-wa-accounts"
[ -x "$_resolver" ] || { echo "ops-inbox-scan: ops-wa-accounts not found" >&2; exit 4; }
_self="$0"
- "$_resolver" | OIS_SELF="$_self" OIS_DAYS="$DAYS" OIS_DO_EMAIL="$DO_EMAIL" \
+ "$_resolver" | OIS_SELF="$_self" OIS_DAYS="$DAYS" OIS_DEBT_DAYS="$DEBT_DAYS" OIS_DO_EMAIL="$DO_EMAIL" \
OIS_EMAIL_QUERY="$EMAIL_QUERY" OIS_EMAIL_MAX="$EMAIL_MAX" \
OIS_GMAIL_ACCOUNT="$GMAIL_ACCOUNT" OIS_PRETTY="$PRETTY" python3 -c '
import json, os, subprocess, sys
+from concurrent.futures import ThreadPoolExecutor, as_completed
blob = json.load(sys.stdin)
enabled = [a for a in blob.get("accounts", []) if a.get("agent_enabled") is True]
@@ -128,12 +141,14 @@ if not enabled:
self_bin = os.environ["OIS_SELF"]
merged = {"generated_at": None, "window_days": int(os.environ["OIS_DAYS"]),
+ "debt_days": int(os.environ.get("OIS_DEBT_DAYS", "90")),
"notes": [], "whatsapp_accounts": []}
-first = True
-for acct in enabled:
+
+def scan_one(acct):
store = acct.get("store") or acct.get("remote_store") or ""
port = acct.get("port")
cmd = [self_bin, "--whatsapp-only", "--days", os.environ["OIS_DAYS"],
+ "--debt-days", os.environ.get("OIS_DEBT_DAYS", "90"),
"--wa-store", store, "--bridge-port", str(port)]
env = dict(os.environ, OIS_SSH=acct.get("ssh") or "",
OIS_SSH_FALLBACK=acct.get("ssh_fallback") or "",
@@ -144,27 +159,42 @@ for acct in enabled:
one = json.loads(out.stdout or "{}")
except Exception as exc: # a broken account must be LOUD, never silent
one = {"whatsapp": {"reachable": False, "error": str(exc)}}
- merged["generated_at"] = merged["generated_at"] or one.get("generated_at")
- merged["notes"].extend(one.get("notes", []))
- merged["whatsapp_accounts"].append({
- "account": acct.get("label"), "phone": acct.get("phone"),
- "bridge_port": port, "store": store,
- **one.get("whatsapp", {}),
- })
- first = False
+ return acct, store, port, one
-if os.environ.get("OIS_DO_EMAIL") == "1":
- cmd = [self_bin, "--email-only", "--email-query", os.environ["OIS_EMAIL_QUERY"],
- "--email-max", os.environ["OIS_EMAIL_MAX"]]
- if os.environ.get("OIS_GMAIL_ACCOUNT"):
- cmd += ["--gmail-account", os.environ["OIS_GMAIL_ACCOUNT"]]
- try:
- out = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
- one = json.loads(out.stdout or "{}")
- merged["email"] = one.get("email")
+workers = min(len(enabled), 4)
+with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
+ futs = [pool.submit(scan_one, a) for a in enabled]
+ email_fut = None
+ if os.environ.get("OIS_DO_EMAIL") == "1":
+ def scan_email():
+ cmd = [self_bin, "--email-only", "--email-query", os.environ["OIS_EMAIL_QUERY"],
+ "--email-max", os.environ["OIS_EMAIL_MAX"]]
+ if os.environ.get("OIS_GMAIL_ACCOUNT"):
+ cmd += ["--gmail-account", os.environ["OIS_GMAIL_ACCOUNT"]]
+ out = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
+ return json.loads(out.stdout or "{}")
+ email_fut = pool.submit(scan_email)
+ by_label = {}
+ for fut in as_completed(futs):
+ acct, store, port, one = fut.result()
+ by_label[id(acct)] = (acct, store, port, one)
+ # Preserve resolver order so the same inbox is labelled the same way every run.
+ for acct in enabled:
+ _acct, store, port, one = by_label[id(acct)]
+ merged["generated_at"] = merged["generated_at"] or one.get("generated_at")
merged["notes"].extend(one.get("notes", []))
- except Exception as exc:
- merged["email"] = {"reachable": False, "note": "email scan failed: %s" % exc}
+ merged["whatsapp_accounts"].append({
+ "account": acct.get("label"), "phone": acct.get("phone"),
+ "bridge_port": port, "store": store,
+ **one.get("whatsapp", {}),
+ })
+ if email_fut is not None:
+ try:
+ one = email_fut.result()
+ merged["email"] = one.get("email")
+ merged["notes"].extend(one.get("notes", []))
+ except Exception as exc:
+ merged["email"] = {"reachable": False, "note": "email scan failed: %s" % exc}
merged["counts"] = {
"whatsapp": {a["account"]: {b: len(a.get(b) or []) for b in
@@ -294,7 +324,7 @@ if [ "$DO_EMAIL" = 1 ] && [ -z "$GMAIL_ACCOUNT" ]; then
| grep -oE '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}' | head -1 || true)"
fi
-export OIS_DAYS="$DAYS" OIS_DO_WA="$DO_WA" OIS_DO_EMAIL="$DO_EMAIL"
+export OIS_DAYS="$DAYS" OIS_DEBT_DAYS="$DEBT_DAYS" OIS_DO_WA="$DO_WA" OIS_DO_EMAIL="$DO_EMAIL"
export OIS_WA_MSGDB="$WA_MSGDB" OIS_WA_WADB="$WA_WADB"
export OIS_GMAIL_ACCOUNT="$GMAIL_ACCOUNT" OIS_PRETTY="$PRETTY"
export OIS_WA_PHONE="$WA_ACCOUNT_PHONE" OIS_WA_PORT="$BRIDGE_PORT"
@@ -438,6 +468,7 @@ import os, sys, json, sqlite3, re
from datetime import datetime, timezone
DAYS = int(os.environ.get("OIS_DAYS", "7"))
+DEBT_DAYS = int(os.environ.get("OIS_DEBT_DAYS", "90"))
DO_WA = os.environ.get("OIS_DO_WA") == "1"
DO_EMAIL = os.environ.get("OIS_DO_EMAIL") == "1"
MSGDB = os.environ.get("OIS_WA_MSGDB", "")
@@ -828,6 +859,65 @@ def scan_whatsapp():
"sweep, so the archive no longer means dealt-with" % reopened
)
+ # FORGOTTEN DEBT. An archived/read thread can still hold an unanswered ask
+ # the owner put away and never came back to. Unread is a display state, so
+ # this must not depend on unread_count. Narrow: last inbound is a real
+ # question, we never answered (or they asked again after us), inside
+ # --debt-days. Older history stays shut (the 316-chat blowout).
+ ASK_RE = re.compile(
+ r"\?|\b(kun|kan|could|can|would|please|graag|laat.*weten|let me know|"
+ r"need|nodig|wanneer|when|hoe|how|wat|what|waarom|why|stuur|send|"
+ r"call|bel|oké met|oke met|ok with)\b",
+ re.IGNORECASE)
+ forgotten = 0
+ forgotten_jids = set()
+ try:
+ debt_rows = con.execute(
+ "SELECT c.jid AS jid, c.name AS name, "
+ " c.last_message_time AS last_message_time, "
+ " (SELECT content FROM messages i WHERE i.chat_jid = c.jid "
+ " AND i.is_from_me = 0 ORDER BY i.timestamp DESC LIMIT 1) AS last_in_text, "
+ " (SELECT MAX(i.timestamp) FROM messages i "
+ " WHERE i.chat_jid = c.jid AND i.is_from_me = 0) AS last_in, "
+ " (SELECT MAX(o.timestamp) FROM messages o "
+ " WHERE o.chat_jid = c.jid AND o.is_from_me = 1) AS last_out "
+ "FROM chats c WHERE c.archived = 1 "
+ " AND c.last_message_time >= datetime('now', ?) "
+ "ORDER BY c.last_message_time DESC",
+ (f"-{DEBT_DAYS} days",),
+ ).fetchall()
+ except sqlite3.Error as exc:
+ debt_rows = []
+ notes.append(f"whatsapp: forgotten-debt check failed ({exc})")
+ for r in debt_rows:
+ jid = r["jid"]
+ if jid in seen_jids:
+ continue
+ if jid.endswith("@broadcast") or jid.endswith("@newsletter") or jid.endswith("@g.us"):
+ continue
+ last_in = r["last_in"]
+ last_out = r["last_out"]
+ body = (r["last_in_text"] or "").strip()
+ if not last_in or not body:
+ continue
+ mark = marks.get(jid)
+ if mark and last_in <= mark:
+ continue
+ if last_out and last_out >= last_in:
+ continue
+ if not ASK_RE.search(body):
+ continue
+ chats.append(r)
+ seen_jids.add(jid)
+ forgotten_jids.add(jid)
+ forgotten += 1
+ if forgotten:
+ notes.append(
+ "whatsapp: %d forgotten unanswered ask(s) reopened inside the "
+ "%d-day debt window (archived/read, still their ball)"
+ % (forgotten, DEBT_DAYS)
+ )
+
# Build merged DM groups keyed by canonical jid.
groups = {} # canonical_jid -> {member_jids:set, name, latest_ts}
g_chats = [] # @g.us
@@ -894,6 +984,8 @@ def scan_whatsapp():
"last_from_me": bool(last["is_from_me"]),
"preview": preview,
}
+ if forgotten_jids.intersection(members):
+ item["forgotten"] = True
if last["is_from_me"]:
out["waiting"].append(item)
else:
@@ -1085,6 +1177,7 @@ def scan_email():
result = {
"generated_at": now.isoformat(),
"window_days": DAYS,
+ "debt_days": DEBT_DAYS,
"peer_stores_read": PEER_STORES,
"notes": notes,
}
diff --git a/claude-ops/bin/ops-inbox-zero b/claude-ops/bin/ops-inbox-zero
index a20eea5b..d5e4f390 100755
--- a/claude-ops/bin/ops-inbox-zero
+++ b/claude-ops/bin/ops-inbox-zero
@@ -126,8 +126,8 @@ if [ "$DO_WA" = 1 ]; then
fi
# -------- 3. scan ------------------------------------------------------------
-log "step 2/9 — ops-inbox-scan --pretty --days ${DAYS}"
-if ! ops-inbox-scan --pretty --days "$DAYS" > "$SCAN_OUT" 2>"$SCAN_OUT.err"; then
+log "step 2/9 — ops-inbox-scan --pretty --days ${DAYS} --all-accounts"
+if ! ops-inbox-scan --pretty --days "$DAYS" --all-accounts > "$SCAN_OUT" 2>"$SCAN_OUT.err"; then
log "scan FAILED — see $SCAN_OUT.err; falling back to per-channel"
log "falling back to per-channel scans is the agent's job; exiting 3"
exit 3
diff --git a/claude-ops/skills/ops-inbox/SKILL.md b/claude-ops/skills/ops-inbox/SKILL.md
index 159d8a54..86298cc9 100644
--- a/claude-ops/skills/ops-inbox/SKILL.md
+++ b/claude-ops/skills/ops-inbox/SKILL.md
@@ -145,13 +145,26 @@ Every run, in order:
surfaced individually with thread context, never as a line in a digest.
Before drafting to any person, load `relations` for their brief and open
commitments.
-1. Resolve the WhatsApp account (`ops-wa-accounts` — never hardcode a port).
-2. Freshness: `~/bin/wa-inbox-fresh.sh` (blocking, bounded). Then `bin/ops-inbox-scan --all-accounts`. Never an unread listing: unread is a display state and is empty for every thread already opened on a phone.
-3. **All-context sweep** (Rule 9 + `references/details.md` "ALL CONTEXT SOURCES"): query every configured calendar, mailbox, and messaging channel before any schedule claim or NEEDS_REPLY draft. Google Calendar alone is not enough — Notion show/calendar databases count when Notion is configured. A miss on one store is not absence.
+1. Resolve WhatsApp accounts (`ops-wa-accounts` — never hardcode a port). Scan every agent-enabled number.
+2. Freshness: `~/bin/wa-inbox-fresh.sh` (blocking, bounded). Then `bin/ops-inbox-scan` (defaults to every enabled account, `--debt-days 90`). Never an unread listing: unread is a display state and is empty for every thread already opened on a phone. Forgotten unanswered asks (archived/read, still their ball, inside 90 days) come back tagged `forgotten`.
+2b. **Every other channel in the same pass, in parallel:** iMessage/SMS (`$HERMES_HOME/bin/imessage-inbox-scan --days 30` — copies `-wal`/`-shm` first or recent messages are invisible; alphanumeric shortcodes and OTP bodies are `fyi`, never `needs_reply`). Slack (`conversations_unreads`, DMs first). Telegram user dialogs if configured. Email is already in the scan. A miss on one channel is not absence on another.
+3. **All-context sweep** (Rule 9 + `references/details.md` "ALL CONTEXT SOURCES"): query every configured calendar, mailbox, and messaging channel before any schedule claim or NEEDS_REPLY draft. Google Calendar alone is not enough — Notion show/calendar databases count when Notion is configured.
4. `bin/ops-inbox-archive-set` report-only. Present KEEP vs ARCHIVE; `--apply` only after explicit OK.
-5. Deep-read KEEP / NEEDS_REPLY. Fan out if volume (`references/fan-out.md`).
+5. Deep-read KEEP / NEEDS_REPLY. Fan out if volume (`references/fan-out.md`). One read-only worker per channel, then one per KEEP thread-chunk. Stage the next draft the moment the previous card is answered — no "next?" pause.
6. Stage drafts one at a time (Rule 6). Archive after a verified send.
+## Every suggested send carries reasoning
+
+A draft without this block is incomplete. Never show only the outbound text.
+
+Print, in the same bubble as the exact draft, three short lines in plain words:
+
+- **Why this reply:** what in the live thread this answers (quote the ask, not a vibe).
+- **Expected outcome:** what happens after they read it (they stop chasing, they can act, the thread closes).
+- **Why that is good:** the concrete gain.
+
+If you cannot fill all three from the thread, do not stage. Go read more.
+
Channel processing, FULL-THREAD AWARENESS GATE, and per-channel recipes: `references/details.md`.
## Standing behavior: RUN WIDE — parallel subagents / agent-teams / workflow by DEFAULT
diff --git a/claude-ops/skills/ops-inbox/references/details.md b/claude-ops/skills/ops-inbox/references/details.md
index 6c97a9ff..b2b378c0 100644
--- a/claude-ops/skills/ops-inbox/references/details.md
+++ b/claude-ops/skills/ops-inbox/references/details.md
@@ -234,7 +234,11 @@ The user does NOT remember every thread. For EVERY message you present, you MUST
Last msg: [full body of their last message]
Context: [related threads/decisions/deadlines found]
- Draft reply: "[contextually aware draft based on all above]"
+ Draft reply: "[exact outbound bytes]"
+
+ Why this reply: [what in the live thread this answers]
+ Expected outcome: [what happens after they read it]
+ Why that is good: [concrete gain, no vibe]
```
Stage this per the **PER-DRAFT APPROVAL** principle below. On Telegram/Hermes, deliver the block above as a standalone FINAL draft bubble in TURN 1, with no approval card in that turn. In TURN 2, after the owner's next message or continuation event, show the one-item `[Send]` `[Handle this for me]` `[Edit]` `[Skip]` card. Never combine items.
diff --git a/claude-ops/tests/test-ops-inbox-cross-account.sh b/claude-ops/tests/test-ops-inbox-cross-account.sh
index a19b8ce6..d5e2e5c9 100755
--- a/claude-ops/tests/test-ops-inbox-cross-account.sh
+++ b/claude-ops/tests/test-ops-inbox-cross-account.sh
@@ -272,7 +272,7 @@ ts = (datetime.datetime.now(datetime.timezone.utc)
con.execute("INSERT INTO chats VALUES ('888111@lid','Swept',?,1,0)", (ts,))
con.execute("INSERT INTO contacts VALUES ('888111@lid','Swept','888111','test',0)")
con.execute("INSERT INTO messages VALUES ('s1','888111@lid','888111',"
- "'Anything left to do?',?,0,'','')", (ts,))
+ "'thanks!',?,0,'','')", (ts,))
con.commit(); con.close()
PY
diff --git a/claude-ops/tests/test-ops-inbox-forgotten-debt.sh b/claude-ops/tests/test-ops-inbox-forgotten-debt.sh
new file mode 100755
index 00000000..6eb421cd
--- /dev/null
+++ b/claude-ops/tests/test-ops-inbox-forgotten-debt.sh
@@ -0,0 +1,138 @@
+#!/usr/bin/env bash
+# test-ops-inbox-forgotten-debt.sh — archived/read unanswered asks still surface.
+#
+# The owner asked (2026-09-11): capture everyone that still deserves a response,
+# including forgotten threads, read or unread, inbox or not. Unread is a display
+# state. Archive means "dealt with as of now", not "never owed a reply".
+#
+# Narrow: last inbound is a real question, we never answered (or they asked
+# again after us), inside --debt-days. Courtesy tails and ancient history stay
+# shut (the 316-chat blowout).
+#
+# Mutation-proof: drop the debt scan, or ignore ASK_RE, and this goes red.
+set -uo pipefail
+
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$HERE/.." && pwd)"
+SCAN="$ROOT/bin/ops-inbox-scan"
+
+pass=0; fail=0
+ok() { pass=$((pass+1)); printf ' ok %s\n' "$1"; }
+bad() { fail=$((fail+1)); printf ' FAIL %s\n' "$1"; }
+
+TMP="$(mktemp -d "${TMPDIR:-/tmp}/ops-forgotten.XXXXXX")"
+trap 'rm -rf "$TMP"' EXIT
+
+STORE="$TMP/whatsapp-bridge/store"
+mkdir -p "$STORE"
+
+python3 - "$STORE/messages.db" <<'PY'
+import sqlite3, sys
+from datetime import datetime, timedelta, timezone
+
+con = sqlite3.connect(sys.argv[1])
+con.execute("CREATE TABLE chats (jid TEXT PRIMARY KEY, name TEXT, "
+ "last_message_time TIMESTAMP, archived INTEGER NOT NULL DEFAULT 0, "
+ "unread_count INTEGER DEFAULT 0)")
+con.execute("CREATE TABLE messages (id TEXT, chat_jid TEXT, sender TEXT, "
+ "content TEXT, timestamp TIMESTAMP, is_from_me BOOLEAN, "
+ "media_type TEXT, filename TEXT, PRIMARY KEY (id, chat_jid))")
+con.execute("CREATE TABLE contacts (jid TEXT PRIMARY KEY, name TEXT, "
+ "phone TEXT, source TEXT, updated_at INTEGER)")
+
+now = datetime.now(timezone.utc)
+def ts(**kw):
+ return (now - timedelta(**kw)).strftime("%Y-%m-%d %H:%M:%S+00:00")
+
+def chat(jid, name, last, archived, unread=0):
+ con.execute("INSERT INTO chats VALUES (?,?,?,?,?)",
+ (jid, name, last, archived, unread))
+ con.execute("INSERT INTO contacts VALUES (?,?,?,'test',0)",
+ (jid, name, jid.split("@")[0]))
+
+def msg(mid, jid, body, when, from_me):
+ con.execute("INSERT INTO messages VALUES (?,?,?,?,?,?,'','')",
+ (mid, jid, jid.split("@")[0], body, when, 1 if from_me else 0))
+
+# 1. Forgotten: archived, already read (unread=0), still their question.
+chat("111@lid", "Forgotten", ts(days=20), 1, 0)
+msg("a1", "111@lid", "kun je even kijken of de factuur klopt?", ts(days=20), False)
+
+# 2. Courtesy tail, archived. MUST stay shut.
+chat("222@lid", "Thanks", ts(days=10), 1, 0)
+msg("b1", "222@lid", "thanks!", ts(days=10), False)
+
+# 3. Ancient unanswered ask. MUST stay shut (316-chat blowout).
+chat("333@lid", "Ancient", ts(days=400), 1, 0)
+msg("c1", "333@lid", "hey are you around?", ts(days=400), False)
+
+# 4. We already answered, then archived. MUST stay shut.
+chat("444@lid", "Answered", ts(days=15), 1, 0)
+msg("d1", "444@lid", "can you send the file?", ts(days=16), False)
+msg("d2", "444@lid", "sent it just now", ts(days=15), True)
+
+# 5. Open inbox, unread=0, still a question. Working set, not forgotten.
+chat("555@lid", "Open", ts(hours=3), 0, 0)
+msg("e1", "555@lid", "wanneer kunnen we bellen?", ts(hours=3), False)
+
+con.commit(); con.close()
+PY
+
+scan_json() {
+ "$SCAN" --whatsapp-only --no-peer-stores --debt-days 90 \
+ --wa-store "$STORE/messages.db" --bridge-port 8099 2>/dev/null
+}
+
+bucket_of() {
+ python3 -c '
+import json, sys
+d = json.loads(sys.stdin.read() or "{}")
+wa = d.get("whatsapp", {})
+who = sys.argv[1]
+for b in ("needs_reply", "waiting", "groups", "fyi"):
+ for row in wa.get(b, []):
+ if row.get("who") == who:
+ flag = "forgotten" if row.get("forgotten") else "live"
+ print(b + ":" + flag); sys.exit(0)
+print("ABSENT")' "$2" <<<"$1"
+}
+
+echo "forgotten debt window 90d"
+OUT="$(scan_json)"
+if [ -z "$OUT" ]; then
+ bad "scan produced no output"
+else
+ b="$(bucket_of "$OUT" Forgotten)"
+ [ "$b" = "needs_reply:forgotten" ] && ok "archived unread=0 question comes back as forgotten" \
+ || bad "Forgotten landed in '$b'"
+
+ b="$(bucket_of "$OUT" Thanks)"
+ [ "$b" = "ABSENT" ] && ok "courtesy tail stays archived" \
+ || bad "Thanks came back as '$b'"
+
+ b="$(bucket_of "$OUT" Ancient)"
+ [ "$b" = "ABSENT" ] && ok "ancient history stays shut" \
+ || bad "Ancient came back as '$b'"
+
+ b="$(bucket_of "$OUT" Answered)"
+ [ "$b" = "ABSENT" ] && ok "we-answered-then-archived stays shut" \
+ || bad "Answered came back as '$b'"
+
+ b="$(bucket_of "$OUT" Open)"
+ [ "$b" = "needs_reply:live" ] && ok "open inbox question is live, not forgotten" \
+ || bad "Open landed in '$b'"
+
+ grep -q "forgotten unanswered" <<<"$OUT" \
+ && ok "scan states that it reopened forgotten asks" \
+ || bad "no note explaining forgotten reopen"
+fi
+
+echo "debt window bounds the reopen"
+OUT7="$("$SCAN" --whatsapp-only --no-peer-stores --debt-days 7 \
+ --wa-store "$STORE/messages.db" --bridge-port 8099 2>/dev/null)"
+b="$(bucket_of "$OUT7" Forgotten)"
+[ "$b" = "ABSENT" ] && ok "20-day ask stays shut when --debt-days is 7" \
+ || bad "Forgotten came back as '$b' inside a 7-day window"
+
+printf '\n%d passed, %d failed\n' "$pass" "$fail"
+[ "$fail" -eq 0 ]