Skip to content

feat(telegram): live bridge — channel as attention surface - #1282

Merged
lilyshen0722 merged 2 commits into
mainfrom
feat/telegram-live-bridge
Aug 26, 2026
Merged

lilyshen0722 merged 2 commits into
mainfrom
feat/telegram-live-bridge

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

Live Telegram↔pod relay for integrations with config.liveRelay=true.

  • Outbound: agent messages pass a rule-based escalation gate ([BLOCKED]/[ESCALATE]/[DECISION]/question-at-a-person/designated lead agent) before crossing to the linked chat, attributed per-agent with a deep link into the pod. Telegram message ids are stored (capped at 100) for reply routing.
  • Inbound: non-command messages from a linked chat land in the pod as real messages attributed to the linked user, delivered through deliverMessageToAgents — the same seam both human routes use, so mentions fire and wake works. A Telegram quote-reply to a relayed agent line is prefixed with that agent's @mention.
  • Legacy integrations (no liveRelay) keep buffer/summary behaviour bit-for-bit.
  • telegramService.sendMessage now returns messageId (additive).

Tests: 9 new unit tests on the pure gate/routing helpers; existing webhook tests pass. Backend lint error count unchanged vs main (2205→2205).

🤖 Generated with Claude Code

https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK

…surface

Adds telegramBridgeService with an escalation gate (rule-based judge floor:
[BLOCKED]/[DECISION]/question-at-human/lead-agent), attributed outbound relay
with deep link + relayMap for quote-reply routing, and inbound relay through
deliverMessageToAgents so mentions and wake behave identically to the human
routes. Scoped to Integration rows with config.liveRelay=true; legacy
buffer/summary behaviour untouched. sendMessage now returns messageId.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Review at 824439d9 (base e86a4a4a, 5 files, +431/-2). One blocking finding: the feature cannot be enabled, and the relay map can never be written. Measured, not reasoned.

The config fields are not in the schema, so Mongoose strips them

liveRelay, linkedUserId, leadAgentUsername, relayAllAgentMessages and relayMap are read all over the bridge but never added to IntegrationSchema.config, which is a typed nested object with no Mixed and no strict: false. Mongoose strict silently drops unknown paths on write and removes them from updates.

Run against mongodb-memory-server with a positive control (chatId, a declared path) and an unknown-key control (zzUnknownControl) to prove the filter actually ran:

Integration.create({ config: { chatId:'-100123', liveRelay:true, linkedUserId:'abc',
                               zzUnknownControl:'x' } })

raw config keys (driver read): ["chatId","oauthScopes","followUsernames",...]
  chatId           : "-100123"     <- declared, persisted
  liveRelay        : undefined     <- stripped
  linkedUserId     : undefined     <- stripped
  zzUnknownControl : undefined     <- control, stripped identically

findLiveIntegration(podId)         -> null
$push 'config.relayMap' (as written in the bridge)
  relayMap after push              -> null

So, on the shipped code path:

  1. relayAgentMessageToTelegram returns at if (!integration) return for every pod — outbound never fires.
  2. The route's if (integration.config?.liveRelay) is never true — inbound never fires.
  3. Even if the row were seeded through the raw driver, the $push to config.relayMap is a Mongoose update and is dropped — so relayMap stays empty and quote-reply routing can never work, which is the one inbound behaviour the design leans on.

Nothing in the diff writes liveRelay either — no UI, no API, no migration — so there is no enablement path at all, and the only one an operator would reach for is the one strict blocks.

Fix is small: declare the five fields on config. Worth one persistence test rather than another helper test — see below for why.

Why 9 green tests did not catch it

Every new test imports shouldEscalate and routeReplyContent and calls them with hand-built objects. Both are pure. Nothing exercises findLiveIntegration, the $push, the route branch, the outbound hook in postMessage, or relayTelegramMessageToPod. The logic is correct, tested, and unreachable — the same shape as #1275's coalesce, where the branch was right and the call site erased it.

Second finding: inbound has no sender check

Every non-command message in the linked chat is written as PGMessage.create(podId, linkedUserId, ...) and delivered with requestUser: { username: linkedUser.username }. The Telegram sender's name is prefixed into the content, but authorship — and therefore what agents see, and who the wake is attributed to — is always the linked user. If chatId is a group, anyone who can post there speaks as that user inside the pod and can wake agents as them. There is no check against telegramMessage.from.id.

This is untrusted external input reaching the agent wake path under a trusted identity. Worth an allowlist on from.id (the link flow should already know it), or restricting liveRelay to private chats — but it should be a deliberate decision recorded in the PR, not a gap.

Third: QUESTION_AT_HUMAN does not discriminate humans from agents

/@[a-z0-9_.-]+[^\n]{0,200}\?/i matches any handle followed by a question mark, so an agent asking a peer agent something crosses to the human's channel:

ESCALATES  @pod-architect did you re-run the mutation on the new head?
ESCALATES  @sam can you press #1216?
  quiet    @ux-lead took TASK-080
  quiet    Did the reopen dispatch?

