Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ calls. Babel's broker alone cannot establish that guarantee for a hosted ChatGPT
Grok, or Codex receiver. The synthetic wake-claim tests count stub enqueue attempts
and explicitly reproduce both remaining external-receiver limitations.

Limits: 16 KiB UTF-8/message, 64 KiB HTTP requests, 30 new messages/sender/minute and a separate 300/owner/minute budget shared by its sessions, 100 hops/thread by default (optional schema 3 per-conversation caps up to 100), 100,000 retained messages, four active MCP subscriptions/recipient and 100 retained subscription identities. Both message budgets use durable rolling 60-second windows; 429 errors identify the exhausted budget. Retries of an existing identical message ID do not consume new-message capacity. Capacity failure closes safely instead of silently deleting dedup history. Review storage usage and arrange operator maintenance/backups; there is no automatic destructive pruning.
Limits: 16 KiB UTF-8/message, 64 KiB HTTP requests, 30 new messages/sender/minute and a separate 300/owner/minute budget shared by its sessions, 100 hops/thread by default (optional schema 3 per-conversation caps up to 100), 100,000 active messages, four active MCP subscriptions/recipient and 100 retained subscription identities. Both message budgets use durable rolling 60-second windows; 429 errors identify the exhausted budget. Retries of an existing identical message ID do not consume new-message capacity. Capacity failure closes safely instead of silently deleting dedup history. Finished threads retire automatically after seven days of inactivity and no longer count toward active capacity. Retired history, message IDs, receipts and audit records remain available; disk capacity still needs monitoring. There is no automatic destructive pruning.

