22 KiB
AGENTS.md — GCoordinator Engineering & Continuation Guide
Operational & architectural guide for AI coding agents (Neon and compatible coding agents) continuing maintenance and feature development in
/home/devuser/workspace/GCoordinator.
1. Purpose & Relationship to How/Plan.md
GCoordinator is a self-hosted, single-admin, security-first central SSH control plane built around:
- Multiplexed SSH access (
ssh2) with multi-hopProxyJumpforwarding, persistent server-side PTY (xterm.js+@xterm/addon-fit), streaming SFTP file management with pre-save unified diffs, and authenticated/proxy/:tunnelId/*HTTP/WS + local/remote TCP port forwarding. - Centralized
AES-256-GCMcredential storage (vault.enc), Ed25519 key lifecycle + zero-lockout atomic key rotation, Argon2id + multi-factor TOTP + optional WebAuthn Passkeys, configurable re-auth strictness, Safe Mode, and Emergency Panic Lock. - Agentless Linux/BSD/macOS metric polling, multi-mount disk tracking, on-demand Server Inspector, HTTP/TCP probes, declarative
systems/*.jsondiscovery/status/actions, Full-DAGworkflows/*.json, fleet broadcast, cross-server transfers, webhook alerting, portable.gcoord.encbackups, and an opt-in BYO-API OpenAI-compatible AI assistant.
All 5 phases of Plan.md plus post-Phase-2 and post-Phase-3 enhancements are implemented and verified (18/18 Vitest suites, 35/35 tests passing).
Precedence rule: How/Plan.md is the original Phase 1–5 design blueprint (its directory-tree diagram still references root Plan.md, which now lives at How/Plan.md). Several core behaviors evolved during implementation—including write-only Vault locking vs. always-on runtime secrets, multi-password/multi-TOTP & configurable strictness, WebAuthn Passkeys, the data/recovery/ emergency backup store, 8 UI/terminal themes, a strict < 20 KB lazy-chunk budget, and xterm.js mobile IME composition fixes. Wherever How/AGENTS.md differs from How/Plan.md, How/AGENTS.md reflects the live codebase and takes precedence.
2. Environment, Build, Run & Test Commands
Runtime Toolchain
- Node.js 22+ LTS: In this dev container,
node,npm, andnpxlive in~/.local/bin. Always prepend PATH in non-login shells:export PATH="$HOME/.local/bin:$PATH" - Containers:
dockerCLI is not installed in this dev container;docker/Dockerfile,docker/docker-compose.yml, anddocker/docker-compose.lan.ymlare deployment definitions.
NPM Scripts (package.json)
npm run typecheck—tsc --noEmit(strict TypeScript withnoUncheckedIndexedAccess: trueandnoImplicitOverride: true).npm run build:client—tsx src/client/build.ts(bundles ES2020 client modules + CSS intodist/public/and enforces gzip budgets).npm run build:server—esbuildbundlesdist/server/index.jsanddist/cli/gcoord.js(--platform=node --target=node22 --format=esm --packages=external).npm run build— runstypecheck && build:client && build:server.npm test—vitest run(runs all 18 unit/E2E suites in ~5s using in-process HTTP servers andMockSshServer).npx vitest run tests/<file>.test.ts— run a targeted Vitest file.npm run dev—tsx watch src/server/index.ts.npm start—node dist/server/index.js(requiresnpm run buildfirst sodist/public/anddist/server/exist).
CLI (src/cli/gcoord.ts -> dist/cli/gcoord.js)
node dist/cli/gcoord.js rotate-key [--data-dir <dir>] [--current-key-file <path>] [--new-key-out <path>]
node dist/cli/gcoord.js backup --out <path.gcoord.enc> [--data-dir <dir>] [--key-file <path>] [--passphrase-file <path>]
node dist/cli/gcoord.js verify-backup <path.gcoord.enc> [--bundle <path>] [--key-file <path>] [--passphrase-file <path>] [--vault-key-file <path>] [--json]
node dist/cli/gcoord.js restore <path.gcoord.enc> [--bundle <path>] [--data-dir <dir>] [--key-file <path>] [--passphrase-file <path>] [--vault-key-file <path>]
Server Environment Variables (src/server/index.ts)
GCOORD_DATA_DIR— persistent state directory (default:./data).PORT— HTTP/WS listen port (default:3000).HOST— bind address (default:0.0.0.0).GCOORD_MASTER_KEY— 32-byte Vault master key (hex or base64).GCOORD_MASTER_KEY_FILE— master key file path (default:/run/secrets/gcoord_master_key).GCOORD_BACKUP_PASSPHRASE— optional passphrase for.gcoord.encCLI operations.TRUST_CLOUDFLARE— set'true'to enableapp.set('trust proxy', 1)and honorCF-Connecting-IPin rate limiting.
3. Repository Map
GCoordinator/
├── How/
│ ├── AGENTS.md # This guide (authoritative for live codebase conventions)
│ └── Plan.md # Original Phase 1–5 architecture blueprint
├── docker/
│ ├── Dockerfile
│ ├── docker-compose.yml
│ └── docker-compose.lan.yml
├── src/
│ ├── cli/
│ │ └── gcoord.ts # rotate-key, backup, verify-backup, restore CLI
│ ├── shared/
│ │ ├── diff.ts # Pure TS unified LCS line diff utility
│ │ ├── ws-protocol.ts # Multiplexed /ws frame schemas & WS_CHANNELS helpers
│ │ └── schemas/ # Shared Zod schemas & TypeScript types
│ │ ├── index.ts
│ │ ├── common.ts
│ │ ├── server.schema.ts
│ │ ├── system.schema.ts
│ │ ├── workflow.schema.ts
│ │ ├── snippets.schema.ts
│ │ ├── alerts.schema.ts
│ │ ├── settings.schema.ts
│ │ └── vault.schema.ts
│ ├── server/
│ │ ├── index.ts # Process bootstrap & SIGINT/SIGTERM graceful shutdown
│ │ ├── app.ts # createGCoordinatorServer() wiring, middleware order, Panic Lock
│ │ ├── db/
│ │ │ ├── database.ts # SQLite WAL connection & ordered migration runner
│ │ │ └── migrations/ # 001_initial.ts, 002_multi_auth.ts, 003_phase4_meta.ts
│ │ ├── security/
│ │ │ ├── vault.ts # VaultService (AES-256-GCM, runtime-ready vs write-locked, Ed25519)
│ │ │ ├── auth.ts # AuthService (Argon2id, multi-password, multi-TOTP, recovery codes, WebAuthn)
│ │ │ ├── guards.ts # RateLimiter, attachClientIp, CSRF, Safe Mode, createStepUpGuard
│ │ │ ├── audit.ts # Append-only AuditService
│ │ │ ├── recovery-store.ts # EmergencyRecoveryService (data/recovery/emergency-secrets.json)
│ │ │ └── backup.ts # Portable AES-256-GCM .gcoord.enc (GCOORD_BACKUP_V1) export/verify/restore
│ │ ├── config/
│ │ │ ├── config-manager.ts # ConfigManager (atomic writes, chokidar hot-reload, revisions)
│ │ │ ├── presets.ts # Default docker-compose, systemd, os-packages seeds
│ │ │ └── diff.ts
│ │ ├── ssh/
│ │ │ ├── ssh-pool.ts # SSHPool (coalesced connections, ProxyJump, execStream, openShell, openSftp)
│ │ │ ├── known-hosts.ts # KnownHostsService (strict TOFU, MITM guard, replaceAllKnownHosts)
│ │ │ ├── key-manager.ts # KeyManager (authorized_keys deploy/revoke, zero-lockout rotation)
│ │ │ ├── sudo.ts # POSIX-quoted sudo wrapper & Buffer zeroization
│ │ │ ├── pty-manager.ts # PTYManager (UTF-8 framing, scrollback ring, export, reaper)
│ │ │ ├── sftp-service.ts # SftpService (stream upload/download, atomic inline edit, tar archives)
│ │ │ └── tunnel-manager.ts # TunnelManager (http-proxy, local-tcp, remote-tcp)
│ │ ├── monitoring/
│ │ │ ├── collectors.ts # OS-aware LinuxCollector, BSDCollector, MacOSCollector
│ │ │ ├── inspector.ts # On-demand ServerInspector (processes, ports, sensors)
│ │ │ ├── probes.ts # ProbeRunner (hub or target forwardOutStream HTTP/TCP probes)
│ │ │ └── monitoring-service.ts # MonitoringService (always-on polling, SQLite rollups, retention)
│ │ ├── systems/
│ │ │ ├── parsers.ts # Output parsers for declarative system discovery/status
│ │ │ └── systems-engine.ts # CustomSystemsEngine (TTL cache, overlays, 3x3 scoped/moded actions)
│ │ ├── automation/
│ │ │ ├── template.ts # Safe env-var & POSIX single-quoted interpolation + target filtering
│ │ │ ├── stream-buffer.ts # BufferedStreamEmitter (128 KB circular WS replay ring)
│ │ │ ├── transfer-engine.ts # TransferEngine (hub-relayed SFTP or direct rsync)
│ │ │ ├── workflow-engine.ts # WorkflowEngine (Kahn DAG scheduler, croner, event triggers, dry-run)
│ │ │ └── broadcast-service.ts # BroadcastService (parallel fleet command execution)
│ │ ├── alerts/
│ │ │ └── alert-engine.ts # AlertEngine (metric/disk/offline/probe/system rules, silences, webhooks)
│ │ ├── ai/
│ │ │ ├── redactor.ts # collectVaultSecretStrings & redactSecrets
│ │ │ ├── guides.ts # AiSurfaceSchema & buildSurfaceGuideAndInventory
│ │ │ └── ai-service.ts # AiService (opt-in /v1/chat/completions, WS streaming, Zod draft check)
│ │ └── api/
│ │ ├── ws-hub.ts # Multiplexed WebSocket hub (/ws, origin & ticket/session checks, replay)
│ │ └── routes/ # auth, vault, config, audit, servers, terminal, sftp, tunnels, systems, workflows, snippets, alerts, backup, ai
│ └── client/
│ ├── build.ts # esbuild client/CSS bundler + gzip budget assertions
│ ├── index.html # SPA shell + PWA manifest + dynamic theme-color meta
│ ├── manifest.json
│ ├── icon.svg
│ ├── css/
│ │ ├── themes.css # 8 CSS custom-property terminal themes
│ │ └── base.css # Flat sharp styles, dialog/drawer styles, mobile <768px rules
│ └── ts/
│ ├── main.ts # Router, nav, topbar indicators, Panic Lock, global state sync
│ ├── state.ts # Client store, CLIENT_THEME_IDS, applyTheme, appendBoundedStreamText
│ ├── api.ts # Fetch wrapper (CSRF header + auto Vault unlock prompt on 423 VAULT_LOCKED)
│ ├── ws-client.ts # Reconnecting /ws client
│ ├── dialogs.ts # Native <dialog> modals (multi-factor step-up, confirm, prompts)
│ ├── charts.ts # Flat SVG sparklines & metric charts (viewport-capped points)
│ ├── webauthn.ts # navigator.credentials base64url helper
│ └── views/
│ ├── auth-view.ts # Core static views
│ ├── dashboard-view.ts
│ ├── server-detail-view.ts
│ ├── vault-view.ts
│ ├── config-view.ts
│ ├── settings-view.ts
│ ├── terminal-view.ts # Code-split lazy views (keep dynamically imported!)
│ ├── xterm-runtime.ts
│ ├── sftp-view.ts
│ ├── tunnels-panel.ts
│ ├── systems-view.ts
│ ├── workflows-view.ts
│ ├── alerts-view.ts
│ └── ai-drawer.ts
└── tests/
├── helpers/mock-ssh-server.ts # In-process ssh2.Server fixture (PTY, SFTP, forwardOut, forwardIn, sudo)
└── *.test.ts # 18 Vitest integration & unit suites
4. Critical Architectural Invariants (Must Preserve)
1. Runtime-Ready Secrets vs. Write-Only Vault Lock (vault.ts)
vaultService.isRuntimeReadyis decoupled fromvaultService.state === 'unlocked'.- At server startup (
initRuntimeinsrc/server/app.ts), established secrets are decrypted into memory usingsecretFilePath,GCOORD_MASTER_KEY,data/vault.key(0600), ordata/recovery/emergency-secrets.json, whilestatebegins'locked'(write-locked). - Background and established-secret consumers (
SSHPool,MonitoringService,TunnelManager,CustomSystemsEngine,WorkflowEngine,AlertEngine,AiService,/api/backup/export) must checkisRuntimeReadyand read credentials viagetRuntimeSecret(id)so polling, crons, SFTP, and webhooks work unattended before login and while write-locked. - Only Vault mutations (adding/editing/deleting credentials), Ed25519 key generation, raw secret reveals, master-key rotation, and fleet key rotation require
state === 'unlocked'. When write-locked, these endpoints must fail withHTTP 423 VAULT_LOCKED(whichsrc/client/ts/api.tsintercepts to prompt Vault unlock and retry automatically). - Emergency Panic Lock (
panicLock(), persisted via${vaultFilePath}.panic-locked) is the only state that zeroes runtime secret buffers (isRuntimeReady = false), tears down active SSH/PTY/tunnel/AI sessions, revokes sessions (WS 4001), and refuses silent disk/env auto-unlock across restarts until a user manually unlocks with the master key.
2. Auth, Multi-Factor Strictness, Safe Mode & Passkeys (auth.ts, guards.ts)
- Supports multiple admin passwords (
admin_passwords) and multiple TOTPs (admin_totps) evaluated inanyorallmode, single-use recovery codes, and@simplewebauthn/serverPasskeys (webauthn_credentials; accessing WebAuthn endpoints over raw IP literals returnsWEBAUTHN_RPID_INVALID). SecuritySettingsSchema(src/shared/schemas/settings.schema.ts) configuresrequireTotpOnLogin,stepUpPolicy(off | every-action | 5m | 1h | 24h | session),stepUpMethod(totp | password | both | passkey),elevateOnLogin, andkeepElevationOnSafeMode. Always gate elevated endpoints withcreateStepUpGuardrather than hardcoding 5-minute TOTP assumptions.- All mutating HTTP routes require an authenticated session cookie, matching
X-CSRF-Tokenheader, and Safe Mode enforcement (HTTP 423 SAFE_MODE_ACTIVEwhensession.safeModeis true; mobile viewports< 768pxdefault to Safe Mode ON). Only Panic Lock and/api/backup/verifyare Safe-Mode exempt.
3. Dual Backup Subsystems (recovery-store.ts vs. backup.ts)
- Local Emergency Secrets Store (
recovery-store.ts): Whensettings.security.enableEmergencySecretsBackupis enabled,EmergencyRecoveryServicemaintainsdata/recovery/emergency-secrets.json(chmod 0600) plus up to 10 snapshots underdata/recovery/snapshots/. KeepsyncRecovery()wired after auth/vault mutations. - Portable Encrypted Bundles (
backup.ts): Creates, verifies, and restoresGCOORD_BACKUP_V1.gcoord.encbundles encrypted withAES-256-GCM(raw-master-keyorscryptpassphrase KDF) containing gzippedconfig/**JSONs (includingservers/*.jsonsystems[].itemOverrides/activeFiles[]),vault.enc, and SQLiteknown_hosts+alert_silences. - Linux
inotifyRule on Config Restore: Whenever swapping or replacingdata/config/while the server is running (e.g.,/api/backup/restore), always callconfigManager.pauseWatcher()before replacing the directory andreloadAllFromDisk()+await configManager.resumeWatcher()afterward; otherwisechokidarretains stale directory inodes and stops firing hot-reload events.
4. Config Hot-Reload & SQLite Migrations (config-manager.ts, database.ts)
- Every config write must be atomic (
tmp -> fsync -> rename), validated against Zod schemas, and recorded in SQLiteconfig_revisionsfor diff/rollback. Hand-edited invalid config files must remain isolated without crashing the hub or clobbering valid files. - Never mutate existing migration files (
001_initial.ts,002_multi_auth.ts,003_phase4_meta.ts) destructively; add new schema changes as004_*.tsand register them insrc/server/db/database.ts.
5. SSH, Shell Quoting, Crypto & Tunnel Proxy Rules
- No Shell Injection: Never interpolate user inputs, workflow variables, or parameters directly into shell strings. Pass inputs via
GCOORD_*environment variables (buildWorkflowEnv,GCOORD_PARAM_*) or sanitize explicitly withinterpolateShellCommandSafe()(src/server/automation/template.ts) / POSIX single-quoting insrc/server/ssh/sudo.ts(and zeroizesudopasswordBuffers right after writing to stdin). ssh2Ed25519 Keygen Bug: Always generate Ed25519 keys throughgenerateValidEd25519KeyPair()insrc/server/security/vault.ts(retries aroundssh2's ASN.1 leading-0x00BitString parser issue).- Direct
rsyncChannel Drain: InTransferEngine(src/server/automation/transfer-engine.ts), always drain/consume SSH channelstdoutandstderrstreams soclosenever deadlocks on full flow-control windows. - Reverse Proxy Isolation: In
src/server/app.ts, keep/proxymounted beforeexpress.json()and exempt/proxy/*from the hub SPA Content-Security-Policy.TunnelManager(src/server/ssh/tunnel-manager.ts) must keep strippinggcoord_sidandgcoord_csrfcookies from forwarded headers and rewriting relativeLocationredirects.
6. Optional BYO-API AI Assistant (src/server/ai/)
- Strictly opt-in: return
403 AI_DISABLEDwheneversettings.ai.enabled === falseand hide[AI ...]triggers in the UI unlessisAiEnabled(state)is true. - Sanitize all outbound AI prompts and context previews through
redactSecrets()(redactor.ts) seeded withcollectVaultSecretStrings(). - Never auto-execute AI-suggested shell commands or auto-save AI-generated JSON/system/workflow drafts—require server Zod
validateDraft, line diff preview, and explicit user confirmation inai-drawer.ts.
5. Frontend, Bundle Budget & Mobile Rules
Hard Gzip Budgets (src/client/build.ts — throws and fails build if exceeded)
- Core bundle (
index.html+themes.css+base.css+main.js): strictly< 50.00 KBgzipped (currently25.46 KB). - Every non-terminal lazy chunk (
dist/public/chunks/*.jsexceptterminal-view-*): strictly< 20.00 KBgzipped.
CRITICAL: Zero Runtime zod in Client Code
- NEVER import runtime schemas or runtime values from
src/shared/schemas/*orzodanywhere insidesrc/client/ts/**. Importing Zod into client TypeScript drags Zod intomain.jsor lazy chunks and breaks the gzip budgets. - Use
import type { ... } from '../../shared/...'exclusively, mirror minimal constants cleanly insrc/client/ts/state.ts(such asCLIENT_THEME_IDS), and keep heavy secondary views (terminal-view,sftp-view,systems-view,workflows-view,alerts-view,ai-drawer,tunnels-panel) code-split via dynamicimport(...).
Flat Sharp Aesthetic & 8 Themes
- Maintain the zero-overhead aesthetic:
border-radius: 0,1pxcrisp borders, zerobox-shadow, zero gradients, zerobackdrop-filter. - Keep all 8 themes (
phosphor-green,amber-term,nord-dark,gruvbox-dark,paper-light,solarized-dark,tokyo-night,high-contrast) in sync acrossTHEME_IDS(src/shared/schemas/settings.schema.ts),src/client/css/themes.css,CLIENT_THEME_IDS(src/client/ts/state.ts), andapplyTheme()(which updates<meta name="theme-color">). Note thatesbuildCSS minification removes quotes in attribute selectors ([data-theme=phosphor-green]).
xterm.js, QR & Low-RAM Mobile (< 768px / Galaxy J7) Safeguards
- Keep global textarea sizing in
src/client/css/base.cssscoped totextarea:not(.xterm-helper-textarea)so.xterm-helper-textareastays0x0and does not overflow its container. - Preserve capture-phase sticky
Ctrl/Altinput handling andclearTerminalComposition()insrc/client/ts/views/xterm-runtime.tsso mobile IMEs (e.g., Firefox Android + Gboard) cannot leave ghost characters (likexafterCtrl+x). - Keep
.qr-boxsquare (align-self: flex-start; width: fit-content; line-height: 0). - Preserve
< 768px44pxminimum touch target heights on.btn-smand.input-sm,overscroll-behavior: containondialog:modalanddialog::backdrop,env(safe-area-inset-bottom)nav padding, viewport-capped chart history viamaxChartPointsForViewport(), andappendBoundedStreamText()for live<pre>stream logs.
6. Testing & Verification Workflow
- Write tests in
tests/*.test.tsusingcreateGCoordinatorServer({ dataDir: tmpDir, port: 0, ... })paired withMockSshServer(tests/helpers/mock-ssh-server.ts) for isolated HTTP +/ws+ SSH/SFTP/PTY/ProxyJump/Tunnel testing without external daemons. Always clean up temp directories andawait instance.close()/await mockSsh.stop()infinallyorafterEach. - Before concluding any code change:
export PATH="$HOME/.local/bin:$PATH" npm run build && npm test - Inspect
git statusandgit diffafter edits to confirm clean diffs, untouched unrelated docs/comments, and passing typechecks, bundle budgets, and all Vitest tests.