# Codex Handoff: Weiyuan Observability ## Purpose This workspace is for implementing a three-layer observability and alerting platform for the `monkey-ai` system and its white-label branches. The intended end state correlates Metrics, Logs, and Traces across hosts, services, brands, upstream vendors, and individual requests. The user wants the work performed incrementally. On 2026-10-15 the user changed the immediate task to starting Docker Desktop locally, running smoke tests, and monitoring the already-running local new-api application first. Test-server deployment follows local validation; production and application repository changes remain separately scoped. ## Production Deployment Request (2026-10-15) - User explicitly authorized deploying the current monitoring project to SSH alias `server134-rot`, directory `/opt/observability/`, and committing/pushing this workspace to `https://git.weytoken.com/qiubs/observability.git`. - This authorization supersedes the historical test-server-only scope for this target. It does not authorize unrelated application/DB/firewall/nginx changes or public exposure. - Remote Git had no refs when checked. Initialized local main using the existing identity from the adjacent monkey-ai checkout and pushed to origin/main. Initial import f657abe; offline-plugin support 6fe8511. Read /opt/observability/DEPLOYED_COMMIT for the final deployed revision including documentation. - User corrected SSH configuration: `root@134.175.227.134:22`. Connection and read-only checks succeeded: Ubuntu 22.04.5, x86_64, 2 CPUs, 7.6 GiB RAM (5.7 GiB available), 49 GiB disk available, Docker 29.1.3, Compose 2.40.3, synchronized time. - `/opt/observability/` contains older project files, but no running monitoring containers or monitoring data/. Preserve these with a backup before upload. Existing application listeners use 3000 and 3001; do not restart them. - Keep all monitoring ports on loopback. Set GRAFANA_PORT=3002; suggested workstation tunnel ports: 13000 -> remote 3002, 19093 -> remote 9093. - Server-specific config: VMAGENT_CONFIG=./config/vmagent/prometheus.server134.yml, VM_RETENTION=30d, VL_RETENTION=7d. Tempo remains 30d; no real trace ingestion is configured. Expand disk capacity before broad log/trace ingestion. - Server `prepare.sh` now restricts `.env` to mode 0600 and does not print the generated Grafana password. - Production app/MySQL targets have not been supplied; do not upload local credentials or use the Windows host.docker.internal target on Linux. - The user subsequently supplied a screenshot showing local mysql_up=1. This updates the older credentials-absent snapshot below, but is not a new independently executed full MySQL smoke check. - Production deployment completed on 2026-10-15. Eight containers running, all ten published ports loopback; all eight scrape targets healthy with production labels; four vmalert rules evaluate without errors; Alertmanager has zero active alerts. - Remote smoke exited 0: fresh Metrics, Logs and exact Trace readback, three authenticated Grafana datasource health checks, and monitor-host-overview dashboard all passed. Synthetic run=f2b2983492f83f83, trace=c4c50887907cda3c5721ead9ebd63f01. - Existing monkey-ai processes on 3000/3001 retained their PIDs and both /api/status endpoints returned HTTP 200 with success=true. Production application monitoring has not yet been configured. - Old directory backup: /opt/observability-backups/before-f657abe.tar.gz (verified archive, mode 0600). Deployment release archives are extracted under /opt/observability-releases/. - Server registry mirrors failed image size validation. Imported exact pinned Linux amd64 images from workstation after SHA256 checks. Do not change/restart Docker daemon to work around this. Start cached images with port preflight then docker compose up -d --pull never. - Log datasource plugin 0.32.0 was imported, signature verification retained, Linux backend executable mode restored to 0755 after Windows transfer. Server .env sets GRAFANA_PREINSTALL_PLUGINS= to avoid repeated downloads; do not set this on a clean host without preinstalling the plugin. - Post-deployment snapshot: about 5.2 GiB RAM available and 45 GiB disk available; no OOM kills or restart loops. This is initial idle usage, not load-test capacity evidence. - A fresh Windows local smoke during deployment passed synthetic Metrics/Logs/Traces but failed the new-api probe (probe_success=0). Local scrape up stayed 1, including local-mysql. Do not claim the current local full smoke or MySQL-specific checks passed; no local app was changed. This failure is separate from the successful remote smoke. ## Local Validation History (2026-10-15) This section supersedes the older test-server-first workspace snapshot below. - User confirmed that "newpai" means new-api / monkey-ai application layer and supplied `http://127.0.0.1:3000`, already running. - The process on port 3000 is `D:\project\safe_change\tmp\new-api-toolargs-full.exe`; do not assume it is the old `monkey-ai-weiyuan-inspection` checkout. Its `/api/status` returned HTTP 200 and `success: true`. No application source or process was changed. - Docker Desktop Linux engine was started. Docker Engine is 29.5.2, Compose is v5.1.4; the Docker VM reports 16 CPUs and about 8 GB RAM. - Local instructions: `deploy/monitoring/README.local.md`. Run `py -3 deploy/monitoring/scripts/local.py {check,up,smoke,ps,logs,down}` from the workspace root. - Local Compose merges `docker-compose.yml` and `docker-compose.local.yml`; project/network are `observability-local`. Named volumes persist storage. `node-exporter` is excluded because it would observe the Docker VM, not Windows. - Grafana uses `http://127.0.0.1:3001/d/new-api-local`; the application keeps port 3000. Alertmanager is `http://127.0.0.1:9093`. Every monitoring published port binds loopback. - Local password is outside the workspace at `%LOCALAPPDATA%\weiyuan-observability\grafana-admin-password.txt` (admin user), with a user-only Windows ACL and Compose secret mount. Never copy its contents into this workspace or chat. Local deployment does not create `.env`. - The launcher reads effective Compose JSON for port preflight rather than duplicating a list. It checks Docker mappings and actual TCP binds, permits the corresponding project's existing service, and fails before pull/up on conflicts. Six Python port tests plus four existing Bash port tests passed. - Blackbox exporter v0.27.0 probes `http://host.docker.internal:3000/api/status` every 15 seconds, requiring HTTP 200 and `success: true`. Local rules alert on probe failure or scrape failure after two minutes. Alertmanager still has no external notification destination. - Current application monitoring is ONLY status endpoint availability, HTTP status and probe duration. Business success rate, application logs, business traces, traffic baselines and cross-navigation are not implemented by this probe. Preserve `service/monitor` semantics when adding them later. - Runtime testing exposed invalid Tempo 2.x configuration for the pinned Tempo 3.0.3 image. The shared config now uses `overrides.defaults.compaction.block_retention: 720h`; old `ingester` and `compactor` fields were removed. Tempo config verification and exact trace readback passed. - `scripts/smoke.py` writes fresh unique synthetic metrics/logs/traces and polls exact readback. It avoids the previous seconds-as-milliseconds metric timestamp and stale-data false passes. `smoke-test.sh` delegates to it; telemetrygen is no longer required by the smoke test. - Grafana now synchronously installs the pinned VictoriaLogs plugin and disables preinstall auto-updates. First startup downloads about 78 MB; local smoke waits up to 10 minutes for Grafana, then authenticates and verifies all three datasources and the application dashboard. - Copying this workspace to another computer does NOT transfer local Docker named-volume data or the external password. New local startup creates fresh storage and credentials. Final local validation on 2026-10-15: - Eight local monitoring containers running, all published ports loopback. Nine configured scrape targets healthy (eight components plus the application probe). - `py -3 deploy/monitoring/scripts/local.py smoke` exited 0 and printed `Local stack, application probe and Grafana checks all passed.` - Successful synthetic run: `8b7f2181b7f5a99f`; trace: `9a2b6e754911e70dfd4163e4cf108475`. These are synthetic identifiers, not business request data. - Metrics, Logs, exact OTLP HTTP trace readback, application HTTP 200/probe_success=1, all scrapes, all three authenticated Grafana datasource health checks and the new-api dashboard passed. - Direct blackbox positive and negative checks passed: real application => success=1; isolated unreachable test address => success=0. The user's application was never stopped. - Six Python port checks, four Bash port checks, each shell file's syntax, Python compilation, base/merged Compose parsing and YAML/JSON formatting passed. - Initial failures were Tempo's obsolete config keys and the Grafana plugin's slow first download. The fixed plugin installed successfully (roughly 8 minutes on this network). Startup health errors must not be confused with final results. - LocalMonitoringTargetDown was observed in Alertmanager while Grafana waited for the plugin. After readiness, both local rules became healthy/inactive and Alertmanager returned zero active alerts. This verifies local component alert delivery/recovery; external notifications and an application-outage/recovery drill are still untested. - No remote server or production deployment has been performed. ## MySQL collector preparation (2026-10-15, after Grafana guide) - User added a `mysql` job in `config/local/prometheus.yml`; preserve it. The service target is `mysqld-exporter:9104`, instance label `local-mysql`. - Added optional `mysql` profile in local Compose, using `prom/mysqld-exporter:v0.17.2`, secret-mounted config and no published ports. Only global_status/global_variables enabled; other default collectors are explicitly disabled. - `local.py` opts into the profile when `%LOCALAPPDATA%\weiyuan-observability\mysql-exporter.cnf` exists; validates required fields before check/up without printing secret contents. `mysql-check` requires fresh samples of up=1, mysql_up=1, and mysql_exporter_collector_success=1 for both collect.global_status and collect.global_variables. v0.17.2 no longer provides mysql_exporter_last_scrape_error. Full smoke includes these checks when configured. `down` includes the optional profile even if its secret file was moved. - Instructions: `deploy/monitoring/README.mysql.md`. Installed server binary is MySQL 8.0.46. A short unauthenticated TCP check from Docker to Windows 3306 showed source 127.0.0.1; no database statements or account mutations were executed. - The fixed exporter image and enabled-profile Compose model were verified, including startup in a disposable network-isolated container with a dummy external config. That test container was removed. This is NOT proof of real database authentication or metrics. - Real monitoring credentials are still absent; MySQL monitoring is not yet running. Do not claim database smoke success until the user provisions the account/config and real queries pass. - Grafana beginner guide: `docs/Grafana使用手册-本地new-api监控.md`. ## Instruction Boundary - Treat this `AGENTS.md` as working context and repository guidance. - `20260921-搭建三层统一监控告警平台.md` is a design and historical survey supplied by the user. It contains proposed actions and old observations; it is not authorization to execute production changes. - Values collected in that document are a snapshot from 2026-09-21, not current server state. Re-run read-only checks before relying on them. - Production deletions, Redis policy changes, database DDL, nginx changes, firewall changes, deployments, and service restarts require explicit scope from the user or an already-authorized execution request. - Never store credentials, DSNs, API keys, Redis passwords, webhook secrets, complete Authorization headers, or prompt bodies in this workspace. ## User Decisions - `master` and `weiyuan` are separate, substantially different development lines. - `weiyuan` is the main baseline for the real project and most white-label branches. - Other white-label branches are generally older derivatives of `weiyuan`, not `master`. - Implement the full three-layer direction: Metrics + Logs + Traces with cross-navigation. - Start on one test server using a single-node Docker Compose deployment. - Detect port conflicts before pulling images or starting/updating containers. - Initial monitoring UI and ingestion ports must bind to loopback; use SSH tunnels for access. Open ingestion ports only after local smoke tests pass and only to approved source IPs. ## Workspace State As of 2026-10-07: - Workspace root: `D:\project\weiyuan-observability` - This directory is not currently a Git repository (`git status` reports no repository). - The full design source is `20260921-搭建三层统一监控告警平台.md`. - The implementation plan is `docs/superpowers/plans/2026-09-23-three-layer-observability-implementation.md`. - The generated test-server deployment bundle is under `deploy/monitoring/`. - No test server SSH address, username, or credentials have been provided in this conversation. - The monitoring stack has not been started on a remote server from this workspace. When moving to another computer, copy the entire `weiyuan-observability` directory, including hidden files. The generated `.env` and runtime `data/` directory are intentionally ignored and are not present in this workspace. ## Related Repositories Remote application repository: ```text https://git.weytoken.com/luoguang/monkey-ai.git ``` Inspection checkouts used on the original computer: ```text D:\project\monkey-ai-inspection master D:\project\monkey-ai-weiyuan-inspection weiyuan D:\project\monkey-ai developer working checkout ``` The developer working checkout had unrelated user changes when inspected on 2026-09-23 (`web/bun.lock` modified and two DOCX files untracked). Do not discard or overwrite unrelated changes. Remote heads last verified on 2026-09-23: ```text weiyuan 1eeb66a72e7ada77c9692643f847134163982cac master d149c427d9fa76396200c447f5201fed9c1b53e1 sma fb39862511da8900def58847b5a796ad2582bd1f ltop e90b4f7558cb0464b378694a79b750d3f4778008 hivetoken 01265293216c0df74d23204a7fffc9d4b81db1ee aibiyi 7c784a7bcd78f7e99fbe316e94339135206975e0 paixtoken 2264d8d9ab4eef7d8bcf95a7435c920e9ccb8e68 tv 5b6052c45167c1765363406d541c8fb8f4c12679 youlangg a3976e457f513bdc3577df82bd6ffcd50f672d88 ``` These SHA values are historical reference points. Run `git ls-remote --heads` or `git fetch` before new branch work. Branch history findings: - `master` and `weiyuan` diverged after common commit `73ed70f2` from 2026-06-14. At the time of inspection they had 21 and 581 unique commits respectively. - `sma` was an old `weiyuan` snapshot from 2026-09-14. - `hivetoken`, `aibiyi`, `paixtoken`, `tv`, `youlangg`, and `vest-baseline` shared a 2026-08-25 `weiyuan` base. - `ltop` diverged earlier around 2026-07-23. - The quality monitoring feature entered `weiyuan` in commit `24710573` on 2026-09-16. None of the listed white-label heads contained its core files when inspected. - `马甲包分支指南.md` inside the application repository says all white-label branches use `master` and references an old remote. That guide is stale for this project and must not override the user's branch decision above. ## Existing `weiyuan` Monitoring Capability `weiyuan` already contains an application-level call-quality subsystem. Do not redesign its outcome model. Relevant files: ```text model/monitor_quality.go service/monitor/ middleware/monitor_outcome.go controller/monitor_quality_record.go controller/analytics_quality.go web/src/components/quality/ web/src/pages/Analytics/index.jsx web/src/pages/Organization/OrgQuality.jsx main.go ``` Implemented behavior: - Six outcomes: direct success, fallback success, fallback exhausted, failure without fallback, client abort, content block. - Five fault sides and model/channel/group/organization/error/path dimensions. - In-memory collection with a 15-second database flush. - Async task terminal-state scanning. - Platform and organization quality dashboards and detail queries. - Alert rules with minimum samples, silence periods, and duplicate-event protection. - Five-minute, hourly, and daily retention of 7 days, 400 days, and 5 years. - Graceful shutdown flush. Current application alert limitations: - Metrics: success rate, fallback failure count, upstream fault percentage, P95 only. - Scopes: global, model, channel, organization only. - Alerts notify the root user through existing email/webhook/Bark/Gotify settings. - No P1/P2/P3 workflow, acknowledgement, escalation, recovery state, or Alertmanager integration. Confirmed gaps: - Host, PM2/process, Redis, MySQL, nginx, and network observability. - VictoriaMetrics/VictoriaLogs/Tempo/Grafana deployment. - W3C `traceparent` across nginx -> monkey-ai -> CPA -> CRS -> tls. - Brand traffic-baseline/no-traffic alerting and most of the 18 planned rules. - Automatic `logs` retention. The code still only has an administrator-triggered `DeleteOldLog`; do not enable expanded error logging globally until automatic retention is implemented and tested. - MySQL and PostgreSQL real-database smoke tests for the quality subsystem remain outstanding. The following test command passed in the clean `weiyuan` inspection checkout on 2026-09-23: ```bash go test ./service/monitor ./controller ./router ./model ``` Re-run it against the current remote state before making new claims. ## Generated Test-Server Deployment Entry point: ```text deploy/monitoring/README.md ``` The Compose deployment includes: - VictoriaMetrics `v1.152.0` - VictoriaLogs `v1.52.0` - Grafana `13.2.2` - Tempo `3.0.3` - Alertmanager `v0.34.1` - node_exporter `v1.12.1` - vmagent and vmalert matching VictoriaMetrics `v1.152.0` - telemetrygen `v0.161.0` for trace smoke testing - VictoriaLogs Grafana datasource plugin `0.32.0` Default bind policy in `.env.example`: ```text UI_BIND_IP=127.0.0.1 INGEST_BIND_IP=127.0.0.1 DEBUG_BIND_IP=127.0.0.1 ``` Published ports: ```text 3000 Grafana 9093 Alertmanager 8428 VictoriaMetrics 9428 VictoriaLogs 4317 OTLP gRPC 4318 OTLP HTTP 3200 Tempo debug/query 8880 vmalert 9100 node_exporter 8429 vmagent ``` `scripts/prepare.sh` performs these operations in order: 1. Creates `.env` from `.env.example` if absent. 2. Generates a random Grafana password if the placeholder is still present. 3. Creates persistent data directories and sets container ownership. 4. Validates Compose configuration. 5. Runs `scripts/check-ports.sh`. 6. Pulls images only after port preflight succeeds. 7. Starts containers and prints status. Port-preflight behavior: - Uses a real TCP bind attempt on the configured IP and port. - Checks Docker published ports as well as ordinary listeners. - Rejects ports used by unrelated processes or containers. - Allows a port already owned by the matching service in this Compose project, so upgrades remain idempotent. - Prints `ss` and `docker ps` diagnostics and exits before changing containers on conflict. Do not change only `docker-compose.yml` when changing a host port. Update all three together: ```text deploy/monitoring/docker-compose.yml deploy/monitoring/scripts/check-ports.sh deploy/monitoring/scripts/smoke-test.sh ``` ## Validation Already Performed The following checks passed locally after the port-preflight change: ```text Port tests: unused port accepted externally occupied port rejected current Compose service port accepted port published by another Docker container rejected Bash syntax: install-docker-ubuntu.sh prepare.sh check-ports.sh smoke-test.sh check-ports-test.sh Docker Compose: docker compose ... config --quiet passed Configuration formatting: all YAML/JSON files passed Prettier check ``` During the historical September verification the local Docker daemon was unavailable, so those checks did not start containers. See the October local-work section above for current runtime results. Remote runtime validation is still required. Useful verification commands from the workspace root: ```powershell & 'C:\Program Files\Git\bin\bash.exe' deploy/monitoring/tests/check-ports-test.sh Get-ChildItem deploy/monitoring/scripts/*.sh,deploy/monitoring/tests/*.sh | ForEach-Object { & 'C:\Program Files\Git\bin\bash.exe' -n $_.FullName; if ($LASTEXITCODE -ne 0) { throw "Bash syntax check failed: $($_.Name)" } } docker compose --env-file deploy/monitoring/.env.example -f deploy/monitoring/docker-compose.yml config --quiet npx --yes prettier@3.6.2 --check "deploy/monitoring/**/*.{yml,yaml,json}" ``` ## Next Actions on the Other Computer 1. Read this file, `deploy/monitoring/README.md`, and the implementation plan. 2. Confirm the test server OS, CPU/RAM/disk, architecture, SSH address, username, sudo access, Docker registry access, time synchronization, and intended data-disk mount. 3. Run read-only server checks before upload: ```bash cat /etc/os-release uname -m nproc free -h df -h timedatectl status sudo ss -lntp docker version || true docker compose version || true ``` 4. Upload `deploy/monitoring/` and follow its README. 5. Run `sudo bash scripts/check-ports.sh` before deployment and resolve conflicts without terminating unknown services. 6. Run `sudo bash scripts/prepare.sh` and save the generated Grafana password outside the repository. 7. Run `sudo bash scripts/smoke-test.sh`. Do not state that deployment succeeded unless Metrics, Logs, and Traces smoke checks all pass. 8. Use an SSH tunnel for Grafana and Alertmanager. Keep UI/debug ports on loopback. 9. After local validation, set `INGEST_BIND_IP` to the test server's private IP and restrict 8428/9428/4317/4318 with cloud security groups or the Docker `DOCKER-USER` chain. Docker-published ports may bypass ordinary UFW INPUT rules. 10. Configure real notification receivers only after the user supplies the approved destination. Never commit webhook secrets. ## Deployment Commands From a Windows workstation, replacing the SSH target: ```powershell scp -r D:\project\weiyuan-observability\deploy\monitoring ops@MONITOR_SERVER:/tmp/ ssh ops@MONITOR_SERVER ``` On the Ubuntu test server: ```bash sudo mkdir -p /opt/observability sudo cp -a /tmp/monitoring/. /opt/observability/ cd /opt/observability sudo bash scripts/install-docker-ubuntu.sh sudo bash scripts/check-ports.sh sudo bash scripts/prepare.sh sudo bash scripts/smoke-test.sh ``` SSH tunnel from Windows: ```powershell ssh -N -L 3000:127.0.0.1:3000 -L 9093:127.0.0.1:9093 ops@MONITOR_SERVER ``` Rollback stops only the monitoring stack and preserves data: ```bash cd /opt/observability sudo docker compose down ``` Never run `docker compose down -v` and never delete `/opt/observability/data` unless the user explicitly requests data destruction and a backup has been verified. ## Broader Implementation Order After the central test stack is proven: 1. Re-collect the five-host baseline read-only. 2. Address urgent disk/dump/log-rotation risks under explicit production scope. 3. Add node_exporter/vmagent/Vector and Redis/MySQL/blackbox exporters. 4. Enable structured nginx access logs and ingest them into VictoriaLogs. 5. Export/reconcile `weiyuan` business quality metrics without changing outcome semantics. 6. Complete the 18 alert rules and notification lifecycle. 7. Add CRS/vendor/egress monitoring. 8. Add Traces last, gated by `OTEL_ENABLED=false`, with canary order ltop -> sma -> small brands -> weelinking. 9. Merge current `weiyuan` into each white-label branch separately, preserving brand assets, domains, ports, and deployment templates. ## Safety and Quality Rules - Read the current files before editing; this workspace may be copied with additional user changes. - Prefer reversible actions and explicit rollback steps. - Never use `latest` image tags. - Never expose Grafana, Alertmanager, component debug ports, or unauthenticated ingestion endpoints to the public internet. - Keep `org_id`, token IDs, user IDs, request bodies, and similarly high-cardinality or sensitive values out of Metrics labels. - Reuse `service/faultclass` and `service/monitor` outcome/fault enums; do not create a second success-rate definition. - Keep `MONITOR_QUALITY_ENABLED=false` and `OTEL_ENABLED=false` as independent rollback switches. - Before claiming completion, run the relevant tests and runtime smoke checks and report exact failures if any.