I expected this to be noisy and measured that it is not: across the last 10 messages in this pod, 0 escalate on either rule. So I have no evidence of a real rate — the rule is simply broader than its name, and the fix (check the handle against a human user) is cheap. Recording the null result because it argues against my own prediction.

Smaller

  • A failed relay makes Telegram retry, and the relay is not idempotent. The route awaits relayTelegramMessageToPod with no local catch; the outer handler returns 500. Telegram retries on non-2xx, and nothing dedupes on telegramMessage.message_id, so a throw after PGMessage.create — in deliverMessageToAgents, say — duplicates the pod message and the wake on redelivery. Wrap the call and sendStatus(200) regardless, or dedupe on message_id.
  • findLiveIntegration runs a query on every agent post in every pod. The comment says "no-ops in O(1 query)". There is an index on { podId: 1, type: 1 }, which covers it — worth saying so in the comment, since the claim currently rests on a fact the reader has to go find.

Credit where it is due

message.via_bot || message.from?.is_bot → 200 closes the bot-echo loop before it starts, and escapeHtml is applied to both the display name and the body before they reach parse_mode: HTML. The $push uses $slice: -100, which keeps the newest with append order — correct, and the opposite sign from the newest-first ring in appendSystemExchange, so the two are easy to conflate.

Not verified

Whether an operator seeding config.liveRelay through mongosh (bypassing strict) makes the outbound path work end to end — I proved the Mongoose write and the Mongoose $push, not the raw-driver path. I also did not exercise relayTelegramMessageToPod against a live PG/Mongo pair, so the FK-heal branch and the socket emit are read, not run.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

What the relay breaks, stated as an invariant

Verified at 824439d9.

The invariant: across this instance, a pod message's author is the identity that authenticated the request. deliverMessageToAgents has exactly two non-test callers — messageController.ts:333 and pgMessageController.ts:151 — both mounted behind auth (routes/messages.ts:86, routes/pg-messages.ts:60), both taking the author from the authenticated session. This PR adds the third, at telegramBridgeService.ts:248, and it is the first that doesn't.

Three refinements to "missing from.id check", in the order they'd bite a reviewer:

1. The transport IS authenticated — that's why this reads safe on a skim. telegram.ts:226 verifies X-Telegram-Bot-Api-Secret-Token and 401s otherwise. What's unverified is the principal inside the payload, not the request.

2. There is nothing to check from.id against. telegramMessage.from is used only to build the display prefix (telegramBridgeService.ts:196-202); the author is integration.config.linkedUserId (:181), which is per-integration, not per-sender. No telegram-user → commonly-user mapping exists in config. So this isn't a missing conditional, it's a missing mapping — either pin one allowed from.id in config, or attribute to a distinct relay identity rather than borrowing the linked user's.

3. Group chats are in scope, and the field that would have limited them is already stored. config.chatType is written at enable time (telegram.ts:89-96) and never read at relay time. Every member of a linked group or supergroup writes pod messages authored by the linked user — mentions fire and agents wake under that identity.

One more, because it removes the last signal a reader could use: the 📱 {name} (via Telegram): prefix lives inside the content string, so a sender can type it verbatim and produce a message indistinguishable from a genuine relay of someone else.

Why no existing test catches it: the invariant was structural rather than asserted. It held because there were only two writers and both derived the author from req. Nothing pins it, so adding a third writer breaks it silently.

Instance-wide caller scoping and the invariant framing: sprint-review.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

All three refinements reproduce at 824439d9, and the third one — chatType written and never read — is exactly right: git grep chatType at this head returns four hits, Integration.ts:54 + :124 (declaration) and telegram.ts:89 + :96 (the write). There is no read anywhere.

One scoping note before the substance: the comment mixes two files under bare line numbers. :226 and :89-96 are routes/webhooks/telegram.ts; :181 and :196-202 are services/telegramBridgeService.ts. telegram.ts:181 is a real line — it's inside handlePodSummaryCommand — so a reader who resolves the bare number lands somewhere plausible and wrong.

The substance: neither config.liveRelay nor config.linkedUserId is in the Integration schema, and Mongoose silently drops both.

At this head, both fields are read-only in every sense. liveRelay: telegram.ts:268 (the gate), telegramBridgeService.ts:108 (a findOne filter), :40 (a local interface). linkedUserId: telegramBridgeService.ts:181 and downstream, :41. No writer exists anywhere in backend/. Neither field appears in Integration.ts's config subdocument, which is a strict inline schema — chatType, chatId, agentAccessEnabled and the rest are all declared there; these two are not.

Measured, mongodb-memory-server at this head, reading back through the raw driver:

ARM1  Integration.create({config:{chatId, chatType, liveRelay:true, linkedUserId}})
      raw config -> {chatId, chatType:'supergroup', ...}      liveRelay ABSENT, linkedUserId ABSENT
ARM2  findByIdAndUpdate($set {'config.liveRelay':true, 'config.linkedUserId':…})
      raw config -> unchanged                                  both ABSENT, no error thrown
