The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
ci: hourly live check of docs search with a Telegram alert
Teknium6d5af7a2756b
diff --git a/.github/workflows/docs-search-monitor.yml b/.github/workflows/docs-search-monitor.ymlnew file mode 100644index 00000000000..1e4c8ededfd--- /dev/null+++ b/.github/workflows/docs-search-monitor.yml@@ -0,0 +1,114 @@+name: Docs Search Monitor++# Live check that search works on hermes-agent.nousresearch.com/docs, with a+# Telegram alert when it breaks. Search broke in production twice in one+# month with every build green (a deleted Algolia search key, then Vercel+# access controls), because nothing ever exercised the deployed site.+#+# website/scripts/check-live-search.mjs reads the Algolia credentials from the+# bundle the site is serving, queries Algolia with the site's Origin, opens the+# top results, then types into the real search modal in headless Chromium.+#+# Alerts go to Telegram when search goes down, every 6 hours while it stays+# down, and once when it recovers. Configure on the `trusted-automation`+# environment (main-only, so branch workflows cannot read the bot token):+# DOCS_ALERT_TELEGRAM_BOT_TOKEN bot token from @BotFather+# DOCS_ALERT_TELEGRAM_CHAT_ID chat to notify (your user id or a group id)+# Without them the job still goes red; it just has nobody to tell.++on:+ schedule:+ - cron: '17 * * * *'+ workflow_run:+ workflows: ['Deploy Site']+ types: [completed]+ workflow_dispatch:+ inputs:+ test_alert:+ description: 'Send a test Telegram message to confirm the alert wiring'+ type: boolean+ default: false++permissions:+ contents: read+ actions: read++concurrency:+ group: docs-search-monitor+ cancel-in-progress: false++jobs:+ probe:+ if: github.repository == 'NousResearch/hermes-agent'+ runs-on: ubuntu-latest+ timeout-minutes: 15+ environment: trusted-automation+ steps:+ - uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7.0.1+ with:+ sparse-checkout: website/scripts+ persist-credentials: false++ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # 7.0.0+ with:+ node-version: 24.11.1++ - name: Install headless Chromium+ run: |+ npm install --no-save --no-audit --no-fund --prefix "$RUNNER_TEMP/pw" [email protected]+ npx --prefix "$RUNNER_TEMP/pw" playwright install --with-deps chromium-headless-shell++ - name: Probe live docs search+ id: probe+ env:+ PLAYWRIGHT_DIR: ${{ runner.temp }}/pw+ run: |+ # One retry after a pause so a transient blip never pages anyone.+ if node website/scripts/check-live-search.mjs; then exit 0; fi+ echo "::warning::first probe failed; retrying in 90s"+ sleep 90+ node website/scripts/check-live-search.mjs++ - name: Telegram alert+ if: always()+ env:+ GH_TOKEN: ${{ github.token }}+ TOKEN: ${{ secrets.DOCS_ALERT_TELEGRAM_BOT_TOKEN }}+ CHAT_ID: ${{ secrets.DOCS_ALERT_TELEGRAM_CHAT_ID }}+ OUTCOME: ${{ steps.probe.outcome }}+ TEST_ALERT: ${{ inputs.test_alert }}+ REASON: ${{ steps.probe.outputs.reason }}+ RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}+ run: |+ prev=$(gh run list -R "$GITHUB_REPOSITORY" --workflow docs-search-monitor.yml \+ --status completed --limit 10 --json databaseId,conclusion \+ --jq "[.[] | select(.databaseId != $GITHUB_RUN_ID and (.conclusion == \"success\" or .conclusion == \"failure\"))][0].conclusion // \"success\"")+ hour=$(date -u +%H)+ if [ "$TEST_ALERT" = true ]; then+ text="Test alert from the docs search monitor (probe: $OUTCOME). $RUN_URL"+ elif [ "$OUTCOME" = success ]; then+ [ "$prev" = failure ] || { echo "healthy, nothing to send"; exit 0; }+ text="Docs search is working again. $RUN_URL"+ elif [ "$OUTCOME" = failure ]; then+ if [ "$prev" = failure ] && [ $((10#$hour % 6)) -ne 0 ]; then+ echo "still broken; already alerted (next reminder on a 6-hour mark)"; exit 0+ fi+ text="Docs search is BROKEN on hermes-agent.nousresearch.com/docs+ ${REASON:-probe failed before it could name a reason}+ $RUN_URL"+ else+ echo "probe step was $OUTCOME; not alerting"; exit 0+ fi+ if [ -z "$TOKEN" ] || [ -z "$CHAT_ID" ]; then+ echo "::warning::DOCS_ALERT_TELEGRAM_BOT_TOKEN / DOCS_ALERT_TELEGRAM_CHAT_ID not set on trusted-automation; alert not sent: $text"+ exit 0+ fi+ # A failed send must not turn the job red: the next run reads this+ # run's conclusion to decide between "broken" and "working again".+ if curl -fsS --retry 3 -o /dev/null "https://api.telegram.org/bot${TOKEN}/sendMessage" \+ --data-urlencode "chat_id=${CHAT_ID}" --data-urlencode "text=${text}" \+ --data-urlencode "disable_web_page_preview=true"; then+ echo "alert sent"+ else+ echo "::error::Telegram sendMessage failed; check the bot token / chat id"+ fidiff --git a/website/scripts/check-live-search.mjs b/website/scripts/check-live-search.mjsnew file mode 100644index 00000000000..46d1002930b--- /dev/null+++ b/website/scripts/check-live-search.mjs@@ -0,0 +1,160 @@+#!/usr/bin/env node+// Probe search on the LIVE docs site the way a visitor uses it.+//+// Search broke in production twice with a green build: once when the Algolia+// search key was deleted, once when Vercel access controls got in the way.+// Neither shows up in CI because CI never talks to the deployed site, so this+// script does: it reads the Algolia credentials out of the bundle the site is+// actually serving, queries Algolia with the site's Origin, opens the top+// hits, and then drives the real search modal in a headless browser.+//+// Usage: node website/scripts/check-live-search.mjs [--no-browser]+// DOCS_URL site to probe (default https://hermes-agent.nousresearch.com/docs)+// PLAYWRIGHT_DIR directory holding node_modules/playwright (browser check)+// Exit 0 = search works; exit 1 = broken, reasons on stderr and in+// $GITHUB_STEP_SUMMARY / $GITHUB_OUTPUT (`reason=`) when run in Actions.++import { appendFileSync } from 'node:fs';+import { createRequire } from 'node:module';+import path from 'node:path';++const DOCS_URL = (process.env.DOCS_URL || 'https://hermes-agent.nousresearch.com/docs').replace(/\/$/, '');+const ORIGIN = new URL(DOCS_URL).origin;+// Terms that must always match many pages; one per major area of the docs.+const QUERIES = ['telegram', 'install', 'skills'];+const MIN_HITS = 5;+const UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36 hermes-docs-search-monitor';++const failures = [];+const fail = (msg) => {+ failures.push(msg);+ console.error(`FAIL ${msg}`);+};+const ok = (msg) => console.log(`ok ${msg}`);++async function get(url, headers = {}) {+ const res = await fetch(url, { headers: { 'user-agent': UA, ...headers }, redirect: 'follow' });+ return { res, body: await res.text() };+}++// Vercel's firewall/challenge and password protection answer 403/401/429+// with an HTML page of their own; name that instead of "bad status".+function blockedBy(res) {+ if (res.headers.get('x-vercel-mitigated')) return `Vercel firewall (${res.headers.get('x-vercel-mitigated')})`;+ if (res.status === 401) return 'auth wall (401)';+ if (res.status === 403 || res.status === 429) return `HTTP ${res.status}`;+ return null;+}++async function readDeployedConfig() {+ const { res, body } = await get(`${DOCS_URL}/`);+ const block = blockedBy(res);+ if (block || !res.ok) {+ fail(`docs page ${DOCS_URL}/ is not reachable for visitors: ${block || `HTTP ${res.status}`}`);+ return null;+ }+ const bundle = body.match(/src="([^"]*\/main\.[0-9a-f]+\.js)"/)?.[1];+ if (!bundle) {+ fail('docs page has no main.<hash>.js bundle; cannot read the deployed search config');+ return null;+ }+ const js = (await get(new URL(bundle, ORIGIN).href)).body;+ const algolia = js.match(/algolia:\{appId:"([^"]+)",apiKey:"([^"]+)",indexName:"([^"]+)"/);+ if (!algolia) {+ fail(`deployed bundle ${bundle} has no Algolia config; search is not configured on the live site`);+ return null;+ }+ const [, appId, apiKey, indexName] = algolia;+ ok(`deployed config: app ${appId}, index "${indexName}" (from ${bundle})`);+ return { appId, apiKey, indexName };+}++async function checkAlgolia({ appId, apiKey, indexName }) {+ const res = await fetch(`https://${appId}-dsn.algolia.net/1/indexes/*/queries`, {+ method: 'POST',+ headers: {+ 'x-algolia-application-id': appId,+ 'x-algolia-api-key': apiKey,+ origin: ORIGIN,+ referer: `${DOCS_URL}/`,+ 'content-type': 'application/json',+ },+ body: JSON.stringify({+ requests: QUERIES.map((query) => ({ indexName, query, hitsPerPage: 3, attributesToRetrieve: ['url'] })),+ }),+ });+ const body = await res.text();+ if (!res.ok) {+ // 403 "Invalid Application-ID or API key" is the deleted-key outage.+ fail(`Algolia rejected the deployed search key: HTTP ${res.status} ${body.slice(0, 200)}`);+ return [];+ }+ const urls = [];+ for (const [i, result] of JSON.parse(body).results.entries()) {+ const hosts = result.hits.map((h) => new URL(h.url).origin);+ if (result.nbHits < MIN_HITS) fail(`query "${QUERIES[i]}" returned ${result.nbHits} hits (< ${MIN_HITS}); index looks empty`);+ else if (!hosts.every((h) => h === ORIGIN)) fail(`query "${QUERIES[i]}" hits point off-site: ${hosts.join(', ')}`);+ else ok(`query "${QUERIES[i]}": ${result.nbHits} hits`);+ if (result.hits[0]) urls.push(result.hits[0].url);+ }+ return urls;+}++async function checkHitPagesOpen(urls) {+ for (const url of urls) {+ const { res } = await get(url);+ const block = blockedBy(res);+ if (block || !res.ok) fail(`search result ${url} does not open: ${block || `HTTP ${res.status}`}`);+ else ok(`result opens: ${url}`);+ }+}++async function checkBrowser() {+ const require = createRequire(path.join(process.env.PLAYWRIGHT_DIR || process.cwd(), 'noop.js'));+ const { chromium } = require('playwright');+ const browser = await chromium.launch();+ try {+ const page = await browser.newPage({ userAgent: UA });+ const algoliaErrors = [];+ page.on('response', (r) => {+ if (r.url().includes('algolia') && r.status() >= 400) algoliaErrors.push(`${r.status()} ${r.url().split('?')[0]}`);+ });+ page.on('requestfailed', (r) => {+ if (r.url().includes('algolia')) algoliaErrors.push(`${r.failure()?.errorText} ${r.url().split('?')[0]}`);+ });+ await page.goto(`${DOCS_URL}/`, { waitUntil: 'domcontentloaded', timeout: 30_000 });+ await page.locator('.DocSearch-Button').first().click({ timeout: 20_000 });+ await page.locator('.DocSearch-Input').fill(QUERIES[0], { timeout: 10_000 });+ try {+ await page.locator('.DocSearch-Hit').first().waitFor({ timeout: 15_000 });+ } catch {+ const shown = (await page.locator('.DocSearch-Modal').innerText().catch(() => '')).replace(/\s+/g, ' ').slice(0, 200);+ fail(`search modal showed no results for "${QUERIES[0]}" (${algoliaErrors.join('; ') || 'no Algolia error seen'}; modal: "${shown}")`);+ return;+ }+ ok(`browser: search modal lists ${await page.locator('.DocSearch-Hit').count()} results for "${QUERIES[0]}"`);+ } finally {+ await browser.close();+ }+}++async function main() {+ const config = await readDeployedConfig();+ if (config) await checkHitPagesOpen(await checkAlgolia(config));+ if (!process.argv.includes('--no-browser')) {+ await checkBrowser().catch((e) => fail(`browser check crashed: ${e.message.split('\n')[0]}`));+ }+ if (process.env.GITHUB_STEP_SUMMARY) {+ const lines = failures.length ? failures.map((f) => `- ${f}`) : ['- all checks passed'];+ appendFileSync(process.env.GITHUB_STEP_SUMMARY, `### Docs search (${DOCS_URL})\n${lines.join('\n')}\n`);+ }+ if (process.env.GITHUB_OUTPUT && failures.length) {+ appendFileSync(process.env.GITHUB_OUTPUT, `reason=${failures[0].replace(/\n/g, ' ').slice(0, 300)}\n`);+ }+ process.exit(failures.length ? 1 : 0);+}++main().catch((e) => {+ fail(`probe crashed: ${e.message}`);+ process.exit(1);+});