Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

chore(engine): gate the hand-filled columns of the capability inventory

Yudhi Armyndharisdf0d04d9cd72
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eccdaf18d..4a612389f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Engine inventory drift guard** — `src/engine/engine-inventory-parity.spec.ts` checks the two hand-filled columns of `docs/29`: a symbol marked as used must appear in adapter code rather than only in a comment, an interface method named in a wired cell must be `supported` for that engine in the capability matrix, and an event marked consumed must have a listener behind it — so the inventory cannot drift away from the adapters unnoticed the way it did before.
- **The engine capability matrix now covers every library method, event and install-time patch** — `docs/29` grew from the 105-method contract view into a three-way comparison of the Baileys library, the whatsapp-web.js library and what OpenWA actually exposes: all 152 Baileys socket methods and 81 whatsapp-web.js Client methods mapped to the interface method that uses them (or marked unexposed, which is the implementation backlog), all 34 + 31 library events marked consumed or dropped, all five install-time patches with the rows that depend on them, and the capabilities both libraries already have that only OpenWA lacks. Every exposure mark was traced back to adapter code, so the inventory reflects what the adapters call rather than what they mention.
- **An onboarding modal the detector does not recognise now shows up in the logs instead of failing silently** — when the "What's new" probe finds nothing to click, the watcher reports the visible dialog's heading and confirm-button labels once per distinct dialog (`action: onboarding_dialog_unrecognized`), so a renamed or localised modal can be covered via `WWEBJS_ONBOARDING_CONTINUE_LABELS` before WhatsApp unlinks the companion. The watcher also logs when it arms and a summary when it stops at its lifetime cap (both debug). Refs #1072.
diff --git a/src/engine/engine-inventory-parity.spec.ts b/src/engine/engine-inventory-parity.spec.ts
new file mode 100644
index 000000000..b39f13ada
--- /dev/null
+++ b/src/engine/engine-inventory-parity.spec.ts
@@ -0,0 +1,184 @@
+import { readdirSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { ENGINE_CAPABILITY_MATRIX } from './engine-capability-matrix';
+
+/**
+ * Drift invariants for the hand-maintained halves of docs/29-engine-capability-matrix.md.
+ *
+ * 29.4 is already guarded (engine-parity.spec.ts) and the symbol LISTS in 29.5 are already guarded
+ * (check-upstream-surface.mjs vs the snapshot). What nothing watched was the two columns a human
+ * fills in by hand:
+ *
+ * - 29.5.1/29.5.2 "OpenWA exposure" — which library symbol the adapters actually use.
+ * - 29.5.4 "OpenWA" — which library events the adapters actually subscribe to.
+ *
+ * Both drifted: symbols marked ✅/⚙️ that appear only inside a comment, and events marked ✅ with no
+ * listener at all. Those are exactly the marks a reader triaging backlog work trusts most, so they
+ * get a gate.
+ *
+ * What this gate CANNOT see, and why (do not read a green run as more than it is):
+ * - Under-mapping. A ✅ row listing four interface methods when the symbol really serves eight
+ * still passes; the check is "the claim has code behind it", not "the claim is exhaustive".
+ * - A library symbol whose name collides with an adapter method of the same name (`logout`,
+ * `createGroup`, …). `this.lifecycle.logout()` is indistinguishable here from `sock.logout()`.
+ * - Direction. Mapping symbol A to interface method B instead of C passes as long as both exist.
+ */
+const DOC = join(__dirname, '..', '..', 'docs', '29-engine-capability-matrix.md');
+const ADAPTER_DIR = join(__dirname, 'adapters');
+
+type Row = { symbol: string; exposure: string };
+type EventRow = { event: string; consumed: boolean };
+type Engine = 'baileys' | 'wwjs';
+type Snapshot = {
+ baileys: { socketMethods: string[]; events: string[] };
+ 'whatsapp-web.js': { clientMethods: string[]; events: string[] };
+};
+
+function docText(): string {
+ return readFileSync(DOC, 'utf8');
+}
+
+/** Adapter sources, comments removed but string literals kept — for finding `.on('event')`. */
+function adapterSourcesWithStrings(): string {
+ return readdirSync(ADAPTER_DIR)
+ .filter(f => f.endsWith('.ts') && !f.endsWith('.spec.ts'))
+ .map(f => stripComments(readFileSync(join(ADAPTER_DIR, f), 'utf8')))
+ .join('\n');
+}
+
+function stripComments(src: string): string {
+ return src.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/(^|[^:/])\/\/[^\n]*/g, '$1 ');
+}
+
+/**
+ * A symbol counts as used only as a property access (`.symbol`), never as a bare word. That is what
+ * separates a real call from the same name sitting inside a string — `EngineNotSupportedError('x')`
+ * names its own method, and a doc-mirroring error message must not be able to satisfy this gate.
+ *
+ * String literals are deliberately NOT stripped: doing so needs a real tokenizer, and a regex that
+ * tries collapses on an apostrophe inside a double-quoted string ("don't"), silently eating the code
+ * between it and the next quote — which fails OPEN, the one direction a drift gate must never fail.
+ */
+function isUsedInAdapterCode(symbol: string, code: string): boolean {
+ return new RegExp(`\\.${symbol}\\b`).test(code);
+}
+
+/** Rows of the 29.5.1 / 29.5.2 inventory tables, by engine. */
+function readInventory(engine: Engine): Row[] {
+ const doc = docText();
+ const start = doc.indexOf(engine === 'baileys' ? '### 29.5.1' : '### 29.5.2');
+ const end = doc.indexOf(engine === 'baileys' ? '### 29.5.2' : '### 29.5.3');
+ const rows: Row[] = [];
+ for (const line of doc.slice(start, end).split('\n')) {
+ const m = line.match(/^\|\s*`([^`]+)`\s*\|(.+?)\|\s*$/);
+ if (m) rows.push({ symbol: m[1], exposure: m[2].trim() });
+ }
+ return rows;
+}
+
+/** Rows of the 29.5.4 event tables, by engine. The tables carry two event pairs per line. */
+function readEvents(engine: Engine): EventRow[] {
+ const doc = docText();
+ const section = doc.slice(doc.indexOf('### 29.5.4'), doc.indexOf('## 29.6'));
+ const bailStart = section.indexOf('**Baileys');
+ const wwjsStart = section.indexOf('**whatsapp-web.js');
+ const block = engine === 'baileys' ? section.slice(bailStart, wwjsStart) : section.slice(wwjsStart);
+ const rows: EventRow[] = [];
+ for (const line of block.split('\n')) {
+ if (!line.startsWith('|') || /^\|\s*-+/.test(line)) continue;
+ const cells = line
+ .split('|')
+ .slice(1, -1)
+ .map(c => c.trim());
+ for (let i = 0; i < cells.length - 1; i++) {
+ const m = cells[i].match(/^`([a-zA-Z][a-zA-Z_.-]*)`$/);
+ if (m) {
+ rows.push({ event: m[1], consumed: cells[i + 1].startsWith('✅') });
+ i++;
+ }
+ }
+ }
+ return rows;
+}
+
+const registeredEvents = new Set(
+ [...adapterSourcesWithStrings().matchAll(/\.on\(\s*'([a-zA-Z][a-zA-Z_.-]*)'/g)].map(m => m[1]),
+);
+
+describe('engine inventory (docs/29 §29.5) — drift invariants', () => {
+ // Guards against a parser that silently stops matching: an empty or short parse would make every
+ // invariant below vacuously true. The expected sizes are the gated snapshot's, not magic numbers.
+ it('the document parsers actually found the tables', () => {
+ const snapshot = JSON.parse(
+ readFileSync(join(__dirname, '..', '..', 'scripts', 'upstream-surface.snapshot.json'), 'utf8'),
+ ) as Snapshot;
+ expect({
+ baileysRows: readInventory('baileys').length,
+ wwjsRows: readInventory('wwjs').length,
+ baileysEvents: readEvents('baileys').length,
+ wwjsEvents: readEvents('wwjs').length,
+ }).toEqual({
+ baileysRows: snapshot.baileys.socketMethods.length,
+ wwjsRows: snapshot['whatsapp-web.js'].clientMethods.length,
+ baileysEvents: snapshot.baileys.events.length,
+ wwjsEvents: snapshot['whatsapp-web.js'].events.length,
+ });
+ });
+
+ // The source scrubber is the other thing that can fail open: if it stopped removing comments,
+ // every "symbol appears in code" assertion would pass on a mention inside a comment — the exact
+ // defect this gate exists to catch. Checked on a synthetic sample so it never depends on the repo.
+ it('the comment scrubber and the usage test behave on a synthetic sample', () => {
+ const sample = [
+ '// a comment mentioning .commentGhost()',
+ '/* a block mentioning .blockGhost() */',
+ 'const msg = "the adapter doesn\'t call ghostInString";',
+ "throw new EngineNotSupportedError('namedGhost');",
+ 'this.sock().realCall();',
+ "sock.ev.on('real.event', handler);",
+ ].join('\n');
+ const scrubbed = stripComments(sample);
+ // A mention inside a comment must not count as usage — the defect this gate exists to catch.
+ expect(isUsedInAdapterCode('commentGhost', scrubbed)).toBe(false);
+ expect(isUsedInAdapterCode('blockGhost', scrubbed)).toBe(false);
+ // Nor may a method naming itself in its own throw.
+ expect(isUsedInAdapterCode('namedGhost', scrubbed)).toBe(false);
+ // A real property access must count, and the apostrophe above must not have eaten it.
+ expect(isUsedInAdapterCode('realCall', scrubbed)).toBe(true);
+ expect(scrubbed).toMatch(/real\.event/);
+ // The real adapter corpus must be non-trivial, or the scan proves nothing.
+ expect(adapterSourcesWithStrings().length).toBeGreaterThan(50_000);
+ expect(registeredEvents.size).toBeGreaterThanOrEqual(20);
+ });
+
+ describe.each<Engine>(['baileys', 'wwjs'])('%s', engine => {
+ it('every ✅/⚙️ exposure mark has the symbol somewhere in adapter CODE, not just a comment', () => {
+ const code = adapterSourcesWithStrings();
+ const unsupported = readInventory(engine)
+ .filter(r => r.exposure.startsWith('✅') || r.exposure.startsWith('⚙️'))
+ .filter(r => !isUsedInAdapterCode(r.symbol, code))
+ .map(r => r.symbol);
+ expect(unsupported).toEqual([]);
+ });
+
+ it('every interface method named in a ✅ exposure cell is `supported` for this engine', () => {
+ const offenders: string[] = [];
+ for (const row of readInventory(engine)) {
+ if (!row.exposure.startsWith('✅')) continue;
+ for (const [, method] of row.exposure.matchAll(/`([a-zA-Z][a-zA-Z0-9]*)`/g)) {
+ const entry = ENGINE_CAPABILITY_MATRIX[method];
+ if (!entry) continue; // prose backtick, not an interface method
+ if (entry[engine].status !== 'supported') offenders.push(`${row.symbol} → ${method}`);
+ }
+ }
+ expect(offenders).toEqual([]);
+ });
+
+ it('the ✅ event marks match the listeners the adapters register', () => {
+ const wrong = readEvents(engine)
+ .filter(row => row.consumed !== registeredEvents.has(row.event))
+ .map(row => `${row.event}: doc=${row.consumed ? '✅' : '❌'} registered=${registeredEvents.has(row.event)}`);
+ expect(wrong).toEqual([]);
+ });
+ });
+});