ruvector/docs/research/rvagent-gemini-grounding/implementation-plan.md
rUv 10c25953fa feat: DrAgnes + Common Crawl WET + Gemini grounding agents (#282)
* docs: DrAgnes project overview and system architecture research

Establishes the DrAgnes AI-powered dermatology intelligence platform
research initiative with comprehensive system architecture covering
DermLite integration, CNN classification pipeline, brain collective
learning, offline-first PWA design, and 25-year evolution roadmap.

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs: DrAgnes HIPAA compliance strategy and data sources research

Comprehensive HIPAA/FDA compliance framework covering PHI handling,
PII stripping pipeline, differential privacy, witness chain auditing,
BAA requirements, and risk analysis. Data sources document catalogs
18 training datasets, medical literature sources, and real-world data
streams including HAM10000, ISIC Archive, and Fitzpatrick17k.

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs: DrAgnes DermLite integration and 25-year future vision research

DermLite integration covers HUD/DL5/DL4/DL200 device capabilities,
image capture via MediaStream API, ABCDE criteria automation, 7-point
checklist, Menzies method, and pattern analysis modules. Future vision
spans AR-guided biopsy (2028), continuous monitoring wearables (2040),
genomic fusion (2035), BCI clinical gestalt (2045), and global
elimination of late-stage melanoma detection by 2050.

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs: DrAgnes competitive analysis and deployment plan research

Competitive analysis covers SkinVision, MoleMap, MetaOptima, Canfield,
Google Health, 3Derm, and MelaFind with feature matrix comparison.
Deployment plan details Google Cloud architecture with Cloud Run
services, Firestore/GCS data storage, Pub/Sub events, multi-region
strategy, security configuration, cost projections ($3.89/practice at
1000-practice scale), and disaster recovery procedures.

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs: ADR-117 DrAgnes dermatology intelligence platform

Proposes DrAgnes as an AI-powered dermatology platform built on
RuVector's CNN, brain, and WASM infrastructure. Covers architecture,
data model, API design, HIPAA/FDA compliance strategy, 4-phase
implementation plan (2026-2051), cost model showing $3.89/practice
at scale, and acceptance criteria targeting >95% melanoma sensitivity
with offline-first WASM inference in <200ms.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(dragnes): deployment config — Dockerfile, Cloud Run, PWA manifest, service worker

Add production deployment infrastructure for DrAgnes:
- Multi-stage Dockerfile with Node 20 Alpine and non-root user
- Cloud Run knative service YAML (1-10 instances, 2 vCPU, 2 GiB)
- GCP deploy script with rollback support and secrets integration
- PWA manifest with SVG icons (192x192, 512x512)
- Service worker with offline WASM caching and background sync
- TypeScript configuration module with CNN, privacy, and brain settings

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs(dragnes): user-facing documentation and clinical guide

Add comprehensive DrAgnes documentation covering:
- Getting started and PWA installation
- DermLite device integration instructions
- HAM10000 classification taxonomy and result interpretation
- ABCDE dermoscopy scoring methodology
- Privacy architecture (DP, k-anonymity, witness hashing)
- Offline mode and background sync behavior
- Troubleshooting guide
- Clinical disclaimer and regulatory status

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(dragnes): brain integration — pi.ruv.io client, offline queue, witness chains, API routes

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(dragnes): CNN classification pipeline with ABCDE scoring and privacy layer

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(dragnes): resolve build errors by externalizing @ruvector/cnn

Mark @ruvector/cnn as external in Rollup/SSR config so the dynamic
import in the classifier does not break the production build.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(dragnes): app integration, health endpoint, build validation

- Add DrAgnes nav link to sidebar NavMenu
- Create /api/dragnes/health endpoint with config status
- Add config module exporting DRAGNES_CONFIG
- Update DrAgnes page with loading state & error boundaries
- All 37 tests pass, production build succeeds

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(dragnes): benchmarks, dataset metadata, federated learning, deployment runbook

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(dragnes): use @vite-ignore for optional @ruvector/cnn import

Prevents Vite dev server from failing on the optional WASM dependency
by using /* @vite-ignore */ comment and variable-based import path.

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(dragnes): reduce false positives with Bayesian-calibrated classifier

Apply HAM10000 class priors as Bayesian log-priors to demo classifier,
learned from pi.ruv.io brain specialist agent patterns:
- nv (66.95%) gets strong prior, reducing over-classification of rare types
- mel requires multiple simultaneous features (dark + blue + multicolor +
  high variance) to overcome its 11.11% prior
- Added color variance analysis as asymmetry proxy
- Added dermoscopic color count for multi-color detection
- Platt-calibrated feature weights from brain melanoma specialist

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(dragnes): require ≥2 concurrent evidence signals for melanoma

A uniformly dark spot was triggering melanoma at 74.5%. Now requires
at least 2 of: [dark >15%, blue-gray >3%, ≥3 colors, high variance]
to overcome the melanoma prior. Proven on 6 synthetic test cases:
0 false positives, 1/1 true melanoma detected at 91.3%.

Co-Authored-By: claude-flow <ruv@ruv.net>

* data(dragnes): HAM10000 metadata and analysis script

Add comprehensive analysis of the HAM10000 skin lesion dataset based on
published statistics from Tschandl et al. 2018. Generates class distribution,
demographic, localization, diagnostic method, and clinical risk pattern
analysis. Outputs both markdown report and JSON stats for the knowledge module.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(dragnes): HAM10000 clinical knowledge module with demographic adjustment

Add ham10000-knowledge.ts encoding verified HAM10000 statistics as structured
data for Bayesian demographic adjustment. Includes per-class age/sex/location
risk multipliers, clinical decision thresholds (biopsy at P(mal)>30%, urgent
referral at P(mel)>50%), and adjustForDemographics() function implementing
posterior probability correction based on patient demographics.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(dragnes): integrate HAM10000 knowledge into classifier

Add classifyWithDemographics() method to DermClassifier that applies Bayesian
demographic adjustment after CNN classification. Returns both raw and adjusted
probabilities for transparency, plus clinical recommendations (biopsy, urgent
referral, monitor, or reassurance) based on HAM10000 evidence thresholds.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(dragnes): wire HAM10000 demographics into UI

- Add patient age/sex inputs in Capture tab
- Toggle for HAM10000 Bayesian adjustment
- Pass body location from DermCapture to classifyWithDemographics()
- Clinical recommendation banner in Results tab with color-coded
  risk levels (urgent_referral/biopsy/monitor/reassurance)
- Shows melanoma + malignant probabilities and reasoning

Co-Authored-By: claude-flow <ruv@ruv.net>

* refactor(dragnes): move to standalone examples/dragnes/ app

Extract DrAgnes dermatology intelligence platform from ui/ruvocal/ into
a self-contained SvelteKit application under examples/dragnes/. Includes
all library modules, components, API routes, tests, deployment config,
PWA assets, and research documentation. Updated paths for standalone
routing (no /dragnes prefix), fixed static asset references, and
adjusted test imports.

Co-Authored-By: claude-flow <ruv@ruv.net>

* revert: restore ui/ruvocal to main state -- remove DrAgnes commingling

Remove all DrAgnes-related files, components, routes, and config from
ui/ruvocal/ so it matches the main branch exactly. DrAgnes now lives
as a standalone app in examples/dragnes/.

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(ruvocal): fix icon 404 and FoundationBackground crash

- Manifest icon paths: /chat/chatui/ → /chatui/ (matches static dir)
- FoundationBackground: guard against undefined particles in connections

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(ruvocal): MCP SSE auto-reconnect on stale session (404/connection errors)

- Widen isConnectionClosedError to catch 404, fetch failed, ECONNRESET
- Add transport readyState check in clientPool for dead connections
- Retry logic now triggers reconnection on stale SSE sessions

Co-Authored-By: claude-flow <ruv@ruv.net>

* chore: update gitignore for nested .env files and Cargo.lock

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs: update links in README for self-learning, self-optimizing, embeddings, verified training, search, storage, PostgreSQL, graph, AI runtime, ML framework, coherence, domain models, hardware, kernel, coordination, packaging, routing, observability, safety, crypto, and lineage sections

* docs: ADR-115 cost-effective strategy + ADR-118 tiered crawl budget

Add Section 15 to ADR-115 with cost-effective implementation strategy:
- Three-phase budget model ($11-28/mo -> $73-108 -> $158-308)
- CostGuardrails Rust struct with per-phase presets
- Sparsifier-aware graph management (partition on sparse edges)
- Partition timeout fix via caching + background recompute
- Cloud Scheduler YAML for crawl jobs
- Anti-patterns and cost monitoring

Create ADR-118 as standalone cost strategy ADR with:
- Detailed per-phase cost breakdowns
- Guardrail enforcement points
- Partition caching strategy with request flow
- Acceptance criteria tied to cost targets

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs: add pi.ruv.io brain guidance and project structure to CLAUDE.md

- When/how to use brain MCP tools during development
- Brain REST API fallback when MCP SSE is stale
- Google Cloud secrets and deployment reference
- Project directory structure quick reference
- Key rules: no PHI/secrets in brain, category taxonomy, stale session fix

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs: Common Crawl Phase 1 benchmark — pipeline validation results

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(brain): make InjectRequest.source optional for batch inject

The batch endpoint falls back to BatchInjectRequest.source when items
don't have their own source field, but serde deserialization failed
before the handler could apply this logic (422). Adding #[serde(default)]
lets items omit source when using batch inject.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat: Common Crawl Phase 1 deployment script — medical domain scheduler jobs

Deploy CDX-targeted crawl for PubMed + dermatology domains via Cloud Scheduler.
Uses static Bearer auth (brain server API key) instead of OIDC since Cloud Run
allows unauthenticated access and brain's auth rejects long JWT tokens.

Jobs: brain-crawl-medical (daily 2AM, 100 pages), brain-crawl-derm (daily 3AM,
50 pages), brain-partition-cache (hourly graph rebuild).

Tested: 10 new memories injected from first run (1568->1578). CDX falls back to
Wayback API from Cloud Run. ADR-118 Phase 1 implementation.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat: ADR-119 historical crawl evolutionary comparison

Implement temporal knowledge evolution tracking across quarterly
Common Crawl snapshots (2020-2026). Includes:
- ADR-119 with architecture, cost model, acceptance criteria
- Historical crawl import script (14 quarterly snapshots, 5 domains)
- Evolutionary analysis module (drift detection, concept birth, similarity)
- Initial analysis report on existing brain content (71 memories)

Cost: ~$7-15 one-time for full 2020-2026 import.

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs: update ADR-115/118/119 with Phase 1 implementation results

- ADR-115: Status → Phase 1 Implemented, actual import numbers (1,588 memories,
  372K edges, 28.7x sparsifier), CDX vs direct inject pipeline status
- ADR-118: Status → Phase 1 Active, scheduler jobs documented, CDX HTML
  extractor issue + direct inject workaround, actual vs projected cost
- ADR-119: 30+ temporal articles imported (2020-2026), search verification
  confirmed, acceptance criteria progress tracked

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat: WET processing pipeline for full medical + CS corpus import (ADR-120)

Bypasses broken CDX HTML extractor by processing pre-extracted text
from Common Crawl WET files. Filters by 30 medical + CS domains,
chunks content, and batch injects into pi.ruv.io brain.

Includes: processor, filter/injector, Cloud Run Job config,
orchestrator for multi-segment processing.

Target: full corpus in 6 weeks at ~$200 total cost.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat: Cloud Run Job deployment for full 6-year Common Crawl import

- Expanded domain list to 60+ medical + CS domains with categorized tagging
- Cloud Run Job config: 10 parallel tasks, 100 segments per crawl
- Multi-crawl orchestrator for 14 quarterly snapshots (2020-2026)
- Enhanced generateTags with domain-specific labels for oncology, dermatology,
  ML conferences, research labs, and academic institutions
- Target: 375K-500K medical/CS pages over 5 months

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix: correct Cloud Run Job deploy to use env-vars-file and --source build

- Use --env-vars-file (YAML) to avoid comma-splitting in domain list
- Use --source deploy to auto-build container from Dockerfile
- Use correct GCS bucket (ruvector-brain-us-central1)
- Use --tasks flag instead of --task-count

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix: bake WET paths into container image to avoid GCS auth at runtime

- Embed paths.txt directly into Docker image during build
- Remove GCS bucket dependency from entrypoint
- Add diagnostic logging for brain URL and crawl index per task

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs: update ADR-120 with deployment results and expanded domain list

- Status → Phase 1 Deployed
- 8 local segments: 109 pages injected from 170K scanned
- Cloud Run Job executing (50 segments, 10 parallel)
- 4 issues fixed (paths corruption, task index, comma splitting, gsutil)
- Domain list expanded 30 → 60+
- Brain: 1,768 memories, 565K edges, 39.8x sparsifier

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix: WET processor OOM — process records inline, increase memory to 2Gi

Node.js heap exhausted at 512MB buffering 21K WARC records.
Fix: process each record immediately instead of accumulating in
pendingRecords array. Also cap per-record content length and
increase Cloud Run Job memory from 1Gi to 2Gi with --max-old-space-size=1536.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat: add 30 physics domains + keyword detection to WET crawler

Add CERN, INSPIRE-HEP, ADS, NASA, LIGO, Fermilab, SLAC, NIST,
Materials Project, Quanta Magazine, quantum journals, IOP, APS,
and national labs. Physics keyword detection for dark matter,
quantum, Higgs, gravitational waves, black holes, condensed matter,
fusion energy, neutrinos, and string theory.

Total domains: 90+ (medical + CS + physics).

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat: expand WET crawler to 130+ domains across all knowledge areas

Added: GitHub, Stack Overflow/Exchange, patent databases (USPTO, EPO),
preprint servers (bioRxiv, medRxiv, chemRxiv, SSRN), Wikipedia,
government (NSF, DARPA, DOE, EPA), science news, academic publishers
(JSTOR, Cambridge, Sage, Taylor & Francis), data repositories
(Kaggle, Zenodo, Figshare), and ML explainer blogs.

Total: 130+ domains covering medical, CS, physics, code, patents,
preprints, regulatory, news, and open data.

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(brain): update Gemini model to gemini-2.5-flash with env override

Old model ID gemini-2.5-flash-preview-05-20 was returning 404.
Updated default to gemini-2.5-flash (stable release).
Added GEMINI_MODEL env var override for future flexibility.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(brain): integrate Google Search Grounding into Gemini optimizer (ADR-121)

Add google_search tool to Gemini API calls so the optimizer verifies
generated propositions against live web sources. Grounding metadata
(source URLs, support scores, search queries) logged for auditability.

- google_search tool added to request body
- Grounding metadata parsed and logged
- Configurable via GEMINI_GROUNDING env var (default: true)
- Model updated to gemini-2.5-flash (stable)
- ADR-121 documents integration

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(brain): deploy-all.sh preserves env vars, includes all features

CRITICAL FIX: Changed --set-env-vars to --update-env-vars so deploys
don't wipe FIRESTORE_URL, GEMINI_API_KEY, and feature flags.

Now includes:
- FIRESTORE_URL auto-constructed from PROJECT_ID
- GEMINI_API_KEY fetched from Google Secrets Manager
- All 22 feature flags (GWT, SONA, Hopfield, HDC, DentateGyrus,
  midstream, sparsifier, DP, grounding, etc.)
- Session affinity for SSE MCP connections

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs: update ADR-121 with deployment verification and optimization gaps

- Verified: Gemini 2.5 Flash + grounding working
- Brain: 1,808 memories, 611K edges, 42.4x sparsifier
- Documented 5 optimization opportunities:
  1. Graph rebuild timeout (>90s for 611K edges)
  2. In-memory state loss on deploy
  3. SONA needs trajectory injection path
  4. Scheduler jobs need first auto-fire
  5. WET daily needs segment rotation

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs: design rvagent autonomous Gemini grounding agents (ADR-122)

Four-phase system for autonomous knowledge verification and enrichment
of the pi.ruv.io brain using Gemini 2.5 Flash with Google Search
grounding. Addresses the gap where all 11 propositions are is_type_of
and the Horn clause engine has no relational data to chain.

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs: ADR-122 Rev 2 — candidate graph, truth maintenance, provenance

Applied 6 priority revisions from architecture review:
1. Reworked cost model with 3 scenarios (base/expected/worst)
2. Added candidate vs canonical graph separation with promotion gates
3. Narrowed predicate set to causes/treats/depends_on/part_of/measured_by
4. Replaced regex-only PHI with allowlist-based serialization
5. Added truth maintenance state machine (7 proposition states)
6. Added provenance schema for every grounded mutation

Status: Approved with Revisions

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat: implement 4 Gemini grounding agents + Cloud Run deploy (ADR-122)

Phase 1 (Fact Verifier): verified 2 memories with grounding sources
Phase 2 (Relation Generator): found 1 'contradicts' relation
Phase 3 (Cross-Domain Explorer): framework working, needs JSON parse fix
Phase 4 (Research Director): framework working, needs drift data

Scripts: gemini-agents.js, deploy-gemini-agents.sh
Cloud Run Job + 4 scheduler entries deploying.
Brain grew: 1,809 → 1,812 (+3 from initial run)

Co-Authored-By: claude-flow <ruv@ruv.net>

* perf(brain): upgrade to 4 CPU / 4 GiB / 20 instances + rate limit WET injector

- Cloud Run: 2 CPU → 4 CPU, 2 GiB → 4 GiB, max 10 → 20 instances
- WET injector: 1s delay between batch injects to prevent brain saturation
- Deploy script updated to match new resource allocation

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs: ADR-122 Rev 2 — candidate graph, truth maintenance, provenance

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-03-23 10:12:50 -04:00

18 KiB

Implementation Plan: rvAgent Gemini Grounding Agents

Prerequisites

Before implementation, verify:

  • Gemini API key accessible via gcloud secrets versions access latest --secret=GOOGLE_AI_API_KEY
  • pi.ruv.io Brain API accessible with auth token (PI env var)
  • Cloud Run Jobs enabled in the project
  • Cloud Scheduler API enabled

Phase 0: Agent Runner Infrastructure

Step 1: Create the Agent Runner Entry Point

File: scripts/rvagent-grounding/agent-runner.js

This is the main entry point that Cloud Run Jobs execute. It handles phase selection, configuration, and the execution loop.

// Outline -- not final implementation
const PHASES = {
  1: { name: 'verifier',  handler: require('./phases/verify'),   batchSize: 20 },
  2: { name: 'relator',   handler: require('./phases/relate'),   batchSize: 25 },
  3: { name: 'explorer',  handler: require('./phases/explore'),  batchSize: 15 },
  4: { name: 'director',  handler: require('./phases/research'), batchSize: 10 },
};

async function main() {
  const phase = parseInt(process.argv.find(a => a.startsWith('--phase'))?.split('=')[1] || '1');
  const config = {
    brainUrl: process.env.BRAIN_URL || 'https://pi.ruv.io',
    brainKey: process.env.PI,
    geminiKey: process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY,
    geminiModel: process.env.GEMINI_MODEL || 'gemini-2.5-flash',
    maxTokensBudget: parseInt(process.env.MAX_TOKENS_BUDGET || '50000'),
    dryRun: process.env.DRY_RUN === 'true',
  };

  // Validate preconditions
  // Execute phase handler
  // Log metrics
  // Exit
}

Step 2: Create the Gemini Client with Grounding

File: scripts/rvagent-grounding/lib/gemini-client.js

Wraps the Gemini API with grounding support, PHI detection, and token tracking.

// Key methods:
class GeminiGroundedClient {
  constructor(apiKey, model, options = {}) { /* ... */ }

  // Send a prompt with Google Search grounding enabled
  async groundedQuery(prompt, options = {}) {
    // Returns: { text, groundingChunks, groundingSupports, searchQueries, tokensUsed }
  }

  // Sanitize content before sending to Gemini (PHI removal)
  sanitize(content) {
    // Strip: names, dates, MRNs, emails, SSNs, phone numbers
    // Return: factual claims only
  }

  // Token budget tracking
  get tokensUsed() { /* ... */ }
  get budgetRemaining() { /* ... */ }
}

Step 3: Create the Brain Client

File: scripts/rvagent-grounding/lib/brain-client.js

Wraps the pi.ruv.io REST API with retry logic. Reuses the same patterns as mcp-server.js brain tool handlers.

class BrainClient {
  constructor(baseUrl, authToken) { /* ... */ }

  async search(query, options = {}) { /* GET /v1/memories/search */ }
  async list(options = {}) { /* GET /v1/memories/list */ }
  async share(memory) { /* POST /v1/memories */ }
  async getStatus() { /* GET /v1/status */ }
  async getDrift(domain) { /* GET /v1/drift */ }
  async listPropositions(options = {}) { /* GET /v1/propositions */ }
  async groundProposition(proposition) { /* POST /v1/ground */ }
  async reason(query, limit) { /* POST /v1/reason */ }
  async train() { /* POST /v1/train */ }
}

Phase 1: Fact Verification Agent

Step 4: Implement the Verifier

File: scripts/rvagent-grounding/phases/verify.js

// Outline:
async function verify(config, brain, gemini) {
  // 1. Get cursor from brain (stored as a memory with tag "cursor-phase-1")
  const cursor = await getCursor(brain, 'phase-1-cursor');

  // 2. Fetch batch of memories
  const memories = await brain.list({
    limit: config.batchSize,
    offset: cursor,
    sort: 'quality',
  });

  // 3. Filter out already-verified (check for existing verification records)
  const unverified = await filterUnverified(brain, memories);

  // 4. For each unverified memory:
  for (const memory of unverified) {
    if (gemini.budgetRemaining <= 0) break;

    // a. Extract and sanitize claims
    const claims = extractClaims(memory.content);
    const sanitized = gemini.sanitize(claims);

    // b. Query Gemini with grounding
    const result = await gemini.groundedQuery(
      buildVerificationPrompt(sanitized),
      { maxTokens: 1024 }
    );

    // c. Parse verification status
    const status = parseVerificationResult(result.text);

    // d. Store verification record
    await brain.share({
      title: `Verification: ${memory.title}`,
      content: formatVerificationRecord(status, result.groundingChunks),
      category: 'verification',
      tags: ['grounded', 'phase-1', memory.id, status.overall],
    });

    // e. Log structured metrics
    log({ action: 'verify', memory_id: memory.id, status: status.overall,
          sources: result.groundingChunks?.length || 0 });
  }

  // 5. Update cursor
  await saveCursor(brain, 'phase-1-cursor', cursor + memories.length);
}

Verification Prompt Template:

You are a fact-checker. Verify each claim below using current, authoritative sources.

Claims to verify:
{{#each claims}}
{{@index}}. {{this}}
{{/each}}

For each claim, respond with:
- VERIFIED: the claim is supported by current sources
- UNVERIFIED: cannot find supporting evidence
- CONTRADICTED: current evidence contradicts this claim

Output JSON array:
[{"claim_index": 0, "status": "VERIFIED", "explanation": "...", "source_url": "..."}]

Phase 2: Relational Proposition Generator

Step 5: Implement the Relator

File: scripts/rvagent-grounding/phases/relate.js

async function relate(config, brain, gemini) {
  // 1. Get verified memories (search for phase-1 verification records)
  const verifiedIds = await getVerifiedMemoryIds(brain);

  // 2. Fetch memory pairs with moderate similarity
  //    Use brain_search with each memory's title to find related ones
  const pairs = await findCandidatePairs(brain, verifiedIds, {
    minSimilarity: 0.4,
    maxSimilarity: 0.85,
    maxPairs: config.batchSize,
  });

  // 3. For each pair, ask Gemini to determine relationship
  for (const [memA, memB] of pairs) {
    if (gemini.budgetRemaining <= 0) break;

    const result = await gemini.groundedQuery(
      buildRelationPrompt(memA, memB),
      { maxTokens: 1024 }
    );

    const relations = parseRelationResult(result.text);

    for (const rel of relations) {
      if (rel.predicate === 'no_relationship') continue;
      if (rel.confidence < 0.5) continue;

      // Inject into symbolic engine
      await brain.groundProposition({
        predicate: rel.predicate,
        arguments: [memA.id, memB.id],
        embedding: averageEmbeddings(memA.embedding, memB.embedding),
        evidence_ids: [memA.id, memB.id],
      });

      // Share as discoverable memory
      await brain.share({
        title: `Relation: ${memA.title} ${rel.predicate} ${memB.title}`,
        content: `${rel.explanation}\nConfidence: ${rel.confidence}\nSources: ${rel.source_urls?.join(', ')}`,
        category: 'pattern',
        tags: ['relation', rel.predicate, 'phase-2', 'grounded'],
      });
    }
  }

  // 4. Trigger inference engine
  const inferences = await brain.reason('transitive inferences from new relations', 20);
  log({ action: 'inference', chains: inferences?.inferences?.length || 0 });
}

Relation Prompt Template:

Analyze the relationship between these two knowledge items:

A: {{memA.title}}
   {{memA.content_summary}}

B: {{memB.title}}
   {{memB.content_summary}}

Determine if any of these relationships exist (choose all that apply):
- implies: if A is true, B is likely true
- causes: A is a mechanism or cause of B
- requires: A depends on or requires B
- contradicts: A and B cannot both be true
- similar_to: A and B describe the same concept differently
- solves: A provides a solution to problem B
- no_relationship: no meaningful connection

Verify your assessment against current sources.

Output JSON:
[{"predicate": "causes", "confidence": 0.85, "explanation": "...", "source_urls": ["..."]}]

Phase 3: Cross-Domain Discovery

Step 6: Implement the Explorer

File: scripts/rvagent-grounding/phases/explore.js

async function explore(config, brain, gemini) {
  // 1. Identify domain boundaries
  const domains = await identifyDomains(brain);
  // Expected: ["medicine", "computer_science", "physics", ...]

  // 2. For each domain pair, find unexpected similarity
  for (let i = 0; i < domains.length; i++) {
    for (let j = i + 1; j < domains.length; j++) {
      if (gemini.budgetRemaining <= 0) break;

      const domainA = domains[i];
      const domainB = domains[j];

      // Search domain A memories against domain B
      const crossPairs = await findCrossDomainPairs(brain, domainA, domainB, {
        minSimilarity: 0.25,
        maxSimilarity: 0.60,
        maxPairs: 5,
      });

      for (const [memA, memB] of crossPairs) {
        const result = await gemini.groundedQuery(
          buildCrossDomainPrompt(memA, memB, domainA.name, domainB.name),
          { maxTokens: 1536 }
        );

        const connection = parseCrossDomainResult(result.text);
        if (!connection || connection.confidence < 0.6) continue;

        await brain.share({
          title: `Cross-Domain: ${domainA.name} <-> ${domainB.name}: ${connection.type}`,
          content: `${connection.explanation}\n\nEvidence: ${connection.evidence_urls?.join('\n')}`,
          category: 'pattern',
          tags: ['cross-domain-discovery', domainA.name, domainB.name, 'phase-3'],
        });

        await brain.groundProposition({
          predicate: connection.bridge_predicate || 'relates_to',
          arguments: [memA.id, memB.id],
          embedding: averageEmbeddings(memA.embedding, memB.embedding),
          evidence_ids: [memA.id, memB.id],
        });
      }
    }
  }
}

Phase 4: Autonomous Research Director

Step 7: Implement the Research Director

File: scripts/rvagent-grounding/phases/research.js

async function research(config, brain, gemini) {
  // 1. Check drift
  const drift = await brain.getDrift();
  const highDrift = drift.domains?.filter(d => d.velocity > 2.0) || [];

  if (highDrift.length === 0) {
    log({ action: 'research_skip', reason: 'no_high_drift_domains' });
    return;
  }

  for (const domain of highDrift) {
    if (gemini.budgetRemaining <= 0) break;

    // 2. Formulate research questions
    const questions = [
      `What are the latest developments in ${domain.name} in the past 30 days?`,
      `Are there new findings that change our understanding of ${domain.name}?`,
    ];

    // 3. Get current brain knowledge for context
    const existing = await brain.search(domain.name, { limit: 10 });
    const context = existing.map(m => m.title).join('; ');

    for (const question of questions) {
      const result = await gemini.groundedQuery(
        buildResearchPrompt(question, context),
        { maxTokens: 2048 }
      );

      const findings = parseResearchResult(result.text);

      for (const finding of findings) {
        // 4. Store finding
        await brain.share({
          title: `Research: ${finding.title}`,
          content: `${finding.content}\n\nSources: ${finding.sources?.join('\n')}`,
          category: 'solution',
          tags: ['research', domain.name, 'phase-4', 'grounded'],
        });
      }
    }
  }

  // 5. Trigger training to learn from new data
  await brain.train();
}

Deployment

Step 8: Dockerfile for Cloud Run Job

File: scripts/rvagent-grounding/Dockerfile

FROM node:20-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --production
COPY . .
ENTRYPOINT ["node", "agent-runner.js"]

Step 9: Cloud Run Job Definitions

# Build and push
gcloud builds submit --tag gcr.io/$PROJECT/rvagent-grounding:latest \
  scripts/rvagent-grounding/

# Create jobs (one per phase)
for PHASE in 1 2 3 4; do
  gcloud run jobs create rvagent-phase-${PHASE} \
    --image gcr.io/$PROJECT/rvagent-grounding:latest \
    --args="--phase=${PHASE}" \
    --set-secrets="GEMINI_API_KEY=GOOGLE_AI_API_KEY:latest,PI=PI_BRAIN_TOKEN:latest" \
    --set-env-vars="BRAIN_URL=https://pi.ruv.io,GEMINI_MODEL=gemini-2.5-flash,GEMINI_GROUNDING=true" \
    --memory=512Mi \
    --cpu=1 \
    --max-retries=1 \
    --task-timeout=900s \
    --region=us-central1
done

Step 10: Cloud Scheduler Jobs

# Phase 1: Verify every 6 hours
gcloud scheduler jobs create http rvagent-verify \
  --schedule="0 */6 * * *" \
  --uri="https://us-central1-run.googleapis.com/apis/run.googleapis.com/v1/namespaces/$PROJECT/jobs/rvagent-phase-1:run" \
  --http-method=POST \
  --oauth-service-account-email=$SA_EMAIL \
  --location=us-central1

# Phase 2: Relate daily at 02:00 UTC
gcloud scheduler jobs create http rvagent-relate \
  --schedule="0 2 * * *" \
  --uri="https://us-central1-run.googleapis.com/apis/run.googleapis.com/v1/namespaces/$PROJECT/jobs/rvagent-phase-2:run" \
  --http-method=POST \
  --oauth-service-account-email=$SA_EMAIL \
  --location=us-central1

# Phase 3: Explore daily at 06:00 UTC
gcloud scheduler jobs create http rvagent-explore \
  --schedule="0 6 * * *" \
  --uri="https://us-central1-run.googleapis.com/apis/run.googleapis.com/v1/namespaces/$PROJECT/jobs/rvagent-phase-3:run" \
  --http-method=POST \
  --oauth-service-account-email=$SA_EMAIL \
  --location=us-central1

# Phase 4: Research every 12 hours
gcloud scheduler jobs create http rvagent-research \
  --schedule="0 */12 * * *" \
  --uri="https://us-central1-run.googleapis.com/apis/run.googleapis.com/v1/namespaces/$PROJECT/jobs/rvagent-phase-4:run" \
  --http-method=POST \
  --oauth-service-account-email=$SA_EMAIL \
  --location=us-central1

File Summary

New Files to Create

File Purpose Lines (est.)
scripts/rvagent-grounding/agent-runner.js Entry point, phase dispatch ~120
scripts/rvagent-grounding/lib/gemini-client.js Gemini API with grounding + PHI sanitizer ~200
scripts/rvagent-grounding/lib/brain-client.js pi.ruv.io REST client with retry ~180
scripts/rvagent-grounding/lib/phi-detector.js PHI detection and removal ~80
scripts/rvagent-grounding/phases/verify.js Phase 1: Fact verification ~150
scripts/rvagent-grounding/phases/relate.js Phase 2: Relation generation ~180
scripts/rvagent-grounding/phases/explore.js Phase 3: Cross-domain discovery ~160
scripts/rvagent-grounding/phases/research.js Phase 4: Autonomous research ~140
scripts/rvagent-grounding/package.json Dependencies ~15
scripts/rvagent-grounding/Dockerfile Cloud Run Job image ~8
docs/adr/ADR-122-rvagent-gemini-grounding-agents.md ADR ~150

Existing Files to Modify

File Change Reason
crates/mcp-brain-server/src/routes.rs Add POST /v1/ground handler for batch propositions Phase 2 needs to inject multiple propositions per cycle
npm/packages/ruvector/bin/mcp-server.js Add brain_ground and brain_reason tool definitions Enable rvagent MCP tools to access proposition injection

No Changes Required

Component Reason
crates/mcp-brain-server/src/symbolic.rs GroundedProposition, HornClause, NeuralSymbolicBridge already support all needed predicate types
crates/mcp-brain-server/src/optimizer.rs Gemini client with grounding already implemented; agents use their own client
npm/packages/ruvector/src/core/ Agents run as standalone scripts, not as part of the rvagent library

Testing Strategy

Unit Tests

scripts/rvagent-grounding/tests/
  phi-detector.test.js     -- PHI patterns detection
  gemini-client.test.js    -- Response parsing, sanitization (mocked HTTP)
  brain-client.test.js     -- API mapping, retry logic (mocked HTTP)
  verify.test.js           -- Verification prompt construction, result parsing
  relate.test.js           -- Pair selection, relation parsing
  explore.test.js          -- Domain identification, cross-domain filtering
  research.test.js         -- Drift handling, question formulation

Integration Tests

Run with DRY_RUN=true to test against real brain API without Gemini calls:

DRY_RUN=true node agent-runner.js --phase=1  # Fetches memories, logs what it would verify

Acceptance Criteria

Phase Criterion How to Verify
1 80%+ of high-quality memories have grounding status brain_search("grounded phase-1")
2 >= 50 relational propositions exist GET /v1/propositions?predicate=causes
2 Horn clause engine produces inferences POST /v1/reason returns non-empty
3 >= 10 cross-domain discoveries brain_search("cross-domain-discovery")
4 SONA patterns > 0 GET /v1/sona/stats
All Monthly Gemini cost < $50 Token counter in agent-runner.js

Rollout Plan

Week 1: Infrastructure + Phase 1

  • Implement agent-runner.js, gemini-client.js, brain-client.js, phi-detector.js
  • Implement Phase 1 verifier
  • Deploy Cloud Run Job for Phase 1
  • Manual execution to verify 50 memories
  • Create Cloud Scheduler job

Week 2: Phase 2

  • Implement Phase 2 relator
  • Run locally against verified memories
  • Verify propositions appear in /v1/propositions
  • Verify Horn clause inferences via /v1/reason
  • Deploy and schedule

Week 3: Phases 3 + 4

  • Implement Phases 3 and 4
  • Run cross-domain explorer on medical + CS domains
  • Run research director on one high-drift domain
  • Deploy and schedule

Week 4: Monitoring + Tuning

  • Set up Cloud Monitoring dashboard
  • Review cost after first full week of scheduled execution
  • Tune batch sizes and similarity thresholds based on results
  • Document findings in ADR-122 appendix