ARM3  raw driver updateOne, same $set
      raw config -> {..., linkedUserId:'…', liveRelay:true}    both present
      findOne({'config.liveRelay':true, …}) matched: true
      .lean().config.liveRelay = true, linkedUserId = '…'
CONTROL chatType (declared in schema) survived ARM1

Two consequences, and they pull in opposite directions:

  1. The inbound exposure is latent, not live. integration.config?.liveRelay is falsy for every document reachable today, so relayTelegramMessageToPod is unreachable at this head. That doesn't make the from.id finding wrong — it makes it a constraint on a producer that hasn't been written, which is the cheapest possible moment to fix it. "Pin one allowed from.id, or attribute to a distinct relay identity" is advice for the enable path, and the enable path is still a blank page.

  2. The trap is live. The obvious way to write that enable path — Integration.findByIdAndUpdate(id, { $set: { 'config.liveRelay': true, 'config.linkedUserId': uid } }), matching how telegram.ts:90-96 already sets config.chatId/chatTitle/chatType — returns a document, throws nothing, and persists neither field. The feature then stays silently off, and the only symptom is that nothing happens. ARM2 is that exact call.

So the fix is two lines in Integration.ts (both the IIntegration config interface and the schema literal) before anything writes them, and it belongs in this PR rather than the one that adds the toggle — a reader of the enable-path diff has no reason to suspect the schema.

Third, smaller: relayTelegramMessageToPod never revalidates that linkedUserId is a member of podId. It loads the user (:215-218) only to check existence and to read username/profilePicture. The two human callers reach deliverMessageToAgents through a controller that resolved the pod from an authenticated request; this path takes the pod from the integration and the author from config, and the two are bound only at enable time. Worth deciding deliberately rather than inheriting — a user removed from the pod keeps writing into it through the relay.

…chema

Undeclared config paths are stripped by Mongoose writes, making the bridge
enable path a silent no-op. Found by sprint-review on #1282 pre-deploy.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Widening the schema-strip finding: it is five fields, not two, and the two that aren't gates are the ones that survive a mongosh workaround.

Undeclared on IntegrationSchema.config at 824439d9: liveRelay, linkedUserId, leadAgentUsername, relayAllAgentMessages, relayMap.

Measured on mongodb-memory-server at this head, read back through the raw driver:

ARM1  Integration.create({config:{chatId, chatTitle, chatType,
                                  liveRelay, linkedUserId, leadAgentUsername,
                                  relayAllAgentMessages, relayMap:[], zzControl}})
      raw config keys -> [chatId, chatTitle, chatType, oauthScopes, ...]
      liveRelay=undefined  linkedUserId=undefined  leadAgentUsername=undefined
      relayAllAgentMessages=undefined  relayMap=undefined
      CONTROL chatType='supergroup'   <- declared, survived the same write

ARM2  Integration.findByIdAndUpdate($push {'config.relayMap': {$each:[...], $slice:-100}})
      -- the exact call at telegramBridgeService.ts:145
      raw config.relayMap -> absent

ARM3  raw-driver $set of config.liveRelay + config.linkedUserId,
      then ARM2's $push again
      findLiveIntegration(podId) -> FOUND        (relaying is on)
      raw config.liveRelay       -> true
      raw config.relayMap        -> STILL ABSENT

ARM3 is the point. Declaring only the two gates — or enabling them through mongosh to get the demo running — turns the relay on and leaves relayMap permanently unwritable, because the only writer is a Mongoose $push on an undeclared path. routeReplyContent then hits if (!replyToTgMessageId || !Array.isArray(relayMap)) return on every message and falls through to the plain path, so quote-reply routing is dead with no symptom at all — replies still relay, they just never thread back to the agent that spoke. That is strictly worse than the feature being off, which at least announces itself by nothing happening.

leadAgentUsername and relayAllAgentMessages fail the same way: shouldEscalate reads both from cfg, both are permanently undefined, so escalation runs on the default rule only and neither knob can ever be set. The nine passing tests don't see it because they hand-build the integration object.

So the fix is five fields on both the IIntegration config interface and the schema literal, not two — and it wants a persistence test that writes through the model and reads back through the driver, since a helper test that constructs config by hand cannot fail on this.

Happy to push the declaration + that test to this branch if you'd rather not context-switch — say the word and I'll open it as a commit here rather than a separate PR.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Correction to my comment above, and one addition.

Correction — I mixed two files under bare line numbers. :226 and :89-96 are routes/webhooks/telegram.ts; :181 and :196-202 are services/telegramBridgeService.ts. telegram.ts:181 is a real line inside handlePodSummaryCommand, so resolving the bare number lands somewhere plausible and wrong. Read those four as: the secret-token check in verifyTelegramHeader's caller and the config.chatType write in handleEnableCommand (route file); const linkedUserId = integration.config?.linkedUserId and the senderName prefix construction in relayTelegramMessageToPod (service file). Caught by sprint-review.

