Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
TeamHub: Collaboration and persistence authority
Go service owning Human HTTP/SSE, Agent callbacks, and active product state.
Common Commands
go test ./internal/<feature> -run <TestName>: run one focused Go test fromapps/teamhub.make -C apps/teamhub check: run formatting, unit, script, and contract checks (doc links run in the rootmake check-docs).- Before opening a pull request, run
make -C apps/teamhub fmt-checkandgo test ./tests/integration/layout -count=1. make -C apps/teamhub test-integration: run the default PostgreSQL integration suite with plaingo test.PARALLELoverrides go test's-parallel(default GOMAXPROCS); CI does not run this suite.make -C apps/teamhub test-integration-processandmake -C apps/teamhub test-integration-migrations: run the build-tagged process and fresh-install migration suites.make -C apps/teamhub generate: regenerate OpenAPI and sqlc outputs after source changes.
Structure
internal/app: routing, authentication, request decoding, response encoding, and error mapping.app.goandfeature*.gobuild the domain services.- Connector authorization defaults to the public Web callback. For a desktop request, pass only a validated one-time loopback address to Composio. TeamHub verifies connection status independently under the signed-in Account.
internal/<feature>: business behavior, transactions and data access with package tests:collaboration(Human Rooms and Messages),agentregistry(Agents, templates, Skill bindings, Another Me),voice(voice features), and the older feature packages.internal/store/queries: sqlc SQL sources; generated files live ininternal/store.internal/skill: parses Skill Packages, resolves effective Skill sets, and reconciles the repository-level built-in Skill catalog into TeamHub.migrations: TeamHub-owned schema changes.tests/integration/<feature>: independent PostgreSQL business test packages.tests/testsupport: shared database lifecycle and pure harness utilities; business fixtures stay in their owning test package.
Important Conventions
The Human's default Another Me Agent is named
Linger. Changing the Human's name updates the delegate description, never the Agent's display name. A forward migration renames generated names; custom Agent names stay. The instruction template describes the delegate's role without overriding its display name. Template migrations preserve custom instructions and advance only the profile configuration revision.Gmail canvas drafts persist their source digest alongside the provider draft ID. Preparing and executing a send confirmation both check the current authorized canvas against that source; changed recipients, body, or attachments require a refreshed draft and a new confirmation. Delivery status and link bookkeeping do not change the source digest. Draft saves run one at a time per connection under a
gmail_canvas_draft_leaseslease that holds no database connection during the upload; a save whose lease expired leaves its draft unbound. A save waits at most 30 seconds for the lease, then fails as retryable; a lease a crashed process left blocks that connection's saves until it expires (10 minutes). Large MIME drafts use Gmail resumable uploads in bounded chunks through the authenticated proxy, avoiding its request-body limit. Each chunk must be fully acknowledged; transport failures do not replay a possibly completed write.A Human sends a Gmail canvas from its chat card (
internal/mailcanvas): editing only saves the Document;POST /v0/documents/{id}/mailcarries the source digest of the email the card last showed and queues one River delivery that uploads the draft and sends it, refusing a canvas that changed since. Each canvas has onemail_canvas_deliveriesrow: afailedorunknowndelivery may be sent again or declined (an unknown one only after the Human checked Gmail), whiledeclined(Don't send) andsentare final. A rejected or interrupted upload isfailed(it sent nothing); only an interrupted or unconfirmed send becomesunknown, which is never replayed on its own. Sending anunknowndelivery again whose earlier Gmail draft is gone (404; Gmail deletes a draft once it is sent) fails with a may-have-been-sent message and starts a new draft next time; other upload errors keep the draft. A delivery that is in flight,sentorunknownblocks Voice Live and Agent sends of that canvas, and an Agent's confirmed send of a canvas-bound draft records asent(orunknown) row, so the card cannot send it again.GETreportssentwhenever the header says so, andcan_edit; only editors may send or decline. While the latest content is still rendering these routes answer 503 withRetry-After.Live voice write tools that finish a send return a
nextasking the model to say it was sent; a result without one can leave the voice silent.Live voice writes need the user's yes from a turn after the question (
voiceLiveConfirmed), exceptvoicelive.DirectYesTools: sending a Gmail canvas, which is open beside the chat, runs when the user's own turn told the model to send it and that turn neither asked about it nor wrote, changed or attached to a canvas; otherwise the details are read back and the yes comes in the user's next turn.A Room permits 100 Routines: recurring ones count while they exist, and one-shot ones count until they fire. There is no separate one-shot limit. Interval Routines store
interval_minutes(10 to 10080 in 10-minute increments), advance on a fixeddueAt + k * intervalgrid without drift or catch-up, and skip overlapping scheduled fires while an undelivered quiet wake or non-terminal trigger Message from the last 24 hours remains unfinished. Agent API, CLI, and Live Voice standardize onevery_n_minutes+interval_minutes(and still acceptevery_n_hours+interval_hourson input for compatibility with older CLI/Desktop builds); Web API keepsevery_n_hours+interval_hoursfor whole-hour intervals and usesevery_n_minutes+interval_minutesfor non-whole-hour intervals.Room input acceptance: Runtime State validates canonical conversation/targeted agent_runtime inputs atomically with Local Run and cursor. Document reads are live-latest and mutations retain CAS. CLI business operations use current Agent/resource authority, not Context/Run prerequisites.
An Agent writes only in its Context Room. To act in another Room, an AnotherMe in its direct chat uses Room handoff (
internal/agentroomhandoff,teamhub room handoff): TeamHub posts a hiddenagent_runtimemessage, authored by the Human and mentioning the AnotherMe, in another live Room where both are members, and it wakes the AnotherMe's Context there, which then speaks for itself. Only a Run whose inputs carry a message the Human wrote, or a card they decided, in the direct chat may hand off (X-TeamHub-Run-Id); proactive wakes, Routines and Task callbacks may not, because they often carry outside content. A refusal names its reason in an error issue, which the CLI shows the Agent. The handoff body is hidden from the Web timeline but other Agents in that Room can read it. Results come back throughsend_direct_message.Go generates only types for the contracts TeamHub serves. Mount each operation in the caller's route table in
internal/app/routes_*.go;TestRoutesMountEveryContractOperationExactlyOncefails on a missing, extra, or wrongly bound route. Handlers areAppmethods that read bound query and header parameters withcontractParams[T]and path parameters withc.Param.Text TeamHub writes for a person to read stays English and ships with the meaning the client words it from: a status or error with a stable code, a card with its kind and fields, catalog text with its id. Add the code (an enum in
contracts/openapi) beside the English rather than wording it per language here; the client keeps the English for a code it does not know.internal/appopens no transaction and calls no store queries: handlers call a domain service and map its errors.TestAppLayerHoldsNoTransactionsOrQueries(tests/integration/layout) fails on a transaction, SQL, astore.Queriesorpgx.Txreference, or the pool outsideapp.goandfeature*.go. The Task and Work Item handlers listed in that test are the only exception.New data access uses sqlc queries in
internal/store/queries; do not add hand-written SQL.app.New(ctx, cfg, deps)builds the App from a complete Config and starts nothing;App.StartWorkers(ctx, skip...)starts background work. Tests useconfig.ForTest(...), inject fakes throughapp.Deps, and skip theapp.Workerparts they drive; do not add per-test options toappor default-filling toNew.Call Agent management through one handwritten adapter over the generated Go client.
Keep TeamHub as an independent Go module; do not introduce
go.workwithout a second handwritten Go module. Use the repository-localreplacefor the generated contracts module.The generated contracts module ID is
github.com/simplexai-labs/linger/contracts-go; it resolves only through thatreplace.Commit a persisted collaboration fact and its Room Event in the same transaction.
PostgreSQL is recovery authority; SSE is a low-latency wake signal.
PostgreSQL is also the recovery authority for Agent Runtime configuration, Execution Context, accepted input, Inbox cursor, Local Run, RuntimeSession, Runtime status coordination, and Local Computer state. Expose command-oriented generated APIs; never expose generic table CRUD to Agent Service.
Never import another app's source or log Runtime secrets.
Before opening or updating a long-lived branch with SQL migrations, fetch the current target branch, sync its migrations, and run
bash apps/teamhub/scripts/check-migration-history.sh <target-ref>from the repository root; the script requires the target ref. The local check includes uncommitted and new SQL files.00852_baseline.sqlis the schema baseline; nothing below it remains. It reuses the version of the last migration it replaced, so a database already at 852 skips it and an older one must be recreated. Target migration filenames, versions and SQL are immutable; add a forward migration above the target's latest version instead of rewriting or deleting an existing file. Renumber only unpublished branch migrations and update their test fixtures and release references. Pull request validation checks changed SQL against the current remote target tip, not the older diff base. A missing upstream migration requires syncing the target; Git conflict resolution alone does not prove version uniqueness. The check compares Git trees, not deployment or Goose database state. If a deployment has already applied a branch's version, provide a new forward repair rather than editing its recorded history.Do not add an empty-database goose UpTo/DownTo integration test for every migration. Prove current behavior on the template clone. Fresh-install tests use
//go:build integration_migration_historyand stay off the default pull request suite. The baseline installs only into an empty database and refuses a database that already holds a TeamHub schema; databases created before the baseline are recreated, not upgraded. Later versions append normal forward migrations.Ordinary tests in the main integration package use
newIntegrationDatabase(t); independent business packages usetests/testsupport/database.Suiteand call itsRunfromTestMain. Each test owns a private clone; never seed or migrate a caller-supplied database. Onlyintegration_migration_historytests may usenewEmptyDatabaseor call gooseUp,UpTo, orDownTodirectly.Keep integration coverage for PostgreSQL transactions, locks, constraints, migrations, and HTTP boundaries. Test pure validation, normalization, state transitions, and stable ID generation in the owning package instead.
A top-level
TestXxxmust not invoke another top-levelTestYyy; extract a non-Test helper when scenarios share setup or assertions.Every default top-level
TestXxxintests/integrationmust start with exactly one marker:allowParallelIntegrationTest(t)(runs beside other tests under go test's-parallel) orserialIntegrationTest(t, reason), wherereasonis one of theserialIntegrationReasonconstants (processEnv,processLogger,suiteMeta,wallClockBound,subprocess). The Go layout test (tests/integration/layout) enforces the marker, the reason set, and the forbidden body patterns; it caps neither the parallel count nor the test count and does not match test names.The suite is plain
go test; there is no shard planner, timing file, test binary artifact, or database prefetch pipeline. The control connection pool is sized from the effective-parallelvalue + 2.A parallel test owns its database, HTTP server, temporary object storage, and provider fakes. Its object root comes from
integrationArtifactRoot(t), a per-test directory of hard links to the template Skill objects;integrationSkillArtifactRoot()is only the template source. A top-level test stays parallel unless it (1) mutates process-global state: environment variables, the default slog logger,GOMAXPROCS, or the integration database suite and its template inspection; (2) spawns subprocesses whose CPU load or shared resources matter; or (3) asserts a wall-clock upper bound that load can break. Criterion (3) keeps only the tests whose bound is the behavior under test, markedwallClockBound; a receive or poll used only as a hang guard uses a 30s window instead. Test names never decide concurrency. Lock and activity introspection (pg_locks,pg_stat_activity,pg_blocking_pids,pg_terminate_backend) is allowed in parallel tests only when scoped to the test's own database (database = (SELECT oid FROM pg_database WHERE datname = current_database())forpg_locks,datname = current_database()forpg_stat_activity) or to PIDs taken from the test's own pool. Rawt.Parallel()calls are forbidden.New asynchronous, retried, or periodic TeamHub work runs on River through
internal/jobs. Enqueue withjobs.InsertTxin the transaction that commits the fact requiring the work, and use River periodic jobs for sweeps.Do not add tables or columns for job leases, attempts, retry schedules, or outbox delivery, and do not start new polling goroutines in
app.go. Exceptions need sub-second latency or a long-lived connection (realtime/SSE, voice, presentation sequence pacing, the River due notifier); state the reason in the pull request. SQL that inserts River rows callsnotify_river_queueso the job does not wait for the queue's poll. Such a loop is woken on commit and sleeps until its next due time, with a fallback of at least one minute; it never polls on a short fixed interval.Voice recording timestamps come from a recorder clock distinct from PostgreSQL. A recorder is bound to a persisted Capture epoch; normalize a reported start earlier than the Capture's clock to that clock before confirming its timeline. A missing start stays unconfirmed. Keep audio duration and transcript offsets on the confirmed timeline, and enqueue an already-requested Stop when the initial recorder becomes known, including after restart reconciliation.
Voice:
TEAMHUB_VOICE_MEDIA(onby default) builds the voice media plane over LiveKit;off, a missingLINGER_SECRET_SEED, or missing ffmpeg keep voice off (the last two logvoice.media_unavailable) without stopping TeamHub.internal/voicekeyresolves the Soniox and xAI keys at each use, the environment key over one saved in the product (voice_provider_keys, sealed withTEAMHUB_SECRET_ENCRYPTION_KEY), so a save applies without a restart on every replica. A save wakes the Node Services voice workers best effort.Web search:
internal/websearchruns Agent searches and page reads through Tavily, Brave, Firecrawl and You.com with deployment-wide keys inweb_search_keys(sealed withTEAMHUB_SECRET_ENCRYPTION_KEY, read at each call) and the chosen default inweb_search_settings. TeamHub calls only the providers' fixed API hosts; the CLI readsdirectpages itself. A search without a backend runs the chosen default as if it were named, even when its key stopped working; without one it uses the first backend with a usable key, else You.com's keyless MCP trial, which TeamHub does not count. A failed call never falls back to another backend.include_quota=falselists the backends without calling any provider. A missing or refused key, or the end of the trial, posts asearch_keycard that stores the request. A key added from that card replays the request first: a provider 401/403 leaves the key unsaved and the card open; any other outcome saves it and answers the cardconfiguredwith the backend and the call's results or error code. Any save answers every other pending cardconfiguredwith the saved backend, which the Agent reruns with; saves outside a card use the official check (Brave has none and stays unverified until its first call).Local models:
local_computer_model_snapshotskeeps each Computer's latest model library snapshot and the last host any snapshot carried; removing the Computer deletes the row in the same transaction. Recording a snapshot publishes alocal-modelsinvalidation (id is the Computer ID) to the owner's Tenant. Any member of the Computer's Tenant reads the library;used_bylists active Agents on runtimepion that Computer whoseruntime_modelequals the model'spi_modelexactly (loaded or not), limited to the Agents the reader sees in the Agent directory. Only the owner acts (LOCAL_MODEL_ACTION_FORBIDDEN), and only while the Computer is online by the Computers page's 60-second rule (LOCAL_COMPUTER_OFFLINE).POST .../local-models(refreshLocalComputerModels) forwards an empty-modelrefreshcommand through the same owner/online gate, whilePOST .../local-models/{modelId}/actionsacts on one model (refreshstays invalid there). A connected Computer that has not decided within the action's 10 seconds answers 504LOCAL_MODEL_ACTION_UNCONFIRMED: it may still act, and the snapshots show the outcome. The Computer's refusal codes map toLocalModelsErrorCodeininternal/app/handlers_local_models.go(andLOAD_NO_ROOM/MEMORY_INSUFFICIENTon model-source switches map toLOCAL_MODEL_NO_ROOMininternal/app/handlers_model_source.go).A Computer's model source lives on the Computer (
internal/app/handlers_model_source.go); TeamHub never stores a BYOK key. A switch checks for running work, runsapplyon the Computer, then moves the owner's Agents on it in one transaction (agentregistry.SwitchComputerRuntime). Work found beforeapplyrefuses the switch withAGENT_HAS_ACTIVE_RUNSunless the owner sentforce_terminate; work that starts duringapplykeeps only its Agent behind, answered with the same code after the others moved.Do not add write-only audit, event, or provenance tables. A new audit table needs a named product or compliance reader in the same pull request.