Back up online:
```sh
Expand Down Expand Up @@ -217,3 +217,26 @@ OpenCode can use an account-wide [native wake plugin](docs/opencode-wake.md):
new sessions automatically receive their own native mailbox context and wake
inside the original runtime, with no per-session service or registration. It
requires the documented trusted-backend OpenCode compatibility gate.


### Inactive thread retirement

Run `python -m babel retire --dry-run` to preview, or `python -m babel retire`
to retire eligible threads transactionally. Install an hourly operator timer
for normal maintenance; message admission also sweeps at the active capacity
bound if a scheduled run was missed. This command is private operator
maintenance, not a new public MCP tool.

A thread is a message root plus all replies. It retires only when every message
is acknowledged or canceled and its latest send, approval, acknowledgment or
cancellation is at least seven days old. New replies protect the entire thread.
Reads, polling, notification delivery and retries do not extend that lifetime.
Drafts and unread messages stay active regardless of age.

Retirement marks all messages in a thread with `retired_at`. History, receipt
retries, audit records and message-ID deduplication remain intact in SQLite and
backups. Retired messages do not consume the active-message quota. New replies
to a retired thread return 410 with instructions to start a new thread; an exact
retry of an existing message ID still returns its original result. Retirement
is additive within schema 4 and does not remove data. A pre-retirement binary
can read the history but will again count retired records toward its total cap.
9 changes: 9 additions & 0 deletions babel/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ def main():
gateway.add_argument("--container", action="store_true", help="Listen on private Docker network")
modes.add_parser("wake", help="Run explicitly configured HTTPS notification worker")
modes.add_parser("backup", help="Online SQLite backup inside configured bridge data/backups")
retire = modes.add_parser("retire", help="Retire finished threads inactive for seven days; preserve history")
retire.add_argument("--dry-run", action="store_true", help="Preview eligible thread/message counts without retiring")
from .enrollment import add_parser
add_parser(modes)
args = parser.parse_args()
Expand Down Expand Up @@ -61,6 +63,13 @@ def main():
pass
finally:
store.close()
elif args.mode == "retire":
import json
store = Store()
try:
print(json.dumps(store.retire_threads(dry_run=args.dry_run)), flush=True)
finally:
store.close()
elif args.mode == "backup":
store = Store()
try:
Expand Down
25 changes: 23 additions & 2 deletions babel/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
RATE_LIMIT = 30
OWNER_RATE_LIMIT = 300
MAX_RETAINED_MESSAGES = 100000
THREAD_IDLE_SECONDS = 7 * 24 * 60 * 60
ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:-]{7,127}\Z")

class BridgeError(Exception):
Expand Down Expand Up @@ -119,6 +120,8 @@ def __init__(self, path=None):
if "gone" not in {row[1] for row in self.db.execute("PRAGMA table_info(subscriptions)")}:
self.db.execute("ALTER TABLE subscriptions ADD COLUMN gone INTEGER NOT NULL DEFAULT 0")
self.db.execute("CREATE INDEX IF NOT EXISTS owner_rate ON messages(source_owner,created)")
from .retirement import initialize
initialize(self.db)
self.db.execute("PRAGMA user_version=4")
self.db.commit()
if str(self.path) != ":memory:":
Expand Down Expand Up @@ -198,11 +201,17 @@ def stage(self, source, recipient, text, message_id=None, reply_to=None, provena
if expected != actual:
raise BridgeError("Message ID already belongs to different content", 409)
return {"message": existing, "duplicate": True}
if self.db.execute("SELECT COUNT(*) FROM messages").fetchone()[0] >= MAX_RETAINED_MESSAGES:
raise BridgeError("Bridge message capacity reached; operator maintenance required", 507)
from .retirement import active_count, retire
if active_count(self.db) >= MAX_RETAINED_MESSAGES:
# Reclaim eligible threads even if the scheduled sweep was missed.
retire(self.db, time.time(), THREAD_IDLE_SECONDS)
if active_count(self.db) >= MAX_RETAINED_MESSAGES:
raise BridgeError("Bridge active-message capacity reached; unresolved work requires operator review", 507)
hops, root_id = 1, message_id
if reply_to:
parent = self._row(reply_to)
if parent["retired_at"] is not None:
raise BridgeError("Thread retired after inactivity; start a new thread without reply_to", 410)
if parent["status"] not in ("queued", "acknowledged"):
raise BridgeError("Replies require an approved parent message", 409)
if parent["conversation_id"] != conversation_id:
Expand Down Expand Up @@ -351,6 +360,18 @@ def message_status(self, message_id, role):
raise BridgeError("Bridge message not found", 404)
return row

def retire_threads(self, dry_run=False):
from .retirement import retire
if type(dry_run) is not bool:
raise BridgeError("dry_run must be a boolean")
with self.transaction():
return retire(self.db, time.time(), THREAD_IDLE_SECONDS, dry_run=dry_run)

def retirement_usage(self):
from .retirement import usage
with self.lock:
return usage(self.db)

def backup(self):
if str(self.path) == ":memory:":
raise BridgeError("Backup requires a persistent bridge database")
Expand Down
50 changes: 50 additions & 0 deletions babel/retirement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""Retire terminal, inactive threads without deleting history or dedup records.

Caller holds the Store transaction for sweeps. Replies and sweeps therefore
serialize across processes using SQLite's writer lock.
"""


def initialize(db):
columns = {row[1] for row in db.execute("PRAGMA table_info(messages)")}
if "retired_at" not in columns:
db.execute("ALTER TABLE messages ADD COLUMN retired_at REAL")
db.execute("CREATE INDEX IF NOT EXISTS thread_messages ON messages(root_id)")
db.execute("CREATE INDEX IF NOT EXISTS active_messages ON messages(retired_at,seq)")
db.execute("CREATE INDEX IF NOT EXISTS message_activity ON events(message_id,action,created)")


def active_count(db):
return db.execute("SELECT COUNT(*) FROM messages WHERE retired_at IS NULL").fetchone()[0]


def usage(db):
active = active_count(db)
total = db.execute("SELECT COUNT(*) FROM messages").fetchone()[0]
return {"active_messages": active, "retired_messages": total - active, "total_messages": total}


# Read/export/claim/poll activity deliberately does not extend thread lifetime.
# Approval and receipt timestamps live on messages; cancellation is an audit event.
ELIGIBLE = """
SELECT m.root_id, COUNT(*) AS messages
FROM messages m WHERE m.retired_at IS NULL
GROUP BY m.root_id
HAVING SUM(m.status NOT IN ('acknowledged','canceled')) = 0
AND MAX(MAX(m.created, COALESCE(m.approved, 0), COALESCE(m.acknowledged, 0),
COALESCE((SELECT MAX(e.created) FROM events e
WHERE e.message_id=m.id AND e.action='canceled'), 0))) <= ?
"""


def retire(db, now, idle_seconds, dry_run=False):
cutoff = now - idle_seconds
eligible = db.execute(
"SELECT COUNT(*), COALESCE(SUM(messages),0) FROM (" + ELIGIBLE + ")",
(cutoff,)).fetchone()
if not dry_run and eligible[0]:
db.execute("UPDATE messages SET retired_at=? WHERE retired_at IS NULL "
"AND root_id IN (SELECT root_id FROM (" + ELIGIBLE + "))", (now, cutoff))
return {"dry_run": dry_run, "idle_days": idle_seconds // 86400,
"inactive_before": cutoff, "eligible_threads": eligible[0],
"eligible_messages": eligible[1], **usage(db)}
22 changes: 22 additions & 0 deletions deploy/agent-babel-retire.service
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[Unit]
Description=Retire finished Agent Babel threads after seven inactive days

[Service]
Type=oneshot
User=agent-babel
Group=agent-babel
WorkingDirectory=/srv/agent-babel
Environment=BABEL_DATA_DIR=/var/lib/agent-babel
ExecStart=/srv/agent-babel/venv/bin/python -m babel retire
TimeoutStartSec=120
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/agent-babel
RestrictAddressFamilies=AF_UNIX
IPAddressDeny=any
CapabilityBoundingSet=
MemoryMax=256M
TasksMax=20
11 changes: 11 additions & 0 deletions deploy/agent-babel-retire.timer
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[Unit]
Description=Check Agent Babel thread retirement hourly

[Timer]
OnCalendar=hourly
Persistent=true
AccuracySec=1min
Unit=agent-babel-retire.service

[Install]
WantedBy=timers.target
6 changes: 3 additions & 3 deletions tests/test_message_capacity.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ def test_old_limit_and_exact_new_limit_preserve_history_across_restart(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / 'bridge.sqlite3'
store = Store(path)
# Historical rows are outside rolling rate windows. Keep mixed states
# to cover both undelivered work and acknowledged history.
# Pending historical rows are outside rolling rate windows but remain active.
# Completed inactive threads are covered by test_retirement.
def fill(first, last):
store.db.executemany('''INSERT INTO messages
(id,source,recipient,text,root_id,hops,status,provenance,created)
VALUES(?,'ada','grokbot','retained history',?,1,?,'manual',1)''',
((f'history-{i:06d}', f'history-{i:06d}',
'queued' if i % 2 else 'acknowledged') for i in range(first, last)))
'queued') for i in range(first, last)))
store.db.commit()

fill(0, 10000)
Expand Down
Loading
Loading