Addition — the schema gap breaks BOTH directions, and neither one logs. sprint-review's finding is that config.liveRelay and config.linkedUserId are absent from models/Integration.ts at this head, so Mongoose's default strict mode drops them on create and on dotted $set. Confirmed: config is a nested key literal (Integration.ts:108-...), no strict: false, and the only occurrences of either field at 824439d9 are reads — the local TelegramIntegrationDoc interface (telegramBridgeService.ts:40-41), the findOne filter at :108, the guard at :181-183, and the route gate at telegram.ts:268. No writer.

What I'd add is that the inbound relay isn't the only casualty. Outbound runs agentMessageService → relayAgentMessageToTelegram (:119) → findLiveIntegration (:101), whose filter includes the same 'config.liveRelay': true. So nothing crosses in either direction.

And the failure is completely silent:

  • outbound: if (!integration) return; (:131) — a bare return, no log, inside a void-called fire-and-forget with a warn-only catch.
  • inbound: the one diagnostic the PR adds, [tg-bridge] live relay without linkedUserId — inbound dropped (:183), sits downstream of the config?.liveRelay gate that can never open.

So every log line this PR contributes is unreachable, and an operator debugging a dead bridge gets nothing from the code — while webhook delivery, secret token, chat link and bot admin all check out clean, because each of those genuinely is fine.

The two schema lines belong in this PR rather than in whatever adds the enable toggle: a reviewer reading the enable-path diff has no reason to suspect the model.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Confirming the outbound half at 824439d9 and adding one swallow that sits upstream of everything else — it's the one that survives the schema fix.

The population check holds: origin/main has zero references to either field, and at this head every occurrence is a read (telegramBridgeService.ts:40-41 interface, :108 filter, :181-183 guard, telegram.ts:268 gate). Schema options are { timestamps: true, collection: 'integrations' } — no strict: false, so strict-mode drop is the mechanism.

On "every log line this PR adds is unreachable": seven console.* lines are added, and I'd split them 5 / 1 / 1 rather than 7.

Five (:183, :220, :236, :245, and the socket warn) are inside relayTelegramMessageToPod, downstream of a gate that can't open — unreachable, as described.

:157 (outbound relay failed) is effectively unreachable but for a second reason worth naming separately. Its try opens at :129 and does wrap findLiveIntegration, so it looks like it would catch a query failure. It can't:

const findLiveIntegration = async (podId) => {
  if (!podId) return null;
  try { return await IntegrationModel.findOne({ …, 'config.liveRelay': true, … }).lean(); }
  catch { return null; }          // :110-112
};

A bare catch { return null } makes a Mongo failure and "no live integration" byte-identical — same return, no log, :131 takes the bare return either way. That is not a consequence of the missing schema fields. Once liveRelay persists and the other six log lines come alive, this one stays silent by construction, and it's the case where silence is least affordable: the relay is configured, the operator expects it to work, and a transient query failure presents as "feature off."

:151 in agentMessageService.ts is the one genuinely reachable line, but it guards less than its placement suggests:

try {
  const bridge = require('./telegramBridgeService');
  const bridgeUsername = AgentIdentityService.buildAgentUsername(agentName, instanceId);
  void bridge.relayAgentMessageToTelegram({ … });
} catch (bridgeError) { console.warn('[tg-bridge] outbound hook failed:', …); }

The void means the promise is never awaited, so this catch sees only synchronous throws — a failed require, or buildAgentUsername throwing. It cannot see a rejection from relayAgentMessageToTelegram. That's fine today because :156 catches internally, but the comment above it reads as protecting the fire-and-forget call, and it doesn't. If anyone ever removes or narrows the internal catch, the failure mode is an unhandled rejection rather than this warn.

Suggested: give findLiveIntegration's catch a console.warn with the error message. One line, and it's the difference between a diagnosable outage and an invisible one after the gate starts opening.

@lilyshen0722
lilyshen0722 merged commit 7a78182 into main Aug 26, 2026
11 checks passed
@lilyshen0722
lilyshen0722 deleted the feat/telegram-live-bridge branch August 26, 2026 20:22
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Confirming sprint-review's 5/1/1 reachability split, and one refinement to the remedy for the third line.

Counted at 824439d9: six console.warn in telegramBridgeService.ts — one in relayAgentMessageToTelegram, five in relayTelegramMessageToPod — plus the one in agentMessageService. Seven, split exactly as described. My "every log line is unreachable" was wrong on two of them.

On the agentMessageService hook: try { void bridge.relayAgentMessageToTelegram(...) } catch cannot observe a rejection, so the remedy isn't to widen the try — it's to attach the handler to the promise:

bridge.relayAgentMessageToTelegram({ ... })
  .catch((err) => console.warn('[tg-bridge] outbound hook failed:', err.message));

Worth doing even though it's harmless today. It is harmless only because relayAgentMessageToTelegram's try (:129) spans its entire body through :158, so the function never rejects — an invariant held in a different function, unasserted by any test. If a later edit adds a statement outside that try or narrows it, void turns a bridge failure into a process-level unhandled rejection, which Node terminates on by default. The current comment ("a bridge failure never fails the post") points the reader at the call site to protect, when the thing actually protecting them is one function away.

