Deterministic at the Edges: Inside the Productivities Multi-Agent Architecture.
How Hably unified workspace chat, scoped assistants, background automations, and bounded sub-agent delegation on one durable runtime across Local SQLite and Cloud PostgreSQL, keeping permissions, provenance, and mutations deterministic at every boundary.
On this page
Most AI features in productivity tools begin with the same simple pattern: wire a language model loop to a handful of helper functions, paste relevant notes into the prompt, and ship a working assistant. That pattern serves small prototypes well enough, yet it breaks down quickly once software spans private journals, shared team projects, local folders on a user’s computer, recurring automations, and external integrations.
You don't need any prior familiarity with Productivities to follow the architecture here. At a high level, Productivities is Hably’s connected workspace combining day-to-day Tasks, Markdown Notes, saved web Pins and Highlights, structured Tables, visual Canvases, People, Calendars, and repeatable Automations. Those records live inside project containers called Spaces, and the app runs across both an offline-capable Local desktop mode (Electron, Node, SQLite, and local Markdown files) and a multi-tenant Cloud service (hosted workers over PostgreSQL with strict tenant isolation).
When we evolved AI from a single chat window into a multi-agent system inside that workspace, four practical engineering problems stopped us from taking shortcuts:
- Process-local loops lose track of state. If an assistant is creating a Task or updating a calendar just as your laptop goes to sleep or a cloud worker restarts, a naive retry loop simply runs the call again and leaves duplicates behind.
- Prompts can't hold security fences. Asking a model in plain prose not to leak confidential notes or step outside an approved folder falls apart fast once untrusted web pages, webhooks, or chained sub-agents enter the mix.
- Large tool catalogues eat context budgets alive. Productivities now exposes more than 170 capabilities across over 20 domains. Sending every schema on every turn burns tens of kilobytes of context and breaks provider prompt caching before anyone asks a question.
- Agent “group chats” turn into guesswork. Dropping several independent bots into one thread with mismatched permissions and private scratchpads leaves users wondering who changed what, which project’s notes fed an answer, or how much budget a delegating chain is quietly spending.
Our guiding rule ended up pretty clear: let the language model handle open-ended reasoning, enforce every identity, scope, permission, provenance, and persistence boundary in deterministic code, and run every AI surface (your personal assistant, scoped project agents, sub-agents, and background automations) through one shared runtime.
1. Setting the Stage: One Shared Execution Harness
Before diving into coordination, it helps to see where agents sit inside the workspace itself. Productivities separates durable user data (where each domain such as Tasks, Notes, Pins, Tables, Canvases, Forms, Routines, Feeds, Highlights, People, and Spaces is the sole owner of its storage and rules), optional workflow plugins, and personal workspace arrangement on top.
So where do agents belong if they aren't allowed their own private database? Right across those three layers as connective intelligence, without acting as a fourth store or sneaking around domain boundaries. An agent never gets bypass privileges and speaks through the exact same domain services as the interface, whether running locally against SQLite or in Productivities Cloud under PostgreSQL Row-Level Security.
Early prototypes grew separate paths for quick commands, global chat, multi-step planning, background rules, and workspace agents. We've since retired the standalone planner and legacy chat pipeline, consolidating every AI surface onto one shared Durable Agent Run Kernel:
- Personal Agent (Workspace-Wide Assistant): Available from global chat, the Command Bar, and a docked side companion panel that tracks whichever Note, Task, Pin, Table, Canvas, or Space you currently have open so questions and targeted edits stay anchored in context.
- Configured Space Agents: Custom agent profiles created by a user with tailored instructions, model choices, reusable
/slugSkill playbooks, external Model Context Protocol (MCP) connections, and explicit Space or local folder bindings. - Task Handoffs: Directly assigning a Task to a compatible agent triggers a bounded background run whose findings appear back in the Task comments alongside actionable notifications.
- Triggered Automation Agents: Scheduled routines or workspace events can invoke an agent headlessly under strict mandates without holding database locks.
2. Multi-Agent Architecture: Coordinator, Specialists, and Peer Agents
Many multi-agent systems get tangled by conflating three separate concepts: the persona a user talks to, how complex work is split across sub-tasks, and the security identity that authorises database writes. Separating those three concerns cleanly is the backbone of Productivities’ multi-agent model.
Profile Scope: Workspace-Wide vs. Explicitly Scoped Agents
Inside Productivities, an agent profile is just a saved configuration running over the shared kernel, never a rogue background daemon carrying ambient permissions. Profiles work in one of two scope modes:
- Built-in Personal Agent: Uses a lazy, workspace-wide scope mode that keeps turn-start context setup
O(1)rather than scanning every Space even in busy workspaces holding dozens of Spaces, while working just as smoothly with zero Spaces or with unassigned inbox Tasks and Pins. - Configured Space & Folder Agents: Bind explicitly to one to eight chosen Spaces, or detach from Spaces completely to focus solely on approved local project folders on your disk. Picking specific Spaces narrows where an agent may look without ever granting extra permissions, since the person starting the chat must already hold live access to every Space in the list.
Every conversation stamps an immutable canonical SHA-256 scope fingerprint locking in its chosen Space list and owner audience at creation time. If you start a combined Project Alpha + Project Beta thread and later lose access to Project Beta, the runtime fences that conversation and asks you to start a fresh thread rather than silently trimming context behind your back.
Single Accountable Coordinator + Depth-1 Delegation
Rather than refereeing a chaotic group chat of competing bots, Productivities keeps one coordinator agent accountable for your turn and hands it a structured delegate_to_agent capability. When a request genuinely benefits from parallel research or specialist focus, the coordinator spawns bounded child runs against either of two targets:
- Built-In Specialists (
specialist): Four tight roles (research,writing,scheduling, andanalysis) that inherit the coordinator’s current Space or workspace reach while stripping away every tool outside that specialist’s allowlist. - Peer Space Agents (
peer_agent): Delegating a scoped sub-task into another configured Space Agent inside the same workspace so its custom guidance, skills, and project familiarity can lend a hand without exposing anything outside its remit.
So how do we stop delegation chains from spiralling in spend, depth, or accidental privilege leaks? Four mechanical rules apply to every child run:
- Hard Depth Limit (
depth = 1): Delegated children unconditionally lose bothdelegate_to_agentandask_userfrom their tool list. Sub-agents can't spawn sub-sub-agents (nobody needs a recursive game of telephone burning through tokens), and they won't hijack your screen mid-turn with nested pop-up questions. - Strict Peer Scope Intersection & No Upward Escalation: When talking to a peer Space Agent, effective reach is calculated live as the intersection of non-private Spaces you're permitted to open and Spaces assigned to the peer. Locked Private Spaces (personal Spaces explicitly sealed from delegation) stay completely off limits, and a Space-scoped parent is blocked from delegating up to a workspace-wide peer.
- Bounded Steps, Parallel Fan-Out & Atomic Budget Slicing: Each child is capped at 1 to 6 steps (defaulting to 4), and up to three read-only delegations can run in parallel. Before launching a child, the coordinator carves an explicit slice out of its own remaining tool steps, model iterations, external calls, and tokens (requiring at least 12,000 remaining tokens before spawning) and reconciles exact usage when the child settles.
- Read-Only Summaries vs. Deferred Proposal Queuing: By default, delegations run in
read_onlymode and return a bounded summary (up to 8,000 characters) stamped with exact source-agent and source-Space tags. Even inpropose_writesmode, a sub-agent never edits live records directly. Every proposed change lands cleanly in the human Pending Approvals Inbox with parent/child provenance and revision checks attached.
3. Proportional Execution and the Durable Run Kernel
Simple questions should never pay the latency tax of an orchestration graph. At the entry to the harness, our router selects the lightest execution pattern matched to the user’s request: instant deterministic commands when intent is unambiguous, plain model conversation with zero tool schemas sent for general questions, a bounded tool loop with hard iteration and token caps, or coordinator-to-specialist delegation when multi-step research or specialist focus is genuinely needed.
Why Build a Custom Database-Backed Run Kernel?
In Cloud mode, stateless API handlers sit apart from background job workers, so process memory can't ever be the source of truth. On the flip side, bolting on an external distributed workflow cluster like Temporal would clash badly with our compact desktop app running inside Electron and SQLite.
Because Productivities already relied on proven transactional lease, outbox, and idempotency tools for automations and offline sync, it made far more sense to build one shared Durable Agent Run Kernel over SQLite and PostgreSQL:
- Fenced Leases Instead of Worker Trust: Workers claim queued work using a renewable UTC lease and a monotonic fencing token separate from worker identity. Every heartbeat, stage update, and event append validates both the fencing token and row revision via compare-and-set, so a slow worker waking up after pause can’t overwrite a newer claim.
- Event Logs as Source of Truth: Run state changes and append-only audit events commit inside the same short database transaction. Live Server-Sent Events (SSE) streams act purely as projections of committed database state rather than authority in their own right.
- Explicit Ambiguity Over Blind Retries: Every logical workspace mutation carries a deterministic idempotency key and advances through a quarantine-aware state machine.
4. Five-Stage Non-Locking Lifecycle, Parallel Reads, and Cloud Trade-Offs
One of the quickest ways to freeze an app with agents is leaving database write locks or open transactions hanging while waiting on a slow language model stream or a human click. In desktop SQLite that locks out edits elsewhere in your workspace; in Cloud PostgreSQL it chews through connection pools in seconds.
To prevent that, our execution harness splits every turn into five tidy stages where zero database locks stay open across model inference, network calls, file I/O, or approval pauses:
| Stage | What Happens | Concurrency & Locking Rule |
|---|---|---|
| 1. Acquire Scoped Context | Resolve actor, workspace, agent profile, fixed Space cohort, active focused object, mandate, and bounded memory snapshots. | Short non-locking reads capture an immutable context snapshot without treating it as a permanent capability grant. |
| 2. Reason & Retrieve | Stream model responses and gather read-only workspace, local folder, web, or peer-agent evidence. | Readers-writer coordination runs up to 6 concurrent read tools with zero write locks held across provider streams. |
| 3. Prepare Exact Effect | Resolve natural references into canonical UUIDv7 identifiers, generate targeted Note diffs or impact summaries, and request approval where required. | Approval cards hold preview digests and expected target revisions with zero open database transactions while waiting. |
| 4. Commit Through Domain | Drain active reads, revalidate live actor membership, scope and material epochs, deadline, expected revision, and one-time approval digest, then write. | Exclusive writer gate enters a single short atomic domain transaction binding mutation, receipt, consent consumption, and event. |
| 5. Report & Reconcile | Emit truthful outcome receipts and queue bounded memory checkpoints. | Positive domain receipts settle truth; lost acknowledgements reconcile deterministically against the same effect key. |
Readers-Writer Parallelism & Unified Read-Authority Coalescing
Wait: if we refuse to keep transactions open across a 15-second streaming reply, how do we pull the plug promptly when someone hits Stop or loses access mid-turn? Early versions ran a single sequential tool lock and kept re-checking database authority on tight timers, adding noticeable latency across Cloud round-trips.
Today, the harness uses a Readers-Writer turn lifecycle paired with unified read-authority windows across both Cloud and direct user-configured providers:
- Parallel Read Batches (Up to 6 Concurrent Calls): Non-mutating tools across SQL, Notes, mounted local folders, and outbound MCP run concurrently in batches of up to six under shared read tracking. On PostgreSQL, reads acquire independent pooled RLS-checked connections in parallel; on SQLite, they serialise safely through the native async transaction queue without overlapping into turn-busy errors. If any read in a batch fails an authority check, an abort controller cancels sibling reads immediately and drains in-flight handles before settlement.
- Synchronous Per-Chunk Guards (Zero SQL): On every single streamed chunk and tool step, in-memory checks still validate the live abort signal, user Stop actions, run deadlines, token budgets, and observed revocation generations synchronously.
- 10-Second Refresh / 15-Second Max-Age Read Authority Window: During ongoing read-only streaming, database membership and configuration re-checks refresh in the background after 10 seconds with a hard 15-second ceiling, invalidating immediately on any error or mutating tool call, and still checking freshly at model dispatch, first visible output, every domain mutation, and final settlement.
- Buffered Read Bookkeeping: Intermediate read-only stage progress and read budget counts stay validated in memory and flush to SQL in one batch at genuine database boundaries such as writes, lease heartbeats, or turn completion.
5. Background Agent Automations, Progressive Approvals & Local Folders
Permission checks in an agentic app can't stop at “is Scott allowed to delete a Task?” You might happily trust a Space Agent to tidy tasks during live chat while still wanting step-by-step confirmation before an unattended Tuesday-morning automation touches Notes.
Every run carries an explicit Autonomy Mandate enforced outside the language model:
- Level 1, Suggest Only: Zero write tools allowed; only read and analysis capabilities run.
- Level 2, Act After Approval: Mutating calls pause safely and render compact interactive approval cards inline (including targeted before-and-after diff previews for
edit_notepatches and cleanask_userquestion cards docked above the composer). Users can also choose once-per-turn approval for non-destructive private workspace edits while high-consequence, destructive, or cross-Space changes always require explicit confirmation. - Level 3, Act Within Approved Mandate: Allows pre-scoped non-destructive operations inside declared Space, item, and budget ceilings without repetitive popups.
- Level 4, Autonomous Automation Mandate: Governs scheduled and event-triggered agent runs under explicit per-action mandates, expiry limits, and hard operation caps.
Out-of-Transaction Agent Automations & the Pending Approvals Inbox
Within Level 4, Workspace Automations can invoke any configured Space Agent directly through a dedicated run_workspace_agent action under one of three explicit automation modes: read_and_report, act_in_assigned_spaces, or draft_proposals_only.
- Zero Held Transaction Locks: Agent execution is registered as an out-of-transaction external action on both Local SQLite and Cloud workers, releasing database locks in milliseconds before inference begins and deriving deterministic request IDs from the automation delivery key so crash replays never run the same turn twice.
- Untrusted Trigger Quarantine & Defence-in-Depth Downgrade: Event payloads (such as incoming feed items or webhooks) are never concatenated into the author’s prompt template; they sit inside a quarantined
external_untrustedcontext segment, and runs remain bound by deterministic Space-scope isolation, operation caps, and approval rules. As an extra defence-in-depth trigger, if prompt-injection patterns are detected in an untrusted payload, an autonomous run inact_in_assigned_spacesmode automatically downgrades any proposed writes todraft_proposals_only. - Compare-and-Set Pending Approvals Inbox: Whether queued by a background automation or by a delegated child agent in
propose_writesmode, deferred writes land in the Pending Approvals Inbox (shown in the UI as Needs Review), storing canonical argument digests, expected target revisions, and content SHA-256 hashes. When a human clicks Approve hours later, the backend opens a fresh transaction under current live permissions, checks that Spaces weren’t revoked or locked as Private, rejects stale targets if the underlying Note or Task changed in the meantime, and commits cleanly.
Confined Local Folder Access & Cloud Desktop Bridge
Agents can also be mounted onto local directories (such as a software repository or research folder) with either read-only inspection (file search, bounded reads, page-windowed PDF extraction, Git status/history) or read-write access:
- Segment-by-Segment Canonical Confinement: Every path resolution anchors to the real canonical directory handle and walks down segment by segment, resolving symlinks and rejecting dangling links outside the root so neither reads nor writes can escape.
- Cloud SSE Device Bridge: When running against Productivities Cloud from the Electron app, local folders are never bulk-uploaded upfront. Instead, bounded folder tool requests dispatch down the active SSE turn stream to the user’s desktop device, which executes them under the same confinement rules and returns results (capped at 24 KiB) over an authenticated callback.
6. Cohort-Isolated, Provenance-Aware Memory
Long-term memory falls apart quickly when project boundaries blur. If an agent helps you inside a combined Finance and Engineering thread, and an hour later you ask a question inside an Engineering-only thread, facts picked up from Finance shouldn't wander across. Personal memories learned by your workspace-wide Personal Agent also stay cleanly separated from project-scoped Space Agents.
Rather than hoping the language model ignores off-limits context out of politeness, Productivities separates memory into four stores enforced directly by subset queries at the persistence layer:
| Memory Store | Owning Domain | Who Can Read It in a Turn? |
|---|---|---|
| Shared Space Memory | Spaces domain (per Space) | Conversations whose selected Spaces include that Space, rendered in separate provenance-labelled blocks. |
| Agent Profile Guidance | Agent configuration owner | The agent profile’s owner (explicit instructions and attached Skills; no automatic learning writes here). |
| Agent Learned Memory & Checkpoints | Agent memory owner | Same user and agent AND Audience(chat) ⊆ Audience(memory) AND Dependencies(memory) ⊆ SelectedSpaces(chat). |
| Personal Agent Memory | Personal memory owner | Workspace-wide Personal Agent turns only, strictly excluded from custom Space Agents. |
Here, Audience is the set of workspace members permitted to see a conversation or memory, ensuring a fact recorded for a narrow audience never surfaces in a broader-audience chat (Audience(chat) ⊆ Audience(memory)). Likewise, because checkpoints record their exact Space dependency set, a memory formed in Space A + Space B is excluded from an A-only thread at query time ({A, B} ⊈ {A}). And when a user clears memory with /forget or resets a memory scope, monotonic material epochs advance immediately: active streams suppress newly forgotten content, in-flight checkpoints from an older epoch fail to commit, and offline queued commands can’t silently resurrect forgotten facts.
7. Scaling to 170+ Tools, Append-Only Disclosure & MCP Boundaries
Across Tasks, Notes, Pins, Highlights, Tables, Canvases, Forms, Calendars, People, Routines, Search, Automations, and Memory, Productivities registers 172 workspace capabilities across 21 domains (~153 KiB of raw JSON schemas). Transmitting all 172 schemas on every turn wastes tokens, hurts accuracy, and breaks tight request payload limits such as our managed Cloud inference ceiling.
Because our Provider-Neutral Model Gateway normalises OpenAI Responses, Anthropic, Gemini, Grok, OpenRouter, Managed Cloud AI (with automatic fallback routing and response-header model attestation), local Ollama models, and local CLIs (Claude and Codex), we couldn’t rely on vendor-specific server features. Instead, tool scaling and external connectivity are built directly into the turn harness:
- Append-Only Progressive Tool Disclosure (8-Tool / 12 KiB Seed): Intent classification picks a tight initial subset of relevant tools alongside
lookup_tools, while conversational turns send zero schemas. When the model activates additional tools throughlookup_tools, the disclosure manager appends them strictly in activation order without alphabetically re-sorting existing tools, keeping the system prompt and seed tool JSON prefix byte-identical across iterations so provider KV and prompt caches (Anthropiccache_controlbreakpoints and OpenAIprompt_cache_key) stay warm. - Unforgeable Request Custody: Each compiled provider request captures an unforgeable
WeakMap-backed handle freezing the exact tools and schemas advertised in that turn, preventing tool smuggling (where a model attempts to invoke an unadvertised tool inside the same response batch). - Hybrid Token Accounting: A local upper-bound token counter skips external token-count HTTP calls whenever estimated usage stays below 75% of budget headroom, falling back to exact provider counting only near tight ceilings.
- Governed Outbound & Inbound MCP + SSRF Guards: Agents can connect to external Model Context Protocol (MCP) servers over Streamable HTTP with turn-scoped session pooling, automatic socket eviction before any pause or approval wait, strict read-only tool filtering in read-only or workspace modes, and manual redirect handling plus private-IP URL allowlisting. Inbound public MCP clients connecting into Productivities share those same Space membership and Private Space exclusion gates.
8. Scoped Retrieval and Honest Local-to-Cloud Parity
Productivities runs offline-first in Local mode, on user infrastructure in Self-Hosted Remote, and in Productivities Cloud (with Self-Hosted Remote sharing the same PostgreSQL server model as Cloud). Rather than hiding architectural differences between Local and server runtimes, the retrieval layer reports capabilities honestly while enforcing the same scope guarantees everywhere:
- Cohort Enforcement Before Top-K Ranking: Whenever an agent searches selected Spaces, trusted Space filters execute inside lexical and vector indexes before census counts, BM25 or semantic ranking, limits, or text hydration. Filtering a global Top-K list after ranking lowers relevance and opens metadata side-channels.
- Honest Cloud & Local Retrieval Parity: Local SQLite runs both hybrid lexical search and local vector embeddings across Notes, Pins, and Highlights alongside full local folder walks, while Productivities Cloud openly reports local embedding retrieval as unavailable, executes PostgreSQL Row-Level Security full-text search (
tsvector), and bridges local folder calls on demand to the connected desktop. - Instant Working Copies & Zero Idle Polling: Cached agent catalogues, conversation histories, and edits render immediately from local device state synced via durable UUIDv7 outbox commands, refreshing open Notes after settled edits with zero idle background polling loops.
9. Proving It Under Pressure: Over 2,000 Automated Agent Verification Cases
Multi-agent boundaries mean little if they rely on happy-path manual checks. Inside the Productivities repository, the agent, delegation, memory, and MCP subsystems are verified by more than 2,000 automated test cases across nearly 400 agent-focused test files spanning unit suites, paired SQLite/PostgreSQL integration runs, crash harnesses, and live Electron browser workflows:
- Dual-Engine Contention & RLS Proofs: Lease claims, readers-writer cancellation races, Private Space MCP fences, and cross-Space memory admission run against both SQLite and live PostgreSQL 17 instances with enforced Row-Level Security.
- Adversarial Delegation & Approval CAS Suites: Dedicated tests prove that depth-2 delegation fails closed, child token/step slices clamp against parent usage, peer scopes intersect cleanly, cross-Space reads taint parent publications, and modified targets return stale-revision conflicts on delayed inbox approvals.
SIGKILLCrash Recovery & Deterministic Wire Replay: Separate-process kill tests confirm interrupted writes and local memory updates quarantine cleanly without duplicating mutations or resurrecting forgotten facts, while clock-deterministic wire replay fixtures test mid-stream revocation, malformed tool-call recovery, and prompt-cache prefix invariance byte by byte.
Closing Takeaways
Whether you’re building inside a local desktop workspace or a multi-tenant cloud SaaS product, five architectural habits keep multi-agent software reliable as it scales:
- Unify every agent surface onto one durable kernel. Running personal assistants, scoped project agents, sub-agents, and automations through one harness eliminates duplicate permission bugs and fragmented trust.
- Keep delegation shallow, budgeted, and provenance-aware. Single-coordinator depth-1 delegation with atomic budget slicing and cross-Space provenance tracking avoids multi-bot chaos while keeping human review in charge of cross-boundary writes.
- Never hold transactions across inference or human waits. Pair five-stage non-locking lifecycles and readers-writer parallel read batches with explicit state-machine quarantine for ambiguous writes.
- Make security structural rather than rhetorical. Space cohort subset rules, canonical segment-walked folder confinement, SSRF redirect guards, and epoch-fenced
/forgetbelong in deterministic code and SQL, never solely in prompt text. - Preserve KV caches while scaling tools. Seeding small capability sets and appending newly discovered tools monotonically protects latency and provider caches even past 170+ tools.
That discipline underneath is what keeps Productivities calm and approachable on the surface, giving individuals and teams helpful AI collaborators that respect workspace boundaries instead of making a mess behind your back.