Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(engine): capability matrix + drift gate + unwired-capability roadmap (#712)
Yudhi Armyndharisa8c66094d3d1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9bcc67c7f..501083dde 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -55,6 +55,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`X-Request-ID` (alphanumeric + dash, ≤128 chars) is echoed; anything else (including a CRLFheader-injection attempt) is replaced with a generated UUID. The id is also set on the response.+- **Engine capability matrix + drift gate.** A committed, source-verified matrix+ (`src/engine/engine-capability-matrix.ts`) records, for every `IWhatsAppEngine` method on each+ engine (whatsapp-web.js default, Baileys), whether it is `supported` or `not-available` — and for+ the not-available ones, the root cause: `adapter-gap` (the underlying library supports it, OpenWA+ just hasn't wired it — fixable) vs `library-limitation` (no first-class library API), with the+ cited library symbol as evidence. A drift gate fails when a method's throw-availability changes.+ `docs/engine-capability-matrix.md` inventories the unwired adapter-gaps as a prioritized capability+ backlog.+### Fixed- **Diagnosable failure for a stale browser profile after a binary-changing upgrade.** Upgradingdiff --git a/docs/engine-capability-matrix.md b/docs/engine-capability-matrix.mdnew file mode 100644index 000000000..7eb733e79--- /dev/null+++ b/docs/engine-capability-matrix.md@@ -0,0 +1,177 @@+# Engine Capability Matrix++This page is the operator- and engineer-facing view of which `IWhatsAppEngine` capabilities are real on each adapter — `wwjs` (whatsapp-web.js, the default) and `baileys` (the browser-free alternative) — and, for the ones that are missing, *why* and *where to start*.++The committed source of truth is `src/engine/engine-capability-matrix.ts`. Every `IWhatsAppEngine` method has a row with two adapters; each adapter is either `supported` (works end-to-end) or `not-available`, and each `not-available` cell carries a **rootCause**:++- **`adapter-gap`** — the underlying library already HAS the capability; only the OpenWA adapter wiring is missing. **Fixable in this repo** with a PR that calls the library symbol the evidence points at.+- **`library-limitation`** — the underlying library exposes no first-class symbol for the operation. Not fixable without a raw-proto/fork effort or an event-cache hack.+- **`uncertain`** — the source trace was inconclusive; needs a live spike.++Each row also cites an **evidence** string (the exact library file:symbol inspected), so an engineer can open the file and start wiring immediately.++## How the matrix stays honest++`src/engine/engine-parity.spec.ts` is a **drift gate**: it reads every adapter method body via `Class.prototype.method.toString()`, classifies it as supported/not-available by whether it throws `EngineNotSupportedError` / `ChannelMediaNotSupportedError`, and fails the build if the committed matrix drifts. No engine is instantiated and no Chromium/socket is opened — it is a fast, hermetic structural check. A parity change cannot land without deliberately updating this matrix and this doc.++The `rootCause`/`evidence` fields are hand-curated from source traces of the installed libraries (`node_modules/@whiskeysockets/baileys`, `node_modules/whatsapp-web.js`); they are not regenerated by the spec and are updated by hand as adapters are wired or libraries change.++> **Phantom support.** The drift gate's throw-heuristic cannot see adapter methods that silently stub (return `null`/`[]` + a warn log) without throwing. Five wwjs entries — `getCatalog`, `getProducts`, `getProduct`, `getContactStatus`, `getContactStatuses` — are marked `not-available` in the matrix even though their adapter bodies do not throw, because the library either has no API (catalog) or the adapter stubs instead of calling the available symbol (status read). When the drift gate is extended to assert against this matrix, it must consult `status`, not just the throw pattern, for these rows (or the adapter stubs must start throwing).++---++## Unwired-capability inventory++24 of the 71 interface methods are `not-available` on at least one adapter (31 not-available adapter-cells total). Grouped by cluster below. Each entry shows: status today → rootCause → evidence → wiring note.++### Channels / Newsletter++| Method | baileys | wwjs |+|---|---|---|+| `getChannelById` | not-available — **adapter-gap** | supported |+| `getChannelMessages` | not-available — **adapter-gap** | supported |+| `getSubscribedChannels` | not-available — **library-limitation** | supported |+| `subscribeToChannel` | not-available — **adapter-gap** | supported |+| `unsubscribeFromChannel` | not-available — **adapter-gap** | supported |++- **`getChannelById` (baileys, adapter-gap).** `sock.newsletterMetadata('jid', channelId)` → `NewsletterMetadata` (`Socket/newsletter.d.ts:9`, shape at `Types/Mex.d.ts:115`). Map `{id,name,description,inviteCode:invite,subscriberCount:subscribers,picture:picture?.url,verified:verification==='VERIFIED',createdAt:creation_time}`. Note: resolves channels by raw jid including not-subscribed ones (wwjs only sees subscribed).+- **`getChannelMessages` (baileys, adapter-gap).** `sock.newsletterFetchMessages(channelId, limit??50, 0, 0)` (`Socket/newsletter.d.ts:19`) returns the **raw `BinaryNode`** of `<message_updates>` children (`newsletter.js:149`). The fetch is one line; the real work is walking the children and mapping each to `ChannelMessage{id,body,timestamp,hasMedia}` — no library parser is exposed.+- **`getSubscribedChannels` (baileys, library-limitation).** No enumerate-subscribed-newsletters query in the library. All 23 `Socket/newsletter.d.ts` exports are per-jid (`newsletterMetadata` requires a key; `newsletterSubscribers(jid)` returns the count of one newsletter). The `newsletter` event surfaces jids opportunistically during live sync, but that is incremental, not a list-all. Would require a raw WMex/app-state hack against an undocumented XWAPath.+- **`subscribeToChannel` (baileys, adapter-gap).** Two-step: `newsletterFollow(jid)` (`Socket/newsletter.d.ts:10`) needs a jid, but OpenWA takes an invite code — bridge via `newsletterMetadata('invite', inviteCode).id` first, then `newsletterFollow`.+- **`unsubscribeFromChannel` (baileys, adapter-gap).** 1:1 — `await sock.newsletterUnfollow(channelId)` (`Socket/newsletter.d.ts:11`). `channelId` is already the `@newsletter` jid, no resolution needed.++### Labels (WhatsApp Business)++| Method | baileys | wwjs |+|---|---|---|+| `addLabelToChat` | not-available — **adapter-gap** | supported |+| `removeLabelFromChat` | not-available — **adapter-gap** | supported |+| `getLabels` | not-available — **library-limitation** | supported |+| `getLabelById` | not-available — **library-limitation** | supported |+| `getChatLabels` | not-available — **library-limitation** | supported |++- **`addLabelToChat` / `removeLabelFromChat` (baileys, adapter-gap).** 1:1 — `sock.addChatLabel(jid,labelId)` / `sock.removeChatLabel(jid,labelId)` (`Socket/chats.d.ts:70-71`, also `business.d.ts:163-164`), both `Promise<void>`. WhatsApp-Business-only op (rejects on personal accounts). Do **not** use `addLabel(jid, LabelActionBody)` (`chats.d.ts:69`) — that creates/edits the label *definition*, not the chat association.+- **`getLabels` / `getLabelById` / `getChatLabels` (baileys, library-limitation).** No label read/fetch symbol anywhere in `lib/**/*.d.ts` (`Types/Label.d.ts` has only the interface + `LabelColor` enum; `chats.d.ts`/`business.d.ts` expose only writes). Label data does arrive via app-state sync (`messaging-history.set`), so a determined adapter could capture+cache labels from the event stream — but that is a relay/cache hack, not a first-class getter, and there is no network fetch to seed/refresh it on demand.++### Catalog / Products / Orders (WhatsApp Business)++| Method | baileys | wwjs |+|---|---|---|+| `getCatalog` | not-available — **adapter-gap** (medium-confidence) | not-available — **library-limitation** |+| `getProducts` | not-available — **adapter-gap** | not-available — **library-limitation** |+| `getProduct` | not-available — **adapter-gap** (medium-confidence) | not-available — **library-limitation** |+| `sendProduct` | not-available — **adapter-gap** | not-available — **library-limitation** |+| `sendCatalog` | not-available — **library-limitation** | not-available — **library-limitation** |++- **`getProducts` (baileys, adapter-gap).** `sock.getCatalog({jid, limit, cursor})` (`Socket/business.d.ts:7`) returns `{products, nextPageCursor}` — paginated, maps to `PaginatedProducts`. Caveat: cursor-based, so `total` is unknown (approximate or iterate).+- **`getCatalog` (baileys, adapter-gap, medium-confidence).** `getCatalog` returns a product list + cursor, **not** the OpenWA `Catalog` metadata wrapper. Name needs `getCollections(jid)` (`business.d.ts:11`); `id`/`description`/`url` have no source — the adapter would synthesize a partial Catalog (`productCount=products.length`, rest best-effort).+- **`getProduct` (baileys, adapter-gap, medium-confidence).** No direct `getProduct(id)`; call `getCatalog({jid,limit})` then `products.find(p=>p.id===productId)` — loads the whole page to fetch one product.+- **`sendProduct` (baileys, adapter-gap).** `AnyRegularMessageContent` accepts `{product: WASendableProduct, businessOwnerJid, body}` (`Types/Message.d.ts:203`, built in `messages.js:397`). Two-step wiring: `getCatalog` lookup to resolve the product's image/title/price, then `sock.sendMessage(chatId, {product:{...}, body})`. `productId`-only send without the lookup is not possible.+- **`sendCatalog` (both, library-limitation).** No catalog-share message type exists in either library. Baileys `AnyMessageContent` has only `{product}` (single product); the catalog CRUD nodes (`Socket/business.js:294-362`) mutate the catalog, they don't send it. Would require raw-proto relay hacks (unverified).+- **wwjs catalog (library-limitation).** `whatsapp-web.js` has no `Client.getCatalog`/`getProducts`/`getProduct`/`sendProduct`/`sendCatalog` (`index.d.ts` grep = 0 hits). `Product`/`Order` are inbound-only parsers. The adapter currently stubs the reads to `null`/`[]` without throwing (phantom support).++### Status — post / delete++| Method | baileys | wwjs |+|---|---|---|+| `postTextStatus` | supported | not-available — **adapter-gap** |+| `postImageStatus` | supported | not-available — **adapter-gap** |+| `postVideoStatus` | supported | not-available — **adapter-gap** |+| `deleteStatus` | supported (caveat) | not-available — **adapter-gap** |++- **`postTextStatus` / `postImageStatus` / `postVideoStatus` (wwjs, adapter-gap).** The library **does** support status broadcast — the wwjs adapter simply throws (`EngineNotSupportedError`, self-labelled "Baileys-only; wwebjs blocked upstream, see #455") instead of routing it. `Client.sendMessage('status@broadcast', ...)` hits the `isStatus` branch which calls `sendStatusTextMsgAction({color,font,text})` (`Utils.js:537`) for text and `sendStatusMediaMsgAction(msg, mediaUpdate)` (`Utils.js:565`) for image/video/gif/audio (`Client.js:1410-1432` allows these content types for status). Wiring: `client.sendMessage('status@broadcast', mediaOrText, { ... })`. **Caveat:** `sendStatusTextMsgAction`/`sendStatusMediaMsgAction` take no recipients arg, so wwjs always broadcasts to the account's status-privacy audience — `StatusPostOptions.recipients` (Baileys `statusJidList` allow-list) cannot be honored on wwjs.+- **`deleteStatus` (wwjs, adapter-gap).** `client.revokeStatusMessage(statusId)` exists (`index.d.ts:139`; `Client.js:2795` → `WAWebRevokeStatusAction`). Revokes OWN status only (throws if `!msg.id.fromMe || !msg.id.remote.isStatus()`). Adapter throws instead of calling it.+- **`deleteStatus` (baileys) caveat.** Marked `supported` (no throw), but the adapter self-describes its `sendMessage(status@broadcast,{delete})` revoke shape as *empirically unverified* (`baileys.adapter.ts:909-911`) — only posting was live-spiked. May need a fallback to `EngineNotSupportedError` if WA rejects the shape.++### Status — read (contact stories)++| Method | baileys | wwjs |+|---|---|---|+| `getContactStatus` | not-available — **library-limitation** | not-available — **adapter-gap** |+| `getContactStatuses` | not-available — **library-limitation** | not-available — **adapter-gap** |++- **`getContactStatus` / `getContactStatuses` (wwjs, adapter-gap).** The library HAS the getters — `Client.getBroadcastById(contactId)` (`index.d.ts:136`; `Client.js:2771`) and `Client.getBroadcasts()` (`index.d.ts:133`; `Client.js:2759` → `WWebJS.getAllStatuses`). Each `Broadcast.msgs: Message[]`. The adapter stubs to `[]` without calling them (`whatsapp-web-js.adapter.ts:1732,1740`). Wiring: `getBroadcasts()` then flatten — for each `Broadcast`, map `b.msgs` to `Status[]` with the contact resolved via `broadcast.getContact()`.+- **`getContactStatus` / `getContactStatuses` (baileys, library-limitation).** `fetchStatus` (`Socket/chats.d.ts:42` via `USyncStatusProtocol`) returns the *about/profile text* line (`{status, setAt}`), **not** 24h stories. No story-read getter exists; story broadcasts surface only as `status@broadcast` messages via `messages.upsert` / `messaging-history.set` events. Would require OpenWA to accumulate `status@broadcast` messages itself and project them into `Status[]`.++### Messaging misc — delete / history / reactions++| Method | baileys | wwjs |+|---|---|---|+| `deleteMessage` | not-available — **adapter-gap** (partial) | supported |+| `getChatHistory` | not-available — **library-limitation** | supported |+| `getMessageReactions` | not-available — **library-limitation** | supported |++- **`deleteMessage` (baileys, adapter-gap, partial).** Only the `forEveryone=false` (delete-for-me) branch is missing — `forEveryone=true` is already correctly wired via `sendMessage({delete})`. The library HAS delete-for-me: `chatModify({deleteForMe:{deleteMedia,key,timestamp}}, jid)` (`Types/Chat.d.ts:76` via `Socket/chats.d.ts:64`). `target.key` is already obtained via `requireStored(messageId)` and `chatModify` is already in use at `baileys.adapter.ts:820,833`. Drop the `if(!forEveryone) throw` guard at line 655 and route the false branch to `chatModify`.+- **`getChatHistory` (baileys, library-limitation).** The only history primitive is `fetchMessageHistory(count, oldestMsgKey, oldestMsgTimestamp)` (`Socket/business.d.ts:25`) — it returns a sync-token *string*, not messages; the messages are delivered later via the `messaging-history.set` event. There is no per-chat `fetchMessages(chatId, limit)` on the socket. A synchronous `Promise<IncomingMessage[]>` for one chat would require an OpenWA-side chat-indexed store populated from `messages.upsert` + `messaging-history.set` events.+- **`getMessageReactions` (baileys, library-limitation).** No on-demand server fetch. Reactions exist only as event-augmented state on `WAMessage.reactions` (`proto.IReaction[]` at `WAProto/index.d.ts:10623`), mutated by `updateMessageWithReaction` and surfaced via the `messages.reaction` event. The adapter already processes `reactionMessage` events (`baileys.adapter.ts:1048-1057`) and emits `onMessageReaction`, but it does **not** persist `.reactions` into its `messageStore` (early-returns at line 1058). A store-backed read would need that persistence added first; even then, only reactions observed since session start are known (no historical backfill).++---++## Prioritized roadmap — adapter gaps (fixable in this repo)++These are the capabilities the underlying library already supports but the OpenWA adapter does not wire. Ranked high-value + low-effort first. Each is a self-contained backlog item; an engineer can open the cited symbol and start.++### Tier 1 — small effort, high value++| # | Method : engine | Library call to wire | Effort | Value |+|---|---|---|---|---|+| 1 | `deleteMessage` (forEveryone=false) : **baileys** | `sock.chatModify({deleteForMe:{deleteMedia:true,key,target.key,timestamp:Date.now()}}, chatId)` — drop the `!forEveryone` throw at `baileys.adapter.ts:655` | **S** | Core messaging op. Delete-for-me is heavily used; currently 501 on baileys for the most common delete mode. `chatModify` already used at lines 820/833; `target.key` already resolved. |+| 2 | `postTextStatus` : **wwjs** | `client.sendMessage('status@broadcast', text, {extra:{backgroundColor,font}})` — routes to `sendStatusTextMsgAction` (`Utils.js:537`) | **S** | Status broadcast parity. Flagship feature currently 501 on the default engine despite the library supporting it. Document the `recipients` (statusJidList) caveat. |+| 3 | `postImageStatus` : **wwjs** | `client.sendMessage('status@broadcast', new MessageMedia(...), {caption})` — routes to `sendStatusMediaMsgAction` (`Utils.js:565`) | **S** | Same as above for image status. |+| 4 | `postVideoStatus` : **wwjs** | `client.sendMessage('status@broadcast', new MessageMedia(...), {caption})` — routes to `sendStatusMediaMsgAction` (`Utils.js:565`) | **S** | Same as above for video status. |+| 5 | `addLabelToChat` : **baileys** | `await sock.addChatLabel(chatId, labelId)` (`Socket/chats.d.ts:70`) | **S** | 1:1 mapping. WhatsApp Business CRM parity. |+| 6 | `removeLabelFromChat` : **baileys** | `await sock.removeChatLabel(chatId, labelId)` (`Socket/chats.d.ts:71`) | **S** | 1:1 mapping. Pairs with #5. |++### Tier 2 — small-to-medium effort, medium-high value++| # | Method : engine | Library call to wire | Effort | Value |+|---|---|---|---|---|+| 7 | `getChannelById` : **baileys** | `sock.newsletterMetadata('jid', channelId)` → map `NewsletterMetadata` (`Socket/newsletter.d.ts:9`) | **S** | Channel/newsletter parity. ~1-liner field map. |+| 8 | `unsubscribeFromChannel` : **baileys** | `await sock.newsletterUnfollow(channelId)` (`Socket/newsletter.d.ts:11`) | **S** | 1:1, no jid resolution needed. |+| 9 | `subscribeToChannel` : **baileys** | 2-step: `newsletterMetadata('invite',code).id` then `newsletterFollow(jid)` (`Socket/newsletter.d.ts:9,10`) | **S** | Channel growth (join by invite code). |+| 10 | `deleteStatus` : **wwjs** | `await client.revokeStatusMessage(statusId)` (`index.d.ts:139`) | **S** | Completes the wwjs status lifecycle (post + delete). Own-status only. |+| 11 | `getContactStatuses` : **wwjs** | `client.getBroadcasts()` → flatten `Broadcast.msgs` to `Status[]` (`index.d.ts:133`) | **M** | Read contact stories on the default engine. Adapter already has the stub; replace `[]` with the call + mapping. |+| 12 | `getContactStatus` : **wwjs** | `client.getBroadcastById(contactId)` → map `Broadcast.msgs` (`index.d.ts:136`) | **M** | Per-contact story read. Pairs with #11. |++### Tier 3 — medium effort++| # | Method : engine | Library call to wire | Effort | Value |+|---|---|---|---|---|+| 13 | `getChannelMessages` : **baileys** | `sock.newsletterFetchMessages(jid,count,since,after)` (`Socket/newsletter.d.ts:19`) + hand-written `BinaryNode`→`ChannelMessage` parser | **M** | Read channel posts. The fetch is 1 line; the BinaryNode parsing/normalization is the real work (no library parser exposed). |+| 14 | `getProducts` : **baileys** | `sock.getCatalog({jid,limit,cursor})` → `{products, nextPageCursor}` (`Socket/business.d.ts:7`) | **M** | Commerce. Derive `pagination.total`/`totalPages` (cursor-based, total unknown — approximate or iterate). |+| 15 | `sendProduct` : **baileys** | 2-step: `getCatalog` lookup (image/title/price) then `sendMessage({product:{...},body})` (`Types/Message.d.ts:203`) | **M** | Outbound commerce. `productId`-only send is not possible without the lookup. |+| 16 | `getCatalog` : **baileys** | `getCatalog` + `getCollections` (`Socket/business.d.ts:7,11`); synthesize partial `Catalog` (medium-confidence shape) | **M** | Catalog metadata. Fields `id`/`description`/`url` have no source — best-effort. |++### Tier 4 — small effort, lower value++| # | Method : engine | Library call to wire | Effort | Value |+|---|---|---|---|---|+| 17 | `getProduct` : **baileys** | `getCatalog({jid,limit})` then `products.find(p=>p.id===productId)` (`Socket/business.d.ts:7`) | **S** | Single-product read. Inelegant — loads a whole page to fetch one product. Ship after #14 reuses the same catalog call. |++---++## Library limitations — not available without raw-proto/fork effort++These are honestly out of reach of a clean adapter wiring because the installed library exposes no first-class symbol. Listed so operators can plan around them rather than file unactionable bugs.++**baileys (9 cells):**+- `getSubscribedChannels` — no enumerate-newsletters query; all `Socket/newsletter.d.ts` exports are per-jid. Needs a raw WMex/app-state hack.+- `getLabels` / `getLabelById` / `getChatLabels` — no label read symbol; only writes (`Types/Label.d.ts` is types-only). Workaround: capture labels from the `messaging-history.set` app-state event into an in-memory cache (relay hack, no on-demand refresh).+- `getChatHistory` — only `fetchMessageHistory` (event-delivered sync token); no synchronous per-chat `fetchMessages`. Needs an OpenWA-side chat-indexed store fed from `messages.upsert` + `messaging-history.set`.+- `getMessageReactions` — no on-demand fetch; reactions only arrive via the `messages.reaction` event. Partial local path: persist each event into the `messageStore`, then read (no historical backfill).+- `getContactStatus` / `getContactStatuses` — `fetchStatus` returns the *about* text, not 24h stories; stories only surface as `status@broadcast` messages. Needs an OpenWA-side story accumulator.+- `sendCatalog` — no catalog-share message type in `AnyMessageContent` (only single `{product}`).++**wwjs (5 cells):**+- `getCatalog` / `getProducts` / `getProduct` — no catalog API at all (`index.d.ts` 0 hits; `Product` is inbound-only).+- `sendProduct` — no outbound product content type.+- `sendCatalog` — no outbound catalog content type.++---++## Snapshot summary++- **71** interface methods, **142** adapter-cells (71 × 2 engines).+- **111** supported cells; **31** not-available cells across **24** methods.+- Of the 31 not-available cells: **17 adapter-gaps** (fixable) + **14 library-limitations** + **0 uncertain**.+- **5 phantom-support corrections** in this re-frame (wwjs catalog + status-read methods that stubbed without throwing are now honestly `not-available`).diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.tsnew file mode 100644index 000000000..eca072754--- /dev/null+++ b/src/engine/engine-capability-matrix.ts@@ -0,0 +1,247 @@+/**+ * Committed engine capability matrix: for each `IWhatsAppEngine` method, the REAL availability on+ * each adapter — `wwjs` = whatsapp-web.js (the default engine), `baileys` = the browser-free+ * alternative.+ *+ * Two fields tell the story:+ * - `status`: 'supported' (the capability genuinely works end-to-end) or 'not-available' (the method+ * either throws `EngineNotSupportedError`/`ChannelMediaNotSupportedError` at the adapter boundary+ * → HTTP 501, OR the adapter claims support but the underlying library cannot deliver — a+ * phantom-support case surfaced by source verification, e.g. wwjs catalog methods that log+ * "not implemented" and return null/[] without throwing).+ * - `rootCause` (present only when `not-available`): WHY it is not available, so a contributor knows+ * exactly where to start. Three values:+ * 'adapter-gap' — the underlying library HAS the capability; only the OpenWA adapter+ * wiring is missing. FIXABLE in this repo (a PR that calls the library+ * symbol the evidence points at).+ * 'library-limitation' — the underlying library exposes NO first-class symbol for this op. Not+ * fixable without a raw-proto/fork effort or an event-cache hack.+ * 'uncertain' — source trace was inconclusive; needs a live spike.+ *+ * `evidence` (present only when at least one adapter is `not-available`) cites the library symbol(s)+ * that were inspected, so an engineer can open the exact file and start wiring immediately.+ *+ * This is a SNAPSHOT. `engine-parity.spec.ts` regenerates the supported/not-available *classification*+ * from the live adapter method bodies (a method is "not-available" if it throws+ * EngineNotSupportedError / ChannelMediaNotSupportedError) and fails on drift, so a parity change+ * cannot land without deliberately updating this matrix (and docs/engine-capability-matrix.md). The+ * `rootCause`/`evidence` fields are hand-curated, source-traced annotations; they are NOT regenerated+ * by the spec and are updated by hand as adapters are wired or libraries change.+ *+ * NOTE on phantom support: the drift gate's throw-heuristic cannot see adapter methods that silently+ * stub (return null/[] + a warn log) without throwing. The matrix BELOW is the source-of-truth: five+ * wwjs entries (getCatalog/getProducts/getProduct/getContactStatus/getContactStatuses) are marked+ * `not-available` here even though their adapter bodies do not throw — because the underlying library+ * either has no API (catalog) or the adapter stubs instead of calling the available symbol (status+ * read). If the drift gate is extended to assert against this matrix, it must consult `status`, not+ * just the throw pattern, for these rows (or the adapter stubs must start throwing).+ */+export type CapabilityStatus = 'supported' | 'not-available';+export type RootCause = 'adapter-gap' | 'library-limitation' | 'uncertain';++export interface AdapterCapability {+ status: CapabilityStatus;+ /** Present only when `status === 'not-available'`. */+ rootCause?: RootCause;+}++export interface MethodCapability {+ wwjs: AdapterCapability;+ baileys: AdapterCapability;+ /** Cited library symbols (baileys; wwjs). Present only when at least one adapter is not-available. */+ evidence?: string;+}++export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {+ addLabelToChat: {+ wwjs: { status: 'supported' },+ baileys: { status: 'not-available', rootCause: 'adapter-gap' },+ evidence:+ 'baileys Socket/chats.d.ts:70 addChatLabel(jid,labelId) + business.d.ts:163 — adapter throws at baileys.adapter.ts:859; wwjs Client.js:2921 addOrRemoveLabels (adapter changeChatLabel @1534)',+ },+ addParticipants: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ blockContact: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ checkNumberExists: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ createGroup: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ deleteChat: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ deleteMessage: {+ wwjs: { status: 'supported' },+ baileys: { status: 'not-available', rootCause: 'adapter-gap' },+ evidence:+ 'baileys forEveryone=true already wired (sendMessage({delete})); forEveryone=false throws at baileys.adapter.ts:655 — library has chatModify({deleteForMe}) (Types/Chat.d.ts:76 via Socket/chats.d.ts:64, already used @baileys.adapter.ts:820,833); wwjs Message.delete (Message.js)',+ },+ deleteStatus: {+ wwjs: { status: 'not-available', rootCause: 'adapter-gap' },+ baileys: { status: 'supported' },+ evidence:+ 'wwjs Client.revokeStatusMessage (index.d.ts:139; Client.js:2795 WAWebRevokeStatusAction.sendStatusRevokeMsgAction) — adapter throws instead of calling it; baileys sendMessage(status@broadcast,{delete}) @baileys.adapter.ts:913 (self-described empirically-unverified revoke shape)',+ },+ demoteParticipants: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ destroy: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ disconnect: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ forceDestroy: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ forwardMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ getCatalog: {+ wwjs: { status: 'not-available', rootCause: 'library-limitation' },+ baileys: { status: 'not-available', rootCause: 'adapter-gap' },+ evidence:+ 'baileys Socket/business.d.ts:7 getCatalog({jid,limit,cursor}) + getCollections (business.d.ts:11) — adapter unwired (returns Product[]+cursor, not Catalog metadata; medium-confidence shape synthesis); wwjs index.d.ts has NO Client.getCatalog (0 hits), adapter stubs to null @whatsapp-web-js.adapter.ts:1770',+ },+ getChannelById: {+ wwjs: { status: 'supported' },+ baileys: { status: 'not-available', rootCause: 'adapter-gap' },+ evidence:+ 'baileys Socket/newsletter.d.ts:9 newsletterMetadata(type,key) → NewsletterMetadata (Mex.d.ts:115) — adapter unwired; wwjs resolves via getChannels() find-by-id @whatsapp-web-js.adapter.ts:1562',+ },+ getChannelMessages: {+ wwjs: { status: 'supported' },+ baileys: { status: 'not-available', rootCause: 'adapter-gap' },+ evidence:+ 'baileys Socket/newsletter.d.ts:19 newsletterFetchMessages(jid,count,since,after) returns RAW BinaryNode of <message_updates> (newsletter.js:149) — adapter unwired AND no exposed library parser (BinaryNode→ChannelMessage mapping is the work); wwjs Channel.fetchMessages (Channel.js:327)',+ },+ getChatHistory: {+ wwjs: { status: 'supported' },+ baileys: { status: 'not-available', rootCause: 'library-limitation' },+ evidence:+ 'baileys only fetchMessageHistory(count,oldestKey,oldestTs) (Socket/business.d.ts:25) returns a sync-token string; messages arrive later via messaging-history.set event — no synchronous per-chat fetchMessages; wwjs Chat.fetchMessages (Chat.js)',+ },+ getChatLabels: {+ wwjs: { status: 'supported' },+ baileys: { status: 'not-available', rootCause: 'library-limitation' },+ evidence:+ 'baileys no getChatLabels in lib/**/*.d.ts; Types/LabelAssociation.d.ts defines ChatLabelAssociation but no query fn (only addChatLabel/removeChatLabel writes @chats.d.ts:70-71); wwjs Client.getChatLabels (Client.js:2838)',+ },+ getChats: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ getContactById: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ getContactStatus: {+ wwjs: { status: 'not-available', rootCause: 'adapter-gap' },+ baileys: { status: 'not-available', rootCause: 'library-limitation' },+ evidence:+ 'baileys fetchStatus (Socket/chats.d.ts:42 via USyncStatusProtocol) = about/profile text only, NOT 24h stories — no story getter in lib; wwjs Client.getBroadcastById (index.d.ts:136; Client.js:2771) EXISTS but adapter stubs to [] @whatsapp-web-js.adapter.ts:1740',+ },+ getContactStatuses: {+ wwjs: { status: 'not-available', rootCause: 'adapter-gap' },+ baileys: { status: 'not-available', rootCause: 'library-limitation' },+ evidence:+ 'baileys fetchStatus = about text only; no story enumerate in lib; wwjs Client.getBroadcasts (index.d.ts:133; Client.js:2759 WWebJS.getAllStatuses) EXISTS but adapter stubs to [] @whatsapp-web-js.adapter.ts:1732',+ },+ getContacts: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ getGroupInfo: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ getGroupInviteCode: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ getGroups: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ getLabelById: {+ wwjs: { status: 'supported' },+ baileys: { status: 'not-available', rootCause: 'library-limitation' },+ evidence:+ 'baileys no getLabel/getLabelById in lib/**/*.d.ts (Types/Label.d.ts has only Label interface + LabelColor enum + LabelActionBody); derivable only from an app-state-sync label cache; wwjs Client.getLabelById (Client.js:2825)',+ },+ getLabels: {+ wwjs: { status: 'supported' },+ baileys: { status: 'not-available', rootCause: 'library-limitation' },+ evidence:+ 'baileys no getLabel/fetchLabel in lib/**/*.d.ts; chats.d.ts:69-73 + business.d.ts:162-166 expose ONLY writes; derivable only from an app-state-sync event cache; wwjs Client.getLabels (Client.js:2747)',+ },+ getMessageReactions: {+ wwjs: { status: 'supported' },+ baileys: { status: 'not-available', rootCause: 'library-limitation' },+ evidence:+ 'baileys no getReactions/fetchReactions; reactions exist only as event-augmented WAMessage.reactions (proto.IReaction @WAProto/index.d.ts:10623) via messages.reaction event; adapter does not persist them into its store; wwjs Message.getReactions (Message.js)',+ },+ getNumberId: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ getPhoneNumber: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ getProduct: {+ wwjs: { status: 'not-available', rootCause: 'library-limitation' },+ baileys: { status: 'not-available', rootCause: 'adapter-gap' },+ evidence:+ 'baileys only getCatalog (Socket/business.d.ts:7); getProduct = getCatalog then find-by-id (compose-and-filter, loads whole page; medium-confidence); wwjs no Client.getProduct — only page-internal getProductMetadata (Utils.js:1253), not a public Client fn; adapter stubs to null @whatsapp-web-js.adapter.ts:1786',+ },+ getProducts: {+ wwjs: { status: 'not-available', rootCause: 'library-limitation' },+ baileys: { status: 'not-available', rootCause: 'adapter-gap' },+ evidence:+ 'baileys Socket/business.d.ts:7 getCatalog({jid,limit,cursor}) → {products, nextPageCursor} — adapter unwired; wwjs no Client.getProducts in index.d.ts (0 hits); adapter stubs to empty @whatsapp-web-js.adapter.ts:1777',+ },+ getProfilePicture: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ getPushName: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ getQRCode: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ getStatus: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ getSubscribedChannels: {+ wwjs: { status: 'supported' },+ baileys: { status: 'not-available', rootCause: 'library-limitation' },+ evidence:+ 'baileys no enumerate-newsletters fn; all 23 Socket/newsletter.d.ts exports are per-jid (newsletterMetadata requires a key; newsletterSubscribers returns the count of ONE). Only the newsletter EVENT surfaces jids opportunistically (incremental, not list-all); wwjs Client.getChannels (Client.js:1680)',+ },+ initialize: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ leaveGroup: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ logout: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ markUnread: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ postImageStatus: {+ wwjs: { status: 'not-available', rootCause: 'adapter-gap' },+ baileys: { status: 'supported' },+ evidence:+ 'wwjs sendStatusMediaMsgAction (Utils.js:565) handles image status@broadcast — adapter throws "blocked upstream #455" instead of routing it; baileys postStatus({image,caption,mimetype}) @baileys.adapter.ts:888. Caveat: wwjs sendStatusMediaMsgAction has no recipients arg (statusJidList not honored)',+ },+ postTextStatus: {+ wwjs: { status: 'not-available', rootCause: 'adapter-gap' },+ baileys: { status: 'supported' },+ evidence:+ 'wwjs sendStatusTextMsgAction({color,font,text}) (Utils.js:537) — adapter throws "blocked upstream #455" instead of routing status@broadcast text; baileys sendMessage(status@broadcast,{text},{statusJidList,...}) @baileys.adapter.ts:885. Caveat: wwjs has no recipients arg (statusJidList not honored)',+ },+ postVideoStatus: {+ wwjs: { status: 'not-available', rootCause: 'adapter-gap' },+ baileys: { status: 'supported' },+ evidence:+ 'wwjs sendStatusMediaMsgAction (Utils.js:565) handles video/gif/audio status — adapter throws "blocked upstream #45455" instead of routing it; baileys postStatus({video,caption,mimetype}) @baileys.adapter.ts:891. Caveat: wwjs has no recipients arg (statusJidList not honored)',+ },+ promoteParticipants: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ reactToMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ removeLabelFromChat: {+ wwjs: { status: 'supported' },+ baileys: { status: 'not-available', rootCause: 'adapter-gap' },+ evidence:+ 'baileys Socket/chats.d.ts:71 removeChatLabel(jid,labelId) + business.d.ts:164 — adapter throws at baileys.adapter.ts:862; wwjs Client.js:2921 addOrRemoveLabels (adapter changeChatLabel @1534)',+ },+ removeParticipants: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ replyToMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ requestPairingCode: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ resolveContactPhone: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ revokeGroupInviteCode: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ sendAudioMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ sendCatalog: {+ wwjs: { status: 'not-available', rootCause: 'library-limitation' },+ baileys: { status: 'not-available', rootCause: 'library-limitation' },+ evidence:+ 'baileys AnyMessageContent (Types/Message.d.ts:166-210) has no catalog key — only {product} single-product + product_catalog_edit/add/delete CRUD (Socket/business.js:294-362); wwjs no Client.sendCatalog in index.d.ts (0 hits)',+ },+ sendChatState: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ sendContactMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ sendDocumentMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ sendImageMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ sendLocationMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ sendPollMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ sendProduct: {+ wwjs: { status: 'not-available', rootCause: 'library-limitation' },+ baileys: { status: 'not-available', rootCause: 'adapter-gap' },+ evidence:+ 'baileys AnyRegularMessageContent {product: WASendableProduct} (Types/Message.d.ts:203) built in messages.js:397 — adapter unwired (2-step: getCatalog lookup for image/title/price THEN sendMessage); wwjs no Client.sendProduct — Product/Order are inbound-only parsers',+ },+ sendSeen: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ sendStickerMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ sendTextMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ sendVideoMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ setGroupDescription: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ setGroupSubject: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ subscribeToChannel: {+ wwjs: { status: 'supported' },+ baileys: { status: 'not-available', rootCause: 'adapter-gap' },+ evidence:+ 'baileys Socket/newsletter.d.ts:10 newsletterFollow(jid) needs a jid — bridge via newsletterMetadata("invite",code).id (2-step); adapter unwired; wwjs Client.subscribeToChannel (Client.js:2529)',+ },+ unblockContact: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ unsubscribeFromChannel: {+ wwjs: { status: 'supported' },+ baileys: { status: 'not-available', rootCause: 'adapter-gap' },+ evidence:+ 'baileys Socket/newsletter.d.ts:11 newsletterUnfollow(jid) — channelId is the @newsletter jid, maps 1:1; adapter unwired; wwjs Client.unsubscribeFromChannel (Client.js:2550)',+ },+};diff --git a/src/engine/engine-parity.spec.ts b/src/engine/engine-parity.spec.tsnew file mode 100644index 000000000..9f91bab61--- /dev/null+++ b/src/engine/engine-parity.spec.ts@@ -0,0 +1,72 @@+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { BaileysAdapter } from './adapters/baileys.adapter';+import { WhatsAppWebJsAdapter } from './adapters/whatsapp-web-js.adapter';+import { ENGINE_CAPABILITY_MATRIX } from './engine-capability-matrix';++/**+ * Drift invariants for the engine capability matrix. The matrix's `status` (supported /+ * not-available) is hand-curated and richer than a throw-scan: it also marks "phantom support"+ * methods (adapter stubs that return null/[] without throwing — see docs/engine-capability-matrix.md).+ * So the gate asserts the invariants a throw-scan CAN verify, not full equality:+ *+ * 1. A method whose adapter body throws EngineNotSupportedError/ChannelMediaNotSupportedError+ * MUST be `not-available` in the matrix (throws always mean unavailable).+ * 2. A method the matrix marks `supported` MUST NOT throw.+ *+ * The allowed gap (not deliberate drift): a method that is `not-available` but does not throw today+ * — a phantom stub. Those are hand-tracked in the matrix; a throw-scan cannot see them. If an adapter+ * method starts or stops throwing, one of the invariants trips and forces a deliberate matrix update.+ *+ * No engine is instantiated and no Chromium/socket is opened: it reads method bodies via+ * `Class.prototype.method.toString()`, a fast hermetic structural check.+ */+const UNSUPPORTED_RE = /this\.unsupported\(|EngineNotSupportedError|ChannelMediaNotSupportedError/;++function readInterfaceMethods(): string[] {+ const src = readFileSync(join(__dirname, 'interfaces', 'whatsapp-engine.interface.ts'), 'utf8');+ const names = new Set<string>();+ for (const line of src.split('\n')) {+ const match = line.match(/^\s{2}([a-zA-Z][a-zA-Z0-9]*)\s*\(/);+ if (match) names.add(match[1]);+ }+ return [...names].sort();+}++type AdapterCtor = { prototype: Record<string, unknown> };+type AdapterKey = 'wwjs' | 'baileys';+const ADAPTERS: ReadonlyArray<[AdapterKey, AdapterCtor]> = [+ ['wwjs', WhatsAppWebJsAdapter as unknown as AdapterCtor],+ ['baileys', BaileysAdapter as unknown as AdapterCtor],+];++function liveThrows(adapter: AdapterCtor, method: string): boolean {+ const fn = adapter.prototype[method];+ if (typeof fn !== 'function') return true; // missing method = effectively unavailable+ return UNSUPPORTED_RE.test(String(fn));+}++describe('engine capability matrix — drift invariants', () => {+ const methods = readInterfaceMethods();+ const matrixKeys = Object.keys(ENGINE_CAPABILITY_MATRIX).sort();++ it('matrix keys exactly match the interface methods (no missing, no stale)', () => {+ const missing = methods.filter(m => !(m in ENGINE_CAPABILITY_MATRIX));+ const stale = matrixKeys.filter(k => !methods.includes(k));+ expect({ missing, stale }).toEqual({ missing: [], stale: [] });+ });++ it.each(methods)('%s: throws ⇒ not-available, supported ⇒ not-throws', method => {+ const entry = ENGINE_CAPABILITY_MATRIX[method];+ for (const [adapter, ctor] of ADAPTERS) {+ const throws = liveThrows(ctor, method);+ const status = entry[adapter].status;+ if (throws) {+ expect({ method, adapter, status }).toEqual({ method, adapter, status: 'not-available' });+ }+ if (status === 'supported') {+ expect({ method, adapter, throws }).toEqual({ method, adapter, throws: false });+ }+ }+ });+});