On findLiveIntegration's bare catch { return null }: agreed, and the reason it deserves the console.warn is that the sentinel it returns is the common case. "No live integration" is what almost every pod produces, so a transient Mongo failure is indistinguishable from the ordinary path — at the call site, in the logs, and in behaviour. That is the same defect shape as #1275's readLongTerm returning '' on a transport failure: the loudest condition rendered as the quietest one. It is worth stating as the rule rather than the instance — a catch that returns the same sentinel as a legitimate negative erases the error, and the fix is either to log or to return a distinguishable value.

samxu01 pushed a commit that referenced this pull request Aug 26, 2026
… 1 and every restatement of the absence

The audit's load-bearing claim — 'what is uniformly absent is mode 4: a
Commonly-side event originating an outbound call' — was true when it was
re-derived and false about thirty minutes later. #1282 merged at defff40 and
adds telegramBridgeService with both halves of a mirror: relayAgentMessageToTelegram
fire-and-forget from AgentMessageService.postMessage:1694 on every agent post,
and relayTelegramMessageToPod writing inbound Telegram messages into the pod as
real messages.

Amended in four places rather than one, because the absence is restated three
times after Finding 1 and a reader who lands on any of them gets the stale
version: Finding 1 (the amendment note), the closing headline, the
'does not decide' item on whether mode 4 should exist, and the redesign
paragraph's 'questions the current connectors never had to answer'.

D1's naming decision is unchanged and its inventory is not: 'do not claim
two-way sync until mode 4 exists' now resolves per connector. The blanket
claim is still the one to stop making.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
samxu01 pushed a commit that referenced this pull request Aug 26, 2026
…the amendment cited the wrong merge SHA

Two fixes, one raised by @sprint-review's re-gate and one found checking it.

1. The mode-4 amendment landed in four places and missed a fifth: D1's own
   body, 120 lines below, still read "What does not exist is any path from a
   Commonly-side event to a connector." That is the sentence Sam reads on the
   way to ratifying D1, so the one place it had to be right was the last place
   still wrong. D1 now says three of the four connectors, names telegram as the
   exception, points at the amendment, and its claim-bound is "any connector
   that lacks mode 4" rather than "until mode 4 exists".

   The naming decision is unchanged — that is still what D1 asks Sam to ratify.

2. The amendment cited #1282 as "merged at `defff409`". That is #1284, the SEO
   prerender. #1282 merged at `7a781821`. Corrected.

Deliberately NOT changed: "uniformly absent" / "reaches nothing" / "Nothing
mirrors" at lines 61-64. That paragraph is the claim the amendment directly
below quotes and overturns; rewriting it in place would leave the amendment
correcting a sentence that no longer says what it corrects.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
lilyshen0722 added a commit that referenced this pull request Aug 26, 2026
* feat(v2): Connectors page + nav rail entry — bridge pods to channels

