The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(whatsapp): stamp every bridge console line in the local log shape
alt-glitch1e2498a23d03
diff --git a/scripts/whatsapp-bridge/bridge.js b/scripts/whatsapp-bridge/bridge.jsindex 02d0b7215c5..68569ec5bc7 100644--- a/scripts/whatsapp-bridge/bridge.js+++ b/scripts/whatsapp-bridge/bridge.js@@ -38,6 +38,7 @@ import {buildPollPayload,createReconnectScheduler,createVersionResolver,+ installConsoleStamps,buildLocationPayload,buildTextSendPayload,createBoundedMessageStore,@@ -50,9 +51,12 @@ import {normalizeWhatsAppId,pollCreationMessageFromPayload,pollUpdateForAggregation,- timestampedLine,+ writeJsonLine,} from './bridge_helpers.js';+// First statement: helpers capture console.log as a default at call time below.+installConsoleStamps();+// Parse CLI argsconst args = process.argv.slice(2);function getArg(name, defaultVal) {@@ -225,7 +229,7 @@ function redactWhatsAppId(value) {function emitDebugEvent(payload) {if (!WHATSAPP_DEBUG) return;try {- console.log(JSON.stringify({ event: 'debug', ...payload }));+ writeJsonLine({ event: 'debug', ...payload });} catch {}}@@ -294,7 +298,7 @@ function pollAggregationSummary(aggregation) {function logPollUpdateDiagnostic({ sourcePath, pollId, pollCreation, pollUpdates, selectedOptions, aggregation }) {const firstUpdate = pollUpdates?.[0] || {};try {- console.log(JSON.stringify({+ writeJsonLine({event: 'poll_update_decode',sourcePath,pollId: pollId || '',@@ -303,7 +307,7 @@ function logPollUpdateDiagnostic({ sourcePath, pollId, pollCreation, pollUpdateshasVote: !!firstUpdate.vote,selectedOptionsLength: selectedOptions?.length || 0,aggregation: pollAggregationSummary(aggregation),- }));+ });} catch {}}@@ -323,7 +327,7 @@ function enqueuePollUpdateEvent({ key, update, selectedOptions, aggregation }) {// inject agent-visible messages on every vote.if (!pollId || !recentlySentIds.has(pollId)) {if (WHATSAPP_DEBUG) {- try { console.log(JSON.stringify({ event: 'ignored', reason: 'foreign_poll_update', pollId })); } catch {}+ try { writeJsonLine({ event: 'ignored', reason: 'foreign_poll_update', pollId }); } catch {}}return;}@@ -377,7 +381,7 @@ let connectionState = 'disconnected';function emitPairEvent(event) {if (!PAIR_JSON) return;try {- console.log(JSON.stringify({ ts: Date.now(), ...event }));+ writeJsonLine({ ts: Date.now(), ...event });} catch {}}@@ -415,7 +419,8 @@ async function startSocket() {emitPairEvent({ event: 'qr', qr });} else {console.log('\nπ± Scan this QR code with WhatsApp on your phone:\n');- qrcode.generate(qr, { small: true });+ // The QR block is multi-line art; a stamp on its first row would skew it.+ qrcode.generate(qr, { small: true }, (code) => process.stdout.write(`${code}\n`));console.log('\nWaiting for scan...\n');}}@@ -427,7 +432,7 @@ async function startSocket() {if (reason === DisconnectReason.loggedOut) {emitPairEvent({ event: 'error', error: 'logged_out', reason });if (!PAIR_JSON) {- console.log(timestampedLine('β Logged out. Delete session and restart to re-authenticate.'));+ console.log('β Logged out. Delete session and restart to re-authenticate.');}process.exit(1);} else {@@ -435,9 +440,9 @@ async function startSocket() {emitPairEvent({ event: 'disconnected', reason });if (!PAIR_JSON) {if (reason === 515) {- console.log(timestampedLine('β» WhatsApp requested restart (code 515). Reconnecting...'));+ console.log('β» WhatsApp requested restart (code 515). Reconnecting...');} else {- console.log(timestampedLine(`β οΈ Connection closed (reason: ${reason}). Reconnecting in 3s...`));+ console.log(`β οΈ Connection closed (reason: ${reason}). Reconnecting in 3s...`);}}scheduleReconnect(reason === 515 ? 1000 : 3000);@@ -452,11 +457,11 @@ async function startSocket() {: null;emitPairEvent({ event: 'connected', user: connectedUser });if (!PAIR_JSON) {- console.log(timestampedLine('β WhatsApp connected!'));+ console.log('β WhatsApp connected!');}if (PAIR_ONLY) {if (!PAIR_JSON) {- console.log(timestampedLine('β Pairing complete. Credentials saved.'));+ console.log('β Pairing complete. Credentials saved.');}// Give Baileys a moment to flush creds, then exit cleanlysetTimeout(() => process.exit(0), 2000);@@ -500,7 +505,7 @@ async function startSocket() {});}} catch (err) {- console.warn(timestampedLine(`[bridge] failed to aggregate poll update: ${err.message}`));+ console.warn('[bridge] failed to aggregate poll update:', err.message);}const selectedOptions = normalizePollUpdateOptions(aggregation, pollUpdates?.[0]);logPollUpdateDiagnostic({@@ -583,12 +588,12 @@ async function startSocket() {if (decision.action === 'drop_disabled') continue;if (decision.action === 'drop_allowlist') {try {- console.log(JSON.stringify({+ writeJsonLine({event: 'ignored',reason: 'allowlist_mismatch_owner_chat',chatId,senderId,- }));+ });} catch {}continue;}@@ -629,12 +634,12 @@ async function startSocket() {if (!msg.key.fromMe) {if (WHATSAPP_MODE === 'self-chat') {try {- console.log(JSON.stringify({+ writeJsonLine({event: 'ignored',reason: 'self_chat_mode_rejects_non_self',chatId,senderId,- }));+ });} catch {}continue;}@@ -649,13 +654,13 @@ async function startSocket() {|| matchesAllowedSender(senderId, senderAltId, ALLOWED_USERS, SESSION_DIR);if (!intakeAllowed) {try {- console.log(JSON.stringify({+ writeJsonLine({event: 'ignored',reason: isGroup ? 'group_policy_rejected' : 'allowlist_mismatch',chatId,senderId,senderAltId,- }));+ });} catch {}continue;}@@ -701,7 +706,7 @@ async function startSocket() {});}} catch (err) {- console.warn(timestampedLine(`[bridge] failed to aggregate poll upsert: ${err.message}`));+ console.warn('[bridge] failed to aggregate poll upsert:', err.message);}const selectedOptions = normalizePollUpdateOptions(aggregation, pollUpdates[0]);logPollUpdateDiagnostic({@@ -949,7 +954,7 @@ app.post('/send-media', async (req, res) => {gifPlayback: true,};} catch (gifErr) {- console.warn(timestampedLine(`[bridge] gif conversion failed, sending as image/gif: ${gifErr.message}`));+ console.warn('[bridge] gif conversion failed, sending as image/gif:', gifErr.message);msgPayload = mediaPayloadForFile({ buffer, filePath, mediaType: type, caption, fileName });} finally {try { if (tmpGifMp4 && existsSync(tmpGifMp4)) unlinkSync(tmpGifMp4); } catch (_) {}@@ -981,7 +986,7 @@ app.post('/send-media', async (req, res) => {audioExt = 'ogg';} catch (convErr) {// ffmpeg not available or conversion failed β fall back to original format- console.warn(timestampedLine(`[bridge] ffmpeg conversion failed, sending as file attachment: ${convErr.message}`));+ console.warn('[bridge] ffmpeg conversion failed, sending as file attachment:', convErr.message);} finally {try { if (tmpPath && existsSync(tmpPath)) unlinkSync(tmpPath); } catch (_) {}}@@ -1089,7 +1094,7 @@ app.post('/read', async (req, res) => {await sock.readMessages(receiptKeys);return res.json({ success: true, marked: true });} catch (err) {- console.warn(timestampedLine(`[bridge] failed to send read receipt: ${err.message}`));+ console.warn('[bridge] failed to send read receipt:', err.message);return res.status(500).json({ error: 'Failed to send read receipt' });}});@@ -1150,8 +1155,8 @@ if (PAIR_ONLY) {});} else {app.listen(PORT, '127.0.0.1', () => {- console.log(timestampedLine(`π WhatsApp bridge listening on port ${PORT} (mode: ${WHATSAPP_MODE})`));- console.log(timestampedLine(`π Session stored in: ${SESSION_DIR}`));+ console.log(`π WhatsApp bridge listening on port ${PORT} (mode: ${WHATSAPP_MODE})`);+ console.log(`π Session stored in: ${SESSION_DIR}`);if (ALLOWED_USERS.size > 0) {console.log(`π Allowed users: ${Array.from(ALLOWED_USERS).join(', ')}`);} else if (WHATSAPP_MODE === 'self-chat') {diff --git a/scripts/whatsapp-bridge/bridge_helpers.js b/scripts/whatsapp-bridge/bridge_helpers.jsindex 100744c6f27..d8f78cb8b3d 100644--- a/scripts/whatsapp-bridge/bridge_helpers.js+++ b/scripts/whatsapp-bridge/bridge_helpers.js@@ -1,6 +1,7 @@import path from 'path';import { mkdirSync, writeFileSync } from 'fs';import { randomBytes } from 'crypto';+import { format } from 'util';export const MIME_MAP = {jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png',@@ -726,18 +727,30 @@ export function createVersionResolver(fetchVersionFn, {};}+const pad = (value, width = 2) => String(value).padStart(width, '0');++/** `2026-09-28 13:18:46,062` in local time: the asctime shape every file in logs/ uses. */+export function formatLogStamp(date) {+ const day = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;+ const time = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;+ return `${day} ${time},${pad(date.getMilliseconds(), 3)}`;+}+/**- * Prefix a human-facing bridge log line with an ISO-8601 UTC timestamp.- *- * Startup/connection-lifecycle console.log/console.warn lines carried no- * timestamp, and the platform adapter pipes the bridge's stdout/stderr- * verbatim into bridge.log (no timestamps are added downstream either) --- * only structured JSON events (pair events, allowlist rejections, #92683)- * were timestamped. During incident forensics this made bridge.log- * impossible to sequence on its own (issue #97021). Kept distinct from the- * JSON `ts: Date.now()` convention those structured events use since these- * are plain human-readable lines, not JSON payloads.+ * Stamp every console.log/warn/error line. The adapter captures stdout/stderr+ * verbatim into bridge.log, which otherwise cannot be sequenced (#97021).*/-export function timestampedLine(message) {- return `[${new Date().toISOString()}] ${message}`;+export function installConsoleStamps(target = console) {+ for (const method of ['log', 'warn', 'error']) {+ const original = target[method].bind(target);+ target[method] = (...args) => {+ const text = format(...args);+ original('%s', text ? `${formatLogStamp(new Date())} ${text}` : text);+ };+ }+}++/** Machine-read JSON event lines bypass the console stamp so line parsers see bare JSON. */+export function writeJsonLine(payload, stream = process.stdout) {+ stream.write(`${JSON.stringify(payload)}\n`);}diff --git a/scripts/whatsapp-bridge/bridge_helpers.timestamp.test.mjs b/scripts/whatsapp-bridge/bridge_helpers.timestamp.test.mjsindex 2fe7670be01..2db1c5e8517 100644--- a/scripts/whatsapp-bridge/bridge_helpers.timestamp.test.mjs+++ b/scripts/whatsapp-bridge/bridge_helpers.timestamp.test.mjs@@ -1,65 +1,94 @@/**- * Unit tests for timestampedLine, the ISO-8601-prefix helper for- * bridge.js's human-facing lifecycle log lines.+ * Unit tests for the bridge's log-line stamping: formatLogStamp,+ * installConsoleStamps and writeJsonLine.** Regression for issue #97021: startup/connection lifecycle console.log/* console.warn lines (bridge listening, connected, logged out, reconnect,* "[bridge] ..." warnings) carried no timestamp, and the platform adapter- * captures the bridge's stdout/stderr verbatim into bridge.log -- only- * structured JSON events (pair events, allowlist rejections, #92683) were- * timestamped, making bridge.log impossible to sequence on its own during- * incident forensics.+ * captures the bridge's stdout/stderr verbatim into bridge.log, making+ * bridge.log impossible to sequence on its own during incident forensics.+ * Machine-read JSON event lines (pair events parsed line-by-line by the+ * dashboard pairing watcher, `ignored` events) must stay byte-identical.*/import { strict as assert } from 'node:assert';-import { timestampedLine } from './bridge_helpers.js';+import { formatLogStamp, installConsoleStamps, writeJsonLine } from './bridge_helpers.js';-const ISO_8601_PREFIX_RE = /^\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z\] /;+const LOCAL_STAMP_PREFIX_RE = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3} /;-// The prefix is a valid, parseable ISO-8601 UTC timestamp.-{- const line = timestampedLine('β WhatsApp connected!');-- assert.match(line, ISO_8601_PREFIX_RE);+function captureWrites(stream, fn) {+ const chunks = [];+ const originalWrite = stream.write;+ stream.write = (chunk, ...rest) => {+ chunks.push(String(chunk));+ const callback = rest.find(arg => typeof arg === 'function');+ if (callback) callback();+ return true;+ };+ try {+ fn();+ } finally {+ stream.write = originalWrite;+ }+ return chunks;+}- const bracketed = line.slice(1, line.indexOf(']'));- assert.ok(!Number.isNaN(new Date(bracketed).getTime()));+function withStampedConsole(fn) {+ const saved = { log: console.log, warn: console.warn, error: console.error };+ installConsoleStamps();+ try {+ fn();+ } finally {+ Object.assign(console, saved);+ }}-// The original message text survives byte-for-byte after the prefix ---// this is a display shim, not a message-mangling one.+// The stamp is local wall-clock time in Python's asctime shape.{- const message = 'β Logged out. Delete session and restart to re-authenticate.';- const line = timestampedLine(message);-- assert.ok(line.endsWith(message));+ assert.equal(formatLogStamp(new Date(2026, 8, 28, 3, 4, 5, 62)), '2026-09-28 03:04:05,062');}-// A template-literal-interpolated message (matching the actual bridge.js-// call sites, e.g. the reconnect/warn lines) is preserved intact too.-{- const reason = 'stream error';- const message = `β οΈ Connection closed (reason: ${reason}). Reconnecting in 3s...`;- const line = timestampedLine(message);+// A console.log line is stamped with the current local time, and the message+// text survives byte-for-byte after the stamp.+withStampedConsole(() => {+ const before = Date.now();+ const out = captureWrites(process.stdout, () => {+ console.log('β Logged out. Delete session and restart to re-authenticate.');+ });- assert.ok(line.includes('stream error'));- assert.ok(line.endsWith(message));-}+ assert.equal(out.length, 1);+ assert.match(out[0], LOCAL_STAMP_PREFIX_RE);+ assert.ok(out[0].endsWith(' β Logged out. Delete session and restart to re-authenticate.\n'));+ const [day, time] = out[0].split(' ');+ const stampedMs = new Date(`${day}T${time.replace(',', '.')}`).getTime();+ assert.ok(Math.abs(stampedMs - before) < 5000, `stamp ${day} ${time} is not local now`);+});-// Two calls a moment apart produce increasing (or equal, at ms resolution)-// timestamps -- the prefix reflects the actual call time, not a cached or-// module-load-time value, so a relaunch loop's individual lines remain-// independently sequenceable.-{- const first = timestampedLine('a');- await new Promise(resolve => setTimeout(resolve, 5));- const second = timestampedLine('b');+// console.warn keeps its multi-argument formatting and still goes to stderr.+withStampedConsole(() => {+ const err = captureWrites(process.stderr, () => {+ console.warn('[bridge] failed to send read receipt:', 'boom');+ });- const firstTs = new Date(first.slice(1, first.indexOf(']'))).getTime();- const secondTs = new Date(second.slice(1, second.indexOf(']'))).getTime();+ assert.equal(err.length, 1);+ assert.match(err[0], LOCAL_STAMP_PREFIX_RE);+ assert.ok(err[0].endsWith(' [bridge] failed to send read receipt: boom\n'));+});- assert.ok(secondTs >= firstTs);-}+// A JSON event line is not stamped, even with the console wrapped, so the+// pairing watcher's per-line json.loads still parses it.+withStampedConsole(() => {+ const out = captureWrites(process.stdout, () => {+ writeJsonLine({ ts: 1790000000000, event: 'qr', qr: 'abc' });+ });++ assert.deepEqual(out, ['{"ts":1790000000000,"event":"qr","qr":"abc"}\n']);+});++// An empty console.log() stays a bare newline rather than a lone stamp.+withStampedConsole(() => {+ assert.deepEqual(captureWrites(process.stdout, () => console.log()), ['\n']);+});console.log('bridge_helpers.timestamp.test.mjs: all assertions passed');