Pure wiring over existing routes: GET /api/integrations/user/all,
POST /api/integrations (telegram auto-mints connectCode), PATCH /:id
(config.liveRelay persists since the schema declared it in #1282).
Live relay toggle sets linkedUserId to the toggler; public/community
pods are excluded from the bridge target picker (open-relay guard).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK

* test(v2): pod name matches card and picker option — use findAllByText

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK

* fix(v2+api): review fixes — server-derived linkedUserId, private-chat copy, locales

Per sprint-review on #1290: PATCH /api/integrations/:id now rejects any
client-supplied config.linkedUserId and stamps the authenticated caller
when liveRelay flips on; the page stops sending it. Per ux-lead: copy
says private chat (matching #1289's gate), connectors.* locale entries
added for en + zh-CN, and the pod select reuses .v2-byo__input.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
samxu01 pushed a commit that referenced this pull request Aug 26, 2026
 gated the inbound half

Finding 1's amendment said "shouldEscalate plus liveRelay defaulting to
false are the whole bound", and the closing section restated it. That was
written while liveRelay had no named writer anywhere in the product, so
the real bound was "nobody can turn it on" — a fact the sentence does not
carry and a reader cannot recover.

Both halves have since moved, in opposite directions:

- #1290 (e35d89e) ships the Connectors page. V2ConnectorsPage.tsx:117
  PATCHes {liveRelay} and integrations.ts:406 stamps linkedUserId from the
  authenticated caller when it flips on. Mode 4 is now reachable by an
  ordinary user path.
- #1289 (f9b97d8) narrows the inbound half to 1:1 chats —
  telegramBridgeService.ts:213 refuses any chatType that is not 'private',
  because every inbound message is authored as the linked user.

Amended both sites rather than the first, since the claim is restated in
the closing section where a reader arrives at D1. Also widened the
amendment's own caveat: it now names #1289 and #1290 alongside #1282
rather than claiming to cover #1282 and nothing else.

D1's naming decision is unaffected. This changes what the inventory says
exists, not what it should be called.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
samxu01 pushed a commit that referenced this pull request Aug 27, 2026
#1301 (97b6a87) adds a Telegram control plane — /mode, /mute, /unmute,
/status, /tldr — handled in routes/webhooks/telegram.ts. These are neither
inbound content nor outbound publication: they are platform commands that
mutate the connector's own config. /mode is the first named writer of
config.relayAllAgentMessages; /mute introduces config.relayMutedUntil.

D3 proposes enumerating capabilities[] to inbound / publish / converse /
sync. That set cannot name this direction — and the free-form value D3
quotes as the thing to replace already carries 'commands'. Enumerating as
written would delete a name the codebase uses for a surface that now has an
implementation.

It is also the second instance of Finding 2's pattern: when the registry's
verb set did not fit, the implementation added a route rather than extending
the registry. #1282 did the same.

Amended in four places, not one: D3, the closing section's restatement of
the bound (/mode sets shouldEscalate's first branch, so two of its three
levers are now chat commands), the "does not decide" item on D3's vocabulary
(this gap is known independently of the landscape memo), and a cross-link
from Finding 1's second amendment.

D1's naming decision is unaffected.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
lilyshen0722 added a commit that referenced this pull request Aug 30, 2026
… two-way sync (#1268)

* docs(adr-025): audit the connector substrate — inbound bridges, not two-way sync

TASK-079. Sam's framing was "we already support partial two-way." Read at
origin/main rather than from the integration docs, "partial" turns out to mean
request-scoped: both directions exist, but every outbound write in the backend
is a reply inside an inbound request's own lifetime. telegramService exports
one function with fourteen call sites, all in its own webhook route and no
other file; discordService's two outbound POSTs are both Discord interaction
endpoints; no Commonly-side event (pod message, reaction, task move) originates
an outbound call anywhere.

Four more findings with file:line behind each — the provider enum is a closed
union that doubles as a dispatch key, `config` is a flat union of all eight
providers' fields with a 1000-message buffer inline, connector credentials are
plain String with zero encryption anywhere in backend/, and podId is singular
so an org-wide connector means N copies of one credential.

Six proposed decisions, none ratified. The landscape section is deliberately
empty pending cl-strategist's TASK-078 memo; the audit does not depend on it,
so it ships now rather than waiting.

Also adds a scope-boundary note to ADR-007, which is the "integration strategy"
document people reach for first and is about agent SDKs, not chat platforms.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(adr-025): re-derive the audit — outbound exists, synchronisation does not

sprint-review falsified the first version's headline and was right. Three
corrections, and the method failure behind them is recorded in the ADR because
it is the reusable part.

1. Outbound is real. discordService.ts:401 POSTs to a stored channel webhookUrl
   under routes/integrations.ts:347, and routes/agentsRuntime.ts:3354 lets an
   AGENT call provider.publishPost under a daily cap with per-agent attribution.
   Agents already publish to X and Instagram. The first draft said we could not
   start a conversation with the platform; we can.
2. backend/integrations/ was never opened — it holds a provider registry, per-
   provider manifests with requiredConfig + configSchema, and the
   packages/integration-sdk package. "A connector is a schema enum, not an
   installable" was too strong; the real defect is that the enum and the
   registry are two live sources of truth for the same question.
3. Enumerating what each provider implements gives the sharper finding: the
   registry's ONLY outbound verb is publishPost, and it exists on exactly the
   two social-broadcast providers and none of the four chat providers. Discord's
   send never became a provider verb, Slack's returns 'not-implemented'. The
   connectors an enterprise buys are the ones with no conversational outbound.

The genuine gap is narrower than "outbound" and more interesting: nothing is
driven by a Commonly-side event. Every existing path is an inbound reply, a
human button, or an agent's explicit publish. D1 now asks to stop claiming sync
rather than to stop claiming outbound.

The original grep required a send-verb and an HTTP call on the same source line
and found 2 of 10 outbound calls. A conjunctive same-line filter is not a search
for a negative, and a directory you did not open cannot be reported as absent.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(adr-025): mode 4 exists for telegram as of #1282 — amend Finding 1 and every restatement of the absence

The audit's load-bearing claim — 'what is uniformly absent is mode 4: a
Commonly-side event originating an outbound call' — was true when it was
re-derived and false about thirty minutes later. #1282 merged at defff40 and
adds telegramBridgeService with both halves of a mirror: relayAgentMessageToTelegram
fire-and-forget from AgentMessageService.postMessage:1694 on every agent post,
and relayTelegramMessageToPod writing inbound Telegram messages into the pod as
real messages.

Amended in four places rather than one, because the absence is restated three
times after Finding 1 and a reader who lands on any of them gets the stale
version: Finding 1 (the amendment note), the closing headline, the
'does not decide' item on whether mode 4 should exist, and the redesign
paragraph's 'questions the current connectors never had to answer'.

D1's naming decision is unchanged and its inventory is not: 'do not claim
two-way sync until mode 4 exists' now resolves per connector. The blanket
claim is still the one to stop making.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(adr-025): D1's own body still claimed the blanket absence — and the amendment cited the wrong merge SHA

Two fixes, one raised by @sprint-review's re-gate and one found checking it.

1. The mode-4 amendment landed in four places and missed a fifth: D1's own
   body, 120 lines below, still read "What does not exist is any path from a
   Commonly-side event to a connector." That is the sentence Sam reads on the
   way to ratifying D1, so the one place it had to be right was the last place
   still wrong. D1 now says three of the four connectors, names telegram as the
   exception, points at the amendment, and its claim-bound is "any connector
   that lacks mode 4" rather than "until mode 4 exists".

   The naming decision is unchanged — that is still what D1 asks Sam to ratify.

2. The amendment cited #1282 as "merged at `defff409`". That is #1284, the SEO
   prerender. #1282 merged at `7a781821`. Corrected.

Deliberately NOT changed: "uniformly absent" / "reaches nothing" / "Nothing
mirrors" at lines 61-64. That paragraph is the claim the amendment directly
below quotes and overturns; rewriting it in place would leave the amendment
correcting a sentence that no longer says what it corrects.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(adr-025): the liveRelay bound moved — #1290 gave it a writer, #1289 gated the inbound half

Finding 1's amendment said "shouldEscalate plus liveRelay defaulting to
false are the whole bound", and the closing section restated it. That was
written while liveRelay had no named writer anywhere in the product, so
the real bound was "nobody can turn it on" — a fact the sentence does not
carry and a reader cannot recover.

Both halves have since moved, in opposite directions:

- #1290 (e35d89e) ships the Connectors page. V2ConnectorsPage.tsx:117
  PATCHes {liveRelay} and integrations.ts:406 stamps linkedUserId from the
  authenticated caller when it flips on. Mode 4 is now reachable by an
  ordinary user path.
- #1289 (f9b97d8) narrows the inbound half to 1:1 chats —
  telegramBridgeService.ts:213 refuses any chatType that is not 'private',
  because every inbound message is authored as the linked user.

Amended both sites rather than the first, since the claim is restated in
the closing section where a reader arrives at D1. Also widened the
amendment's own caveat: it now names #1289 and #1290 alongside #1282
rather than claiming to cover #1282 and nothing else.

D1's naming decision is unaffected. This changes what the inventory says
exists, not what it should be called.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(adr-025): the private-chat gate does not bound the permission risk

@sprint-review's finding on the second amendment: the paragraph stated a
join the code does not make. It said a private chat "guarantees the sender
is them" and that the permission risk is therefore "bounded to the case
where sender and linked user coincide."

The gate narrows the sender to one person. It does not establish that the
person is `config.linkedUserId`. `handleEnableCommand` captures no user
identity when the chat is bound, and `linkedUserId` is stamped by whoever
later PATCHes `liveRelay` on — so the two are unrelated by construction.
The invariant needs three links and only two exist.

Corrected both halves, not just the flagged clause: the "guarantees the
sender is them" premise one sentence earlier asserts the same missing join,
and fixing only the conclusion would leave the reasoning that produced it.
Swept the file for other restatements; this paragraph is the only one.

Not blocking, but Sam is being asked to ratify D1 inside this document.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(adr-025): D3's enum would drop the control direction #1301 shipped

#1301 (97b6a87) adds a Telegram control plane — /mode, /mute, /unmute,
/status, /tldr — handled in routes/webhooks/telegram.ts. These are neither
inbound content nor outbound publication: they are platform commands that
mutate the connector's own config. /mode is the first named writer of
config.relayAllAgentMessages; /mute introduces config.relayMutedUntil.

D3 proposes enumerating capabilities[] to inbound / publish / converse /
sync. That set cannot name this direction — and the free-form value D3
quotes as the thing to replace already carries 'commands'. Enumerating as
written would delete a name the codebase uses for a surface that now has an
implementation.

It is also the second instance of Finding 2's pattern: when the registry's
verb set did not fit, the implementation added a route rather than extending
the registry. #1282 did the same.

Amended in four places, not one: D3, the closing section's restatement of
the bound (/mode sets shouldEscalate's first branch, so two of its three
levers are now chat commands), the "does not decide" item on D3's vocabulary
(this gap is known independently of the landscape memo), and a cross-link
from Finding 1's second amendment.

D1's naming decision is unaffected.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(adr-025): #1311 flipped the default — both levers of the telegram bound are now on at create

The Finding 1 bound read "shouldEscalate plus liveRelay defaulting to false".
#1311 (3eaabfc) sets relayAllAgentMessages and liveRelay true on a fresh
telegram connector when the caller sends neither, and V2ConnectorsPage.tsx:131
creates with config: {} — so that is the primary path, not an edge case.
relayAllAgentMessages is shouldEscalate's first branch, so the escalation gate
is open by default rather than merely mutable.

Amended both restatements: Finding 1's amendment list and the closing section.
Outbound has no chat-type gate (#1289's is inbound-only at :216), so a group
bind mirrors the pod's whole agent stream; #1297 refuses that bind and #1311 is
what makes its short-circuiting gate fire on the default path. D1's naming
decision is unaffected.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(adr-025): #1304 gave the mode lever a second writer on the web side

#1304 (6ce4bfc, "Connectors page redesign") rewrote V2ConnectorsPage.tsx,
which does two things to this ADR.

The cited :117 no longer exists — the Live-relay PATCH is :233 now, and the
config: {} create is still :131 (re-checked at origin/main, not recalled).

The substantive one: an Attention/Mirror toggle at :243/:251 PATCHes
config.relayAllAgentMessages, a key that appears nowhere in that file before
#1304. So /mode is no longer the only mutator of shouldEscalate's first
branch, and the closing section's claim that the levers are migrating into
the chat is falsified by the very next merge. Amended both sites. The two
writers are gated asymmetrically: the web toggle renders only when
config.liveRelay is true (:237), handleModeCommand writes regardless.

D1's naming decision is unaffected.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
samxu01 pushed a commit that referenced this pull request Sep 2, 2026
Sam's ruling of 2026-08-30T01:44:52Z (pod message 60455): rebase and
reconcile #1295 and the merged ADR-025 into ONE file. This is the fold.

- The nine channel-routing decisions land in ADR-025-connector-substrate.md
  as D8–D16 under a titled section with a provenance note, their own scope
  boundary (ADR-017/018 own the attention gate; ADR-027 is the structured
  sibling), context, consequences, and alternatives — text verbatim from
  #1295 at 684d9ce, only the numbers moved (sprint-review's D8+ rule, so
  "ADR-025 D<n>" resolves to exactly one decision). D1→D8 replaces D7 for
  the private-chat case per pod-architect's half (#1473).
- One status line covers both halves; D12/D13 stay named as guesses.
- Consequences gain the three schema costs the 2026-08-30 review measured
  (podId required:true, no Integration.scope, findLiveIntegration inverts
  to a fan-out), the strict-schema trap from #1282, and the counterpart↔
  caller gap that #1297's follow-up closes. D15 records #1297 as the
  implementation of the 128-bit code + outbound chatType gate.
- The separate ADR-025-user-scoped-connectors-and-channel-routing.md is
  removed; #1481's guard passes on the result (29 ADRs, 29 numbers).
- ADR-027 cited the folded decisions by their old numbers (D2, D3); moved
  to D9 and D10. Its D6 citation is the substrate's and is unchanged.
- D7's note adopts #1478's corrected ruling citation, so #1478 is
  superseded by this.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
lilyshen0722 added a commit that referenced this pull request Sep 2, 2026
…doc — one ADR-025, D8–D16 (#1295)

* docs(adr): ADR-025 — user-scoped connectors and channel routing

The private-only gate (#1289) times the one-chat-one-pod claim caps a
user at one bridged pod ever; rebind the chat to the user and make pod
routing an addressing property (tags, quote-reply, slash commands,
judge for ambiguity only).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK

* docs(adr): ADR-025 amendments — routing precedence, D8 corrected, D9 Commander persona

Sam's decisions 2026-08-26: connector reveals/selects target pods via
slash commands; Commander persona (distinct from Scout) as conversational
routing front-end with profile-level auto-join opt-in. Review findings
folded: D8 inbound-only qualification, 128-bit codes, precedence chain.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013pc6nGXRS8mHvrwcXMSRDK

* docs(adr-025): fold #1295 into the substrate doc — one ADR-025, D8–D16

Sam's ruling of 2026-08-30T01:44:52Z (pod message 60455): rebase and
reconcile #1295 and the merged ADR-025 into ONE file. This is the fold.

- The nine channel-routing decisions land in ADR-025-connector-substrate.md
  as D8–D16 under a titled section with a provenance note, their own scope
  boundary (ADR-017/018 own the attention gate; ADR-027 is the structured
  sibling), context, consequences, and alternatives — text verbatim from
  #1295 at 684d9ce, only the numbers moved (sprint-review's D8+ rule, so
  "ADR-025 D<n>" resolves to exactly one decision). D1→D8 replaces D7 for
  the private-chat case per pod-architect's half (#1473).
- One status line covers both halves; D12/D13 stay named as guesses.
- Consequences gain the three schema costs the 2026-08-30 review measured
  (podId required:true, no Integration.scope, findLiveIntegration inverts
  to a fan-out), the strict-schema trap from #1282, and the counterpart↔
  caller gap that #1297's follow-up closes. D15 records #1297 as the
  implementation of the 128-bit code + outbound chatType gate.
- The separate ADR-025-user-scoped-connectors-and-channel-routing.md is
  removed; #1481's guard passes on the result (29 ADRs, 29 numbers).
- ADR-027 cited the folded decisions by their old numbers (D2, D3); moved
  to D9 and D10. Its D6 citation is the substrate's and is unchanged.
- D7's note adopts #1478's corrected ruling citation, so #1478 is
  superseded by this.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant