Skip to content

A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.

feat: add Offline Troubleshooting Agent

Tiioluwani6f92c8601dfe
diff --git a/ai_agents/offline_troubleshooting_agent/.env.example b/ai_agents/offline_troubleshooting_agent/.env.example
new file mode 100644
index 0000000..e51d5bc
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/.env.example
@@ -0,0 +1,20 @@
+# Actian VectorAI DB
+ACTIAN_VECTORAI_HOST=
+ACTIAN_VECTORAI_PORT=
+ACTIAN_VECTORAI_INCIDENT_COLLECTION=
+ACTIAN_VECTORAI_MANUAL_COLLECTION=
+
+# Ollama
+OLLAMA_BASE_URL=http://localhost:11434
+OLLAMA_MODEL=qwen3:4b-instruct
+
+# Local embeddings
+EMBEDDING_MODEL=nomic-embed-text
+
+# Agent limits
+MAX_AGENT_ROUNDS=8
+MAX_TOOL_CALLS=20
+
+# Gradio
+GRADIO_SERVER_NAME=127.0.0.1
+GRADIO_SERVER_PORT=7860
diff --git a/ai_agents/offline_troubleshooting_agent/.gitignore b/ai_agents/offline_troubleshooting_agent/.gitignore
new file mode 100644
index 0000000..d4104f0
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/.gitignore
@@ -0,0 +1,17 @@
+# Python
+__pycache__/
+*.py[cod]
+*$py.class
+*.egg-info/
+.pytest_cache/
+
+# Virtual environments
+venv/
+.venv/
+env/
+
+# Environment variables
+.env
+
+# Actian VectorAI DB persistent volume
+local_data/
diff --git a/ai_agents/offline_troubleshooting_agent/README.md b/ai_agents/offline_troubleshooting_agent/README.md
new file mode 100644
index 0000000..bcbad9b
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/README.md
@@ -0,0 +1,217 @@
+# Offline Troubleshooting Agent
+> A local AI maintenance assistant that keeps its memory even when the internet doesn't.
+
+## Overview
+The Offline Troubleshooting Agent is a fully local AI maintenance assistant for a simulated industrial machine. It investigates simulated sensor faults using a local LLM, a local equipment manual, and a local vector memory of previously resolved incidents, then requires a human technician to confirm or correct its diagnosis before anything is saved. Everything, the model, the embeddings, and the memory store, runs on a single machine, so the agent keeps working and keeps remembering even with the network fully disconnected.
+
+## Demo
+![Architecture](assets/architecture.png)
+The agent investigates using local tools (current readings, the equipment manual, and past incidents) before a human ever reviews anything, and nothing is written to persistent memory until that human confirms it.
+
+See `docs/OFFLINE_TEST_LOG_20260923T092644.md` for a real completed offline run, actual proof of the offline claim, not just the diagram's word for it.
+
+## Features
+- Simulates three distinct machine fault types (bearing wear, cooling failure, pressure loss) with realistic sensor trends
+- Investigates faults using a local LLM (qwen3:4b-instruct via Ollama) with a small, auditable tool set
+- Retrieves relevant equipment manual sections and prior resolved incidents from a local vector database
+- Distinguishes current sensor evidence from retrieved past incidents instead of blindly trusting either one
+- Requires human confirmation before any diagnosis is written to permanent memory, and preserves the model's original diagnosis separately from the human's confirmed cause
+- Persists incidents across application restarts and Actian container restarts
+- Proven to work with the network fully disconnected, verified by an automated offline test with a built in connectivity guard
+- Ships with automated tests covering the simulator, memory layer, agent tools, agent behavior, and safety boundaries
+
+## Tech Stack
+| Layer | Technology |
+|-------|------------|
+| LLM | Ollama running qwen3:4b-instruct |
+| Embeddings | Ollama running nomic-embed-text |
+| Vector Memory | Actian VectorAI DB |
+| UI | Gradio |
+| Data handling | Pandas |
+| Schema validation | Pydantic |
+
+## Prerequisites
+- Python 3.10 or higher
+- Docker Desktop
+- Ollama installed, with:
+ - [ ] qwen3:4b-instruct pulled (`ollama pull qwen3:4b-instruct`)
+ - [ ] nomic-embed-text pulled (`ollama pull nomic-embed-text`)
+
+No API keys or cloud accounts are needed anywhere in this project. It is fully local.
+
+## Installation
+### 1. Clone the Repository
+```bash
+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git
+cd Hands-On-AI-Engineering/ai_agents/offline_troubleshooting_agent
+```
+
+### 2. Start Actian VectorAI DB
+```bash
+docker compose up -d
+```
+This starts the container on host ports 6673 to 6675 instead of the image's default 6573 to 6575, so it will not collide with another Actian based project that might already be running on the same machine.
+
+### 3. Create a Virtual Environment
+This project uses its own `.venv` because installing `actian-vectorai-client` pulled in a `protobuf` version that conflicted with other tooling already installed on the development machine (see `docs/BUILD_LOG.md`, step 5). An isolated environment avoids that conflict entirely.
+```bash
+python -m venv .venv
+```
+
+### 4. Activate the Virtual Environment
+macOS/Linux:
+```bash
+source .venv/bin/activate
+```
+Windows PowerShell:
+```powershell
+.venv\Scripts\Activate.ps1
+```
+Windows CMD:
+```cmd
+.venv\Scripts\activate.bat
+```
+
+### 5. Install Dependencies
+```bash
+pip install -r requirements.txt
+```
+
+### 6. Configure Environment Variables
+```bash
+cp .env.example .env
+```
+Fill in the Actian fields to match the port mapping from step 2. See Environment Variables below for the full list.
+
+### 7. Seed Demo Data
+```bash
+python scripts/seed_memory.py --mode seeded
+```
+This ingests the local equipment manual and loads a few demo incidents, so the first investigation already has prior experience to retrieve.
+
+## Environment Variables
+| Variable | Description | Where to Get It |
+|----------|--------------|------------------|
+| OLLAMA_BASE_URL | URL of the local Ollama server | Runs locally, no account needed |
+| OLLAMA_MODEL | Local model used for the agent loop | Runs locally, no account needed. Pull with `ollama pull qwen3:4b-instruct` |
+| EMBEDDING_MODEL | Local model used for embeddings | Runs locally, no account needed. Pull with `ollama pull nomic-embed-text` |
+| ACTIAN_VECTORAI_HOST | Host for the local Actian VectorAI DB container | Runs locally, no account needed |
+| ACTIAN_VECTORAI_PORT | Port for the local Actian VectorAI DB container | Runs locally, no account needed |
+| ACTIAN_VECTORAI_INCIDENT_COLLECTION | Collection name for resolved incidents | Runs locally, no account needed |
+| ACTIAN_VECTORAI_MANUAL_COLLECTION | Collection name for manual chunks | Runs locally, no account needed |
+| GRADIO_SERVER_NAME | Host the Gradio app binds to | Runs locally, no account needed |
+| GRADIO_SERVER_PORT | Port the Gradio app binds to | Runs locally, no account needed |
+
+Unlike most projects in this repo, every one of these runs entirely on your own machine. There is nothing here to sign up for.
+
+## Usage
+### Run the App
+```bash
+python app.py
+```
+Comes up at `http://127.0.0.1:7860` (configurable via GRADIO_SERVER_NAME and GRADIO_SERVER_PORT). Trigger a fault from the Machine Status panel, click Start Investigation, and watch the Investigation, Retrieved Memory, and Recommendation panels fill in as the agent works. Once it concludes, a Review & Confirm panel appears with the model's diagnosis pre filled and fully editable. Click Confirm & Save to Memory to write it as a durable incident, or Discard to throw the investigation away without saving anything.
+
+### The Persistence Test
+Proves a saved incident survives a real Actian container restart.
+```bash
+python scripts/persistence_test.py --mode save
+docker compose restart offline-troubleshooting-vectorai
+python scripts/persistence_test.py --mode verify
+```
+`--mode verify` runs as a separate process and passes only if every field of the saved marker incident matches exactly and it is retrievable both by direct id lookup and by semantic search.
+
+### The Offline Test
+This is the actual point of the project. Everything else proves the pieces work. This test proves the real claim: a real local investigation can recall a genuinely new incident with zero internet access.
+
+`scripts/offline_test.py` triggers a bearing fault, runs a full investigation, and checks by exact incident id whether it recalls a reference incident that was saved earlier while still online. Before anything else runs, the script needs the network physically disconnected, and it enforces that itself: it first attempts a short timeout TCP connection to a public address, and if that connection succeeds, the network is not actually disconnected, so it prints a loud warning and exits immediately rather than letting the test silently pass under the wrong conditions. This guard exists specifically to keep the result honest.
+
+To run it for real:
+1. Physically disconnect the network (turn off Wi-Fi or unplug the cable).
+2. In a terminal, run:
+```bash
+python scripts/offline_test.py
+```
+3. Reconnect the network once it finishes.
+
+Results are written to a timestamped file under `docs/OFFLINE_TEST_LOG_<timestamp>.md`, so they survive even if the terminal closes before reconnecting.
+
+### Resetting the Demo
+```bash
+python scripts/reset_demo.py
+python scripts/reset_demo.py --reseed
+```
+The first clears the incidents collection. The second clears it and then reloads the demo incidents from `data/seed_incidents.json`. Neither touches the simulator's live machine state, use the Reset Machine button in the UI for that.
+
+## Project Structure
+```
+offline_troubleshooting_agent/
+├── README.md
+├── requirements.txt
+├── .env.example
+├── docker-compose.yml
+├── app.py
+│
+├── agent/
+│ ├── confirmation.py
+│ ├── harness.py
+│ ├── llm_client.py
+│ ├── prompts.py
+│ ├── state.py
+│ └── tools.py
+│
+├── simulator/
+│ ├── machine.py
+│ ├── scenarios.py
+│ └── history.py
+│
+├── memory/
+│ ├── vectorai_client.py
+│ ├── embeddings.py
+│ ├── manual.py
+│ └── incident_store.py
+│
+├── documents/
+│ ├── machine_manual.md
+│ └── troubleshooting_guide.md
+│
+├── data/
+│ └── seed_incidents.json
+│
+├── models/
+│ └── schemas.py
+│
+├── ui/
+│ └── gradio_app.py
+│
+├── scripts/
+│ ├── seed_memory.py
+│ ├── reset_demo.py
+│ ├── persistence_test.py
+│ ├── offline_test.py
+│ ├── maintenance_rebuild_index.py
+│ └── check_*.py
+│
+├── docs/
+│ ├── BUILD_LOG.md
+│ └── PROJECT_REFERENCE.md
+│
+└── tests/
+ ├── test_simulator.py
+ ├── test_tools.py
+ ├── test_agent.py
+ ├── test_confirmation.py
+ ├── test_safety.py
+ └── test_*.py
+```
+
+## Limitations
+This is a simulated machine and a fictional equipment manual, not a certified safety system. `qwen3:4b-instruct` is a small local model and occasionally needs the harness's retry nudge or fallback logic rather than concluding cleanly on the first attempt. Actian VectorAI DB Community Edition has a known behavior where a collection needs to be explicitly reopened after a restart before it is queryable again. This project handles that automatically inside `ensure_collection()`.
+
+## Safety Note
+This is a simulation and demo assistant, not a certified industrial safety system. It recommends inspection and normal maintenance procedure, never instructs bypassing safety interlocks or alarms, and never directly controls machinery.
+
+## License
+MIT
+
+---
+[⬆ Back to Top](#offline-troubleshooting-agent)
diff --git a/ai_agents/offline_troubleshooting_agent/agent/__init__.py b/ai_agents/offline_troubleshooting_agent/agent/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/ai_agents/offline_troubleshooting_agent/agent/confirmation.py b/ai_agents/offline_troubleshooting_agent/agent/confirmation.py
new file mode 100644
index 0000000..6266be4
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/agent/confirmation.py
@@ -0,0 +1,88 @@
+import uuid
+from datetime import datetime
+
+from agent.state import InvestigationState
+from models.schemas import Incident
+from simulator.machine import PRESSURE_RANGE, TEMP_RANGE, VIBRATION_RANGE
+
+DEFAULT_MACHINE_ID = "Machine A"
+
+
+def _derive_symptoms(current_readings: dict) -> list[str]:
+ """Deterministically label out-of-range readings against the simulator's
+ baseline ranges — not something to ask the model for."""
+ symptoms: list[str] = []
+
+ temperature_c = current_readings.get("temperature_c")
+ if temperature_c is not None:
+ if temperature_c > TEMP_RANGE[1]:
+ symptoms.append("elevated temperature")
+ elif temperature_c < TEMP_RANGE[0]:
+ symptoms.append("low temperature")
+
+ vibration_mm_s = current_readings.get("vibration_mm_s")
+ if vibration_mm_s is not None:
+ if vibration_mm_s > VIBRATION_RANGE[1]:
+ symptoms.append("elevated vibration")
+ elif vibration_mm_s < VIBRATION_RANGE[0]:
+ symptoms.append("low vibration")
+
+ pressure_bar = current_readings.get("pressure_bar")
+ if pressure_bar is not None:
+ if pressure_bar > PRESSURE_RANGE[1]:
+ symptoms.append("elevated pressure")
+ elif pressure_bar < PRESSURE_RANGE[0]:
+ symptoms.append("low pressure")
+
+ return symptoms
+
+
+def build_default_review_fields(state: InvestigationState, current_readings: dict) -> dict:
+ """Pre-fill values for the human review form.
+
+ These are a starting point for a technician to edit, never something
+ auto-submitted — the model's likely_cause only becomes confirmed_cause
+ if a human leaves it unchanged and explicitly clicks save.
+ """
+ result = state.final_result or {}
+ return {
+ "confirmed_cause": result.get("likely_cause", ""),
+ "fix_applied": result.get("recommendation", ""),
+ "outcome": "resolved",
+ "notes": "\n".join(result.get("supporting_evidence") or []),
+ "symptoms": _derive_symptoms(current_readings),
+ }
+
+
+def build_incident_from_review(
+ state: InvestigationState,
+ current_readings: dict,
+ confirmed_cause: str,
+ fix_applied: str,
+ outcome: str,
+ notes: str,
+ symptoms: list[str],
+) -> Incident:
+ """Build the Incident that will actually be written to durable memory.
+
+ `diagnosis` is preserved as the model's original likely_cause for the
+ record; `confirmed_cause`/`fix_applied`/`outcome`/`notes` come from the
+ human-edited form fields, which may differ from what the model
+ suggested — that distinction is the whole point of the review step.
+ """
+ result = state.final_result or {}
+ return Incident(
+ incident_id=str(uuid.uuid4()),
+ created_at=datetime.now(),
+ machine_id=DEFAULT_MACHINE_ID,
+ symptoms=symptoms,
+ temperature_c=current_readings.get("temperature_c"),
+ vibration_mm_s=current_readings.get("vibration_mm_s"),
+ pressure_bar=current_readings.get("pressure_bar"),
+ error_code=current_readings.get("error_code"),
+ diagnosis=result.get("likely_cause", ""),
+ confirmed_cause=confirmed_cause,
+ fix_applied=fix_applied,
+ outcome=outcome,
+ notes=notes,
+ )
diff --git a/ai_agents/offline_troubleshooting_agent/agent/harness.py b/ai_agents/offline_troubleshooting_agent/agent/harness.py
new file mode 100644
index 0000000..bf564a4
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/agent/harness.py
@@ -0,0 +1,244 @@
+import json
+import os
+import uuid
+from collections.abc import Generator
+
+import ollama
+from dotenv import load_dotenv
+
+from agent.llm_client import (
+ _configured_base_url,
+ _configured_model,
+ assert_local_only,
+ get_client,
+ health_check as llm_health_check,
+)
+from agent.prompts import SYSTEM_PROMPT, build_kickoff_message
+from agent.state import InvestigationResult, InvestigationState
+from agent.tools import AgentTools
+from memory.vectorai_client import health_check as vectorai_health_check
+from simulator.history import History
+from simulator.machine import Machine
+
+load_dotenv()
+
+DEFAULT_MAX_AGENT_ROUNDS = 8
+DEFAULT_MAX_TOOL_CALLS = 20
+
+
+def _configured_max_rounds() -> int:
+ return int(os.getenv("MAX_AGENT_ROUNDS", DEFAULT_MAX_AGENT_ROUNDS))
+
+
+def _configured_max_tool_calls() -> int:
+ return int(os.getenv("MAX_TOOL_CALLS", DEFAULT_MAX_TOOL_CALLS))
+
+
+def _unreachable_result() -> dict:
+ return InvestigationResult(
+ likely_cause="Undetermined — investigation could not start",
+ confidence=0.0,
+ recommendation="Manual inspection recommended.",
+ supporting_evidence=[],
+ retrieved_incident_ids=[],
+ manual_sources=[],
+ ).model_dump()
+
+
+def _fallback_result(state: InvestigationState) -> dict:
+ return InvestigationResult(
+ likely_cause="Undetermined — investigation did not reach a conclusion",
+ confidence=0.0,
+ recommendation="Manual inspection recommended.",
+ supporting_evidence=list(state.findings),
+ retrieved_incident_ids=[
+ item["id"] for item in state.retrieved_incidents if item.get("id")
+ ],
+ manual_sources=[
+ item["section_title"]
+ for item in state.retrieved_manual_chunks
+ if item.get("section_title")
+ ],
+ ).model_dump()
+
+
+def run_investigation(
+ machine: Machine,
+ history: History,
+ objective: str,
+ max_rounds: int | None = None,
+ max_tool_calls: int | None = None,
+) -> Generator[InvestigationState, None, None]:
+ if max_rounds is None:
+ max_rounds = _configured_max_rounds()
+ if max_tool_calls is None:
+ max_tool_calls = _configured_max_tool_calls()
+
+ investigation_id = str(uuid.uuid4())
+ current_readings = machine.get_current_readings().model_dump(mode="json")
+
+ llm_status = llm_health_check()
+ if not llm_status.get("reachable") or not llm_status.get("model_available"):
+ state = InvestigationState(
+ investigation_id=investigation_id,
+ objective=objective,
+ current_readings=current_readings,
+ )
+ if not llm_status.get("reachable"):
+ state.errors.append("Ollama is not reachable — is it running?")
+ else:
+ model = _configured_model()
+ state.errors.append(
+ f"model {model} is not pulled — run `ollama pull {model}`."
+ )
+ state.final_result = _unreachable_result()
+ yield state
+ return
+
+ vectorai_status = vectorai_health_check()
+ if not vectorai_status.get("reachable"):
+ state = InvestigationState(
+ investigation_id=investigation_id,
+ objective=objective,
+ current_readings=current_readings,
+ )
+ state.errors.append(
+ "Actian VectorAI DB is not reachable — is the container running "
+ "(docker compose up -d)?"
+ )
+ state.final_result = _unreachable_result()
+ yield state
+ return
+
+ state = InvestigationState(
+ investigation_id=investigation_id,
+ objective=objective,
+ current_readings=current_readings,
+ )
+ tools = AgentTools(machine=machine, history=history, state=state)
+ dispatch = {fn.__name__: fn for fn in tools.tool_list()}
+
+ yield state
+
+ messages: list = [
+ {"role": "system", "content": SYSTEM_PROMPT},
+ {"role": "user", "content": build_kickoff_message(objective, state.current_readings)},
+ ]
+
+ base_url = _configured_base_url()
+ model = _configured_model()
+ assert_local_only(base_url, model)
+ client = get_client()
+
+ executed_signatures: set[str] = set()
+ total_tool_calls = 0
+ tool_call_limit_reached = False
+ nudge_used = False
+
+ def process_tool_calls(tool_calls):
+ nonlocal total_tool_calls, tool_call_limit_reached
+ for call in tool_calls:
+ if total_tool_calls >= max_tool_calls:
+ state.errors.append("max_tool_calls_reached")
+ tool_call_limit_reached = True
+ break
+
+ name = call.function.name
+ args = dict(call.function.arguments or {})
+ # args can contain lists (e.g. finish_investigation's
+ # supporting_evidence), which aren't hashable, so use a stable
+ # JSON string as the canonical signature instead of a tuple.
+ signature = f"{name}:{json.dumps(args, sort_keys=True, default=str)}"
+
+ if signature in executed_signatures:
+ messages.append(
+ {
+ "role": "tool",
+ "tool_name": name,
+ "content": "Skipped: identical call already made this investigation.",
+ }
+ )
+ total_tool_calls += 1
+ yield state
+ continue
+
+ executed_signatures.add(signature)
+ fn = dispatch.get(name)
+ try:
+ if fn is None:
+ raise KeyError(f"Unknown tool '{name}'")
+ result = fn(**args)
+ messages.append({"role": "tool", "tool_name": name, "content": str(result)})
+ except Exception as exc:
+ state.errors.append(f"tool_error:{name}:{exc}")
+ messages.append(
+ {"role": "tool", "tool_name": name, "content": f"Tool error: {exc}"}
+ )
+
+ total_tool_calls += 1
+ yield state
+
+ def chat_or_none():
+ """Call the model; on a mid-investigation connection loss, record a
+ clear error and return None instead of letting the exception
+ propagate out of run_investigation() and crash the caller (e.g. the
+ Gradio UI)."""
+ try:
+ return client.chat(
+ model=model, messages=messages, tools=list(dispatch.values()), think=False
+ )
+ except (ConnectionError, ollama.RequestError) as exc:
+ state.errors.append(f"llm_connection_lost_mid_investigation: {exc}")
+ return None
+
+ for _round in range(max_rounds):
+ response = chat_or_none()
+ if response is None:
+ break
+ messages.append(response.message)
+
+ tool_calls = response.message.tool_calls
+ if not tool_calls:
+ content = response.message.content or ""
+ state.errors.append(f"model_ended_without_tool_call: {content[:300]}")
+
+ if not nudge_used:
+ nudge_used = True
+ messages.append(
+ {
+ "role": "user",
+ "content": (
+ "You didn't call a tool. If your investigation is complete, "
+ "call finish_investigation now summarizing your conclusion "
+ "using the evidence you've already gathered. If you still "
+ "need more information, call the appropriate tool."
+ ),
+ }
+ )
+ response = chat_or_none()
+ if response is None:
+ break
+ messages.append(response.message)
+ tool_calls = response.message.tool_calls
+ if not tool_calls:
+ content = response.message.content or ""
+ state.errors.append(f"model_ended_without_tool_call: {content[:300]}")
+
+ if not tool_calls:
+ state.errors.append("model_ended_without_finish_investigation")
+ break
+
+ yield from process_tool_calls(tool_calls)
+
+ if tool_call_limit_reached:
+ break
+
+ if state.final_result is not None:
+ break
+ else:
+ if state.final_result is None:
+ state.errors.append("max_rounds_reached")
+
+ if state.final_result is None:
+ state.final_result = _fallback_result(state)
+ yield state
diff --git a/ai_agents/offline_troubleshooting_agent/agent/llm_client.py b/ai_agents/offline_troubleshooting_agent/agent/llm_client.py
new file mode 100644
index 0000000..067c2eb
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/agent/llm_client.py
@@ -0,0 +1,86 @@
+import os
+
+import ollama
+from dotenv import load_dotenv
+
+load_dotenv()
+
+DEFAULT_BASE_URL = "http://localhost:11434"
+DEFAULT_MODEL = "qwen3:4b-instruct"
+
+
+def _configured_base_url() -> str:
+ return os.getenv("OLLAMA_BASE_URL", DEFAULT_BASE_URL)
+
+
+def _configured_model() -> str:
+ return os.getenv("OLLAMA_MODEL", DEFAULT_MODEL)
+
+
+def _normalize_tag(name: str) -> str:
+ return name if ":" in name else f"{name}:latest"
+
+
+def assert_local_only(base_url: str, model: str) -> None:
+ if "ollama.com" in base_url.lower():
+ raise RuntimeError(
+ f"OLLAMA_BASE_URL '{base_url}' points at Ollama's cloud API. "
+ "This project must run against a local-only Ollama server."
+ )
+
+ if "cloud" in model.lower():
+ raise RuntimeError(
+ f"OLLAMA_MODEL '{model}' looks like a cloud-offload model tag. "
+ "This project must use a fully local model, not a cloud-backed one."
+ )
+
+ if os.getenv("OLLAMA_API_KEY"):
+ raise RuntimeError(
+ "OLLAMA_API_KEY is set in the environment. Cloud auth has no purpose "
+ "in this local-only setup — unset it before continuing."
+ )
+
+
+def get_client() -> ollama.Client:
+ return ollama.Client(host=_configured_base_url())
+
+
+def health_check() -> dict:
+ base_url = _configured_base_url()
+ model = _configured_model()
+ assert_local_only(base_url, model)
+
+ client = get_client()
+ try:
+ response = client.list()
+ local_models = [m.model for m in response.models]
+ reachable = True
+ except Exception:
+ local_models = []
+ reachable = False
+
+ normalized_model = _normalize_tag(model)
+ model_available = any(
+ _normalize_tag(available) == normalized_model for available in local_models
+ )
+
+ return {
+ "reachable": reachable,
+ "model_available": model_available,
+ "local_models": local_models,
+ }
+
+
+def generate_reply(prompt: str, system: str | None = None) -> str:
+ base_url = _configured_base_url()
+ model = _configured_model()
+ assert_local_only(base_url, model)
+
+ client = get_client()
+ messages = []
+ if system:
+ messages.append({"role": "system", "content": system})
+ messages.append({"role": "user", "content": prompt})
+
+ response = client.chat(model=model, messages=messages)
+ return response.message.content
diff --git a/ai_agents/offline_troubleshooting_agent/agent/prompts.py b/ai_agents/offline_troubleshooting_agent/agent/prompts.py
new file mode 100644
index 0000000..fa03985
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/agent/prompts.py
@@ -0,0 +1,55 @@
+SYSTEM_PROMPT = """You are a local equipment troubleshooting assistant for a simulated demo \
+machine. This is a simulation/demo assistant, not a certified industrial safety system.
+
+Your job during an investigation:
+- Inspect the available evidence before diagnosing anything. Use your tools to check current \
+readings, recent history, the equipment manual, and past incidents before drawing conclusions.
+- Never invent sensor readings, error codes, or other data. Only use what your tools actually \
+return.
+- Treat previous incidents retrieved from memory as context, not guaranteed truth. A similar \
+past incident is evidence to weigh, not an automatic answer — if the current readings conflict \
+with a retrieved incident, trust the current readings and say so.
+- Use the equipment manual where it is useful to support or check a possible explanation.
+- Clearly distinguish current evidence (this investigation's readings and history) from previous \
+experience (retrieved past incidents).
+- Avoid overconfidence when the evidence is weak or ambiguous. It is fine to report low \
+confidence or an inconclusive result rather than guessing.
+- Recommend inspections and normal maintenance steps, never unsafe control actions.
+- Never instruct the user to bypass interlocks, disable alarms, or otherwise bypass safety \
+mechanisms.
+- Never claim to directly control the machinery. You can only observe and recommend.
+- Stop investigating once you have enough evidence for a reasonable recommendation — you do not \
+need to call every tool or gather exhaustive evidence.
+
+Tool-use rules:
+- Do not call the same tool with the same arguments more than once in an investigation.
+- When you are done investigating, call `finish_investigation` exactly once to produce your \
+final structured recommendation. This is the only way to conclude the investigation.
+- `finish_investigation` only produces a recommendation for a human to review — it does not \
+save anything permanently. A human must separately confirm the real cause and fix before \
+anything is written to durable memory.
+
+Stopping guidance:
+- Once you have checked current readings and made at least one manual search and one \
+past-incident search, you very likely have enough to conclude — call `finish_investigation` \
+rather than searching again.
+- Do not call the same tool with the same or very similar arguments more than once. If a tool \
+result says a call was already made this investigation, that means STOP repeating it and move \
+to a different action or conclude — do not retry with slightly reworded arguments.
+- Call `save_finding` at most once or twice total per investigation, only for genuinely new \
+observations not already recorded.
+- As a firm target: aim to call `finish_investigation` within 5-6 tool calls total. \
+Investigating longer than that on a single, clearly-signaled fault is a sign you should \
+conclude with your best evidence rather than keep searching.
+"""
+
+
+def build_kickoff_message(objective: str, current_readings: dict) -> str:
+ readings_lines = "\n".join(
+ f"{key}: {value}" for key, value in current_readings.items()
+ )
+ return (
+ f"Objective: {objective}\n\n"
+ f"Current readings:\n{readings_lines}\n\n"
+ "Use your tools to investigate and produce a recommendation."
+ )
diff --git a/ai_agents/offline_troubleshooting_agent/agent/state.py b/ai_agents/offline_troubleshooting_agent/agent/state.py
new file mode 100644
index 0000000..edb5223
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/agent/state.py
@@ -0,0 +1,26 @@
+from pydantic import BaseModel, Field
+
+
+class InvestigationState(BaseModel):
+ investigation_id: str
+ objective: str
+
+ current_readings: dict = Field(default_factory=dict)
+ findings: list[str] = Field(default_factory=list)
+
+ retrieved_incidents: list[dict] = Field(default_factory=list)
+ retrieved_manual_chunks: list[dict] = Field(default_factory=list)
+
+ tool_calls: list[dict] = Field(default_factory=list)
+ errors: list[str] = Field(default_factory=list)
+
+ final_result: dict | None = None
+
+
+class InvestigationResult(BaseModel):
+ likely_cause: str
+ confidence: float
+ recommendation: str
+ supporting_evidence: list[str]
+ retrieved_incident_ids: list[str]
+ manual_sources: list[str]
diff --git a/ai_agents/offline_troubleshooting_agent/agent/tools.py b/ai_agents/offline_troubleshooting_agent/agent/tools.py
new file mode 100644
index 0000000..2ab843e
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/agent/tools.py
@@ -0,0 +1,203 @@
+from collections.abc import Callable
+from typing import Any
+
+from agent.state import InvestigationResult, InvestigationState
+from memory.incident_store import search_incidents
+from memory.manual import search_manual_chunks
+from simulator.history import History
+from simulator.machine import Machine
+
+RESULT_SUMMARY_MAX_LENGTH = 200
+
+
+class AgentTools:
+ """Bound tool methods exposed to the local LLM for a single investigation.
+
+ Wraps a running Machine simulator, its reading history, and a shared
+ InvestigationState so every call both returns a plain result to the model
+ and records its effect on the investigation state.
+ """
+
+ def __init__(self, machine: Machine, history: History, state: InvestigationState):
+ self.machine = machine
+ self.history = history
+ self.state = state
+
+ def _log_call(self, name: str, args: dict, result_summary: str) -> None:
+ summary = result_summary
+ if len(summary) > RESULT_SUMMARY_MAX_LENGTH:
+ summary = summary[: RESULT_SUMMARY_MAX_LENGTH - 3] + "..."
+ self.state.tool_calls.append({"name": name, "args": args, "result_summary": summary})
+
+ def get_current_readings(self) -> dict:
+ """Get the machine's current sensor readings.
+
+ Returns the most recent temperature, vibration, pressure, status, and
+ error code from the simulated machine. Use this first to see the
+ present state before looking at history or searching memory.
+
+ Returns:
+ dict: The current reading with keys temperature_c, vibration_mm_s,
+ pressure_bar, status, error_code, and timestamp.
+ """
+ reading = self.machine.get_current_readings()
+ result = reading.model_dump(mode="json")
+ self._log_call("get_current_readings", {}, str(result))
+ return result
+
+ def get_recent_history(self, limit: int = 20) -> list[dict]:
+ """Get recent sensor readings leading up to now.
+
+ Returns up to `limit` of the most recent readings in chronological
+ order, useful for seeing how temperature, vibration, and pressure
+ have trended over the last several steps of a developing fault.
+
+ Args:
+ limit: Maximum number of recent readings to return. Defaults to 20.
+
+ Returns:
+ list[dict]: Readings in chronological order (oldest first), each
+ with keys temperature_c, vibration_mm_s, pressure_bar, status,
+ error_code, and timestamp.
+ """
+ history_df = self.history.get_recent_history(limit=limit)
+ result = history_df.to_dict(orient="records")
+ self._log_call("get_recent_history", {"limit": limit}, f"{len(result)} readings")
+ return result
+
+ def search_manual(self, query: str, top_k: int = 3) -> list[dict]:
+ """Search the local equipment manual and troubleshooting guide.
+
+ Embeds the query locally and searches manual chunks for relevant
+ guidance on normal operating ranges, error codes, or inspection
+ steps.
+
+ Args:
+ query: A natural-language description of what you're looking
+ for, e.g. "bearing vibration warning" or "cooling fan
+ inspection".
+ top_k: Maximum number of manual chunks to return. Defaults to 3.
+
+ Returns:
+ list[dict]: Matching manual chunks, each with id, score, text,
+ section_title, source_filename, and component.
+ """
+ results = search_manual_chunks(query, top_k=top_k)
+ self.state.retrieved_manual_chunks.extend(results)
+ self._log_call(
+ "search_manual", {"query": query, "top_k": top_k}, f"{len(results)} chunks"
+ )
+ return results
+
+ def search_past_incidents(self, query: str, top_k: int = 3) -> list[dict]:
+ """Search previously resolved incidents for similar past cases.
+
+ Embeds the query locally and searches confirmed, human-verified past
+ incidents for cases with similar symptoms. Retrieved incidents are
+ evidence to weigh against current readings, not guaranteed truth —
+ they may not apply if the current evidence doesn't actually match.
+
+ Args:
+ query: A natural-language description of the current symptoms,
+ e.g. "high temperature and high vibration".
+ top_k: Maximum number of past incidents to return. Defaults to 3.
+
+ Returns:
+ list[dict]: Matching past incidents, each with id, score, and the
+ incident's stored fields (confirmed_cause, fix_applied, outcome,
+ readings, error_code, etc).
+ """
+ results = search_incidents(query, top_k=top_k)
+ self.state.retrieved_incidents.extend(results)
+ self._log_call(
+ "search_past_incidents",
+ {"query": query, "top_k": top_k},
+ f"{len(results)} incidents",
+ )
+ return results
+
+ def save_finding(self, finding: str, evidence: str) -> str:
+ """Record an important observation made during the investigation.
+
+ Use this to note a conclusion you've drawn from the evidence so far
+ (e.g. "vibration pattern matches bearing wear") along with what
+ supports it. This does not save anything permanently — it only
+ builds up the visible investigation trail for this session.
+
+ Args:
+ finding: A short statement of what you observed or concluded.
+ evidence: What specific evidence supports this finding.
+
+ Returns:
+ str: A short confirmation that the finding was recorded.
+ """
+ entry = f"{finding} (evidence: {evidence})"
+ self.state.findings.append(entry)
+ self._log_call("save_finding", {"finding": finding, "evidence": evidence}, entry)
+ return "Finding recorded."
+
+ def finish_investigation(
+ self,
+ likely_cause: str,
+ confidence: float,
+ recommendation: str,
+ supporting_evidence: list[str],
+ retrieved_incident_ids: list[str],
+ manual_sources: list[str],
+ ) -> dict:
+ """Finish the investigation and produce a structured recommendation.
+
+ Call this once you have enough evidence to give a reasonable
+ conclusion. This does NOT save anything to permanent memory — a
+ human must separately confirm the real cause and fix before
+ anything is written to durable incident memory.
+
+ Args:
+ likely_cause: The most likely root cause based on the evidence.
+ confidence: A confidence score between 0.0 and 1.0.
+ recommendation: The recommended next action (an inspection or
+ normal maintenance step, never an unsafe control action).
+ supporting_evidence: Short statements of the evidence supporting
+ this conclusion.
+ retrieved_incident_ids: IDs of past incidents that informed this
+ conclusion, if any.
+ manual_sources: Section titles from the manual that informed
+ this conclusion, if any.
+
+ Returns:
+ dict: The structured investigation result.
+ """
+ result = InvestigationResult(
+ likely_cause=likely_cause,
+ confidence=confidence,
+ recommendation=recommendation,
+ supporting_evidence=supporting_evidence,
+ retrieved_incident_ids=retrieved_incident_ids,
+ manual_sources=manual_sources,
+ )
+ result_dict = result.model_dump()
+ self.state.final_result = result_dict
+ self._log_call(
+ "finish_investigation",
+ {
+ "likely_cause": likely_cause,
+ "confidence": confidence,
+ "recommendation": recommendation,
+ "supporting_evidence": supporting_evidence,
+ "retrieved_incident_ids": retrieved_incident_ids,
+ "manual_sources": manual_sources,
+ },
+ str(result_dict),
+ )
+ return result_dict
+
+ def tool_list(self) -> list[Callable[..., Any]]:
+ """Return the bound tool methods this agent is allowed to call."""
+ return [
+ self.get_current_readings,
+ self.get_recent_history,
+ self.search_manual,
+ self.search_past_incidents,
+ self.save_finding,
+ self.finish_investigation,
+ ]
diff --git a/ai_agents/offline_troubleshooting_agent/app.py b/ai_agents/offline_troubleshooting_agent/app.py
new file mode 100644
index 0000000..d4edab3
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/app.py
@@ -0,0 +1,14 @@
+import os
+
+from dotenv import load_dotenv
+
+from ui.gradio_app import build_app
+
+load_dotenv()
+
+if __name__ == "__main__":
+ server_name = os.getenv("GRADIO_SERVER_NAME", "127.0.0.1")
+ server_port = int(os.getenv("GRADIO_SERVER_PORT", "7860"))
+
+ app = build_app()
+ app.launch(server_name=server_name, server_port=server_port)
diff --git a/ai_agents/offline_troubleshooting_agent/assets/architecture.png b/ai_agents/offline_troubleshooting_agent/assets/architecture.png
new file mode 100644
index 0000000..41679b5
Binary files /dev/null and b/ai_agents/offline_troubleshooting_agent/assets/architecture.png differ
diff --git a/ai_agents/offline_troubleshooting_agent/data/offline_test_baseline.json b/ai_agents/offline_troubleshooting_agent/data/offline_test_baseline.json
new file mode 100644
index 0000000..e433157
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/data/offline_test_baseline.json
@@ -0,0 +1,5 @@
+{
+ "incident_id": "bc455f13-34e4-4704-8854-0d9a86f40dc9",
+ "confirmed_cause": "Worn bearing in the main shaft assembly",
+ "notes": "Vibration reading of 7.91 mm/s is significantly above the normal 1.5\u20133.0 mm/s range\nTemperature is rising steadily to 91.7\u00b0C\nError code BRG-02 matches symptoms of bearing vibration warning\nPast incident with identical symptoms (high vibration and rising temperature) confirmed a worn bearing as the cause\nManual section on bearing troubleshooting recommends the same inspection and repair steps\n\nOFFLINE TEST REFERENCE INCIDENT"
+}
\ No newline at end of file
diff --git a/ai_agents/offline_troubleshooting_agent/data/persistence_test_baseline.json b/ai_agents/offline_troubleshooting_agent/data/persistence_test_baseline.json
new file mode 100644
index 0000000..b9fe98b
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/data/persistence_test_baseline.json
@@ -0,0 +1,17 @@
+{
+ "incident_id": "5c009740-f658-5b80-8f7e-c03ba01daf9a",
+ "created_at": "2026-09-23T07:18:26.960646",
+ "machine_id": "Machine A",
+ "symptoms": [
+ "persistence test marker"
+ ],
+ "temperature_c": 999.9,
+ "vibration_mm_s": 999.9,
+ "pressure_bar": 999.9,
+ "error_code": "TEST-00",
+ "diagnosis": "Not a real diagnosis \u2014 written by scripts/persistence_test.py.",
+ "confirmed_cause": "PERSISTENCE TEST MARKER - safe to ignore/delete",
+ "fix_applied": "N/A \u2014 persistence test only, no real fix.",
+ "outcome": "persistence-test",
+ "notes": "Written by scripts/persistence_test.py --mode save to verify Actian VectorAI DB data survives a container restart (section 22)."
+}
\ No newline at end of file
diff --git a/ai_agents/offline_troubleshooting_agent/data/seed_incidents.json b/ai_agents/offline_troubleshooting_agent/data/seed_incidents.json
new file mode 100644
index 0000000..4cac811
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/data/seed_incidents.json
@@ -0,0 +1,62 @@
+[
+ {
+ "incident_id": "eaca15e8-b09a-51d3-852d-efc893955a49",
+ "created_at": "2026-09-10T09:15:00",
+ "machine_id": "Machine A",
+ "symptoms": ["high temperature", "high vibration"],
+ "temperature_c": 92.0,
+ "vibration_mm_s": 8.1,
+ "pressure_bar": 5.0,
+ "error_code": "BRG-02",
+ "diagnosis": "Likely worn bearing causing elevated vibration and rising temperature.",
+ "confirmed_cause": "worn bearing",
+ "fix_applied": "bearing replacement",
+ "outcome": "resolved",
+ "notes": "Vibration and temperature returned to normal baseline after replacement."
+ },
+ {
+ "incident_id": "c43aa763-6248-5175-96e3-5ddae4391342",
+ "created_at": "2026-09-05T14:30:00",
+ "machine_id": "Machine A",
+ "symptoms": ["high temperature", "near-normal vibration"],
+ "temperature_c": 96.0,
+ "vibration_mm_s": 2.3,
+ "pressure_bar": 5.1,
+ "error_code": "TMP-04",
+ "diagnosis": "Likely cooling airflow problem given rising temperature with normal vibration and pressure.",
+ "confirmed_cause": "blocked cooling fan",
+ "fix_applied": "cleared fan obstruction",
+ "outcome": "resolved",
+ "notes": "Debris was found lodged in the cooling fan intake."
+ },
+ {
+ "incident_id": "86f0c8b4-3b36-5425-88db-eee0ee898b25",
+ "created_at": "2026-08-28T11:00:00",
+ "machine_id": "Machine A",
+ "symptoms": ["low pressure", "mildly elevated temperature"],
+ "temperature_c": 77.0,
+ "vibration_mm_s": 2.4,
+ "pressure_bar": 2.8,
+ "error_code": "PRS-03",
+ "diagnosis": "Likely pressure system leak given dropping pressure with normal vibration.",
+ "confirmed_cause": "seal leak",
+ "fix_applied": "replaced seal",
+ "outcome": "resolved",
+ "notes": "Leak traced to a worn seal on the pressure line fitting."
+ },
+ {
+ "incident_id": "4151d788-02fe-56ca-92f1-6744cd690d65",
+ "created_at": "2026-09-15T16:45:00",
+ "machine_id": "Machine A",
+ "symptoms": ["elevated vibration", "otherwise normal readings"],
+ "temperature_c": 72.0,
+ "vibration_mm_s": 4.5,
+ "pressure_bar": 5.0,
+ "error_code": null,
+ "diagnosis": "Elevated vibration with normal temperature and pressure; no error code raised.",
+ "confirmed_cause": "loose access panel",
+ "fix_applied": "panel refastened",
+ "outcome": "resolved, not a bearing issue",
+ "notes": "Vibration was traced to a loose external access panel rattling against the housing, not the bearing."
+ }
+]
diff --git a/ai_agents/offline_troubleshooting_agent/docker-compose.yml b/ai_agents/offline_troubleshooting_agent/docker-compose.yml
new file mode 100644
index 0000000..b0b1e4d
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/docker-compose.yml
@@ -0,0 +1,13 @@
+services:
+ offline-troubleshooting-vectorai:
+ image: actian/vectorai:latest
+ container_name: offline-troubleshooting-vectorai
+ ports:
+ - "6673:6573"
+ - "6674:6574"
+ - "6675:6575"
+ volumes:
+ - ./local_data:/var/lib/actian-vectorai
+ environment:
+ - ACTIAN_VECTORAI_ACCEPT_EULA=YES
+ restart: unless-stopped
diff --git a/ai_agents/offline_troubleshooting_agent/docs/BUILD_LOG.md b/ai_agents/offline_troubleshooting_agent/docs/BUILD_LOG.md
new file mode 100644
index 0000000..c71cadb
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/docs/BUILD_LOG.md
@@ -0,0 +1,83 @@
+# Build Log
+
+Progress notes for the Offline Troubleshooting Agent build, tracked against the
+14-step implementation order in `PROJECT_REFERENCE.md` section 31. This file is
+a working log, not user-facing documentation — see the README (step 14) for
+that once it exists.
+
+## Status against section 31's 14 steps
+
+Done:
+
+1. Machine simulator — `simulator/machine.py`, `simulator/scenarios.py`, `simulator/history.py`
+2. Local Gradio UI (machine status only) — `ui/gradio_app.py`, `app.py`
+3. Local Ollama connection — `agent/llm_client.py`
+4. Local embedding model — `memory/embeddings.py`
+5. Actian VectorAI DB connection — `memory/vectorai_client.py`, `docker-compose.yml`
+6. Manual ingestion and retrieval — `memory/manual.py`, `documents/*.md`
+7. Incident storage and retrieval — `memory/incident_store.py`, `models/schemas.py` (`Incident`), `data/seed_incidents.json`
+8. Agent tools — `agent/tools.py`, `agent/state.py`
+9. Agent loop — `agent/harness.py`, `agent/prompts.py`, plus Gradio wiring for Investigation/Retrieved Memory/Recommendation panels
+
+Remaining:
+
+10. Confirmation + save flow — human-in-the-loop UI that calls `memory.incident_store.save_incident()` after a technician confirms the real cause and fix (per section 17). Not built yet; `save_incident` is not reachable from the agent loop at all right now (see decision below).
+11. Persistence test — save an incident, restart the app, confirm it's still retrievable (section 22).
+12. Offline test — full network-disabled run-through per section 19 Part 3 / section 20.
+13. Automated tests — the test suite already covers most of sections 26's checklist incrementally as each piece was built (simulator, memory, manual retrieval, tools, agent behavior with mocked LLM output), but hasn't had a final pass against the full section 26 list, and `tests/test_offline_assumptions.py` doesn't exist yet.
+14. README polish — current `README.md` is still the step-1 placeholder.
+
+## Key deviations and fixes made along the way
+
+- **Docker service renamed to avoid a port collision.** The original `docker-compose.yml` used service/container name `vectorai` on host ports 6573-6575, which collided with an unrelated project's already-running container of the same name on the same ports. Renamed to `offline-troubleshooting-vectorai`, remapped to host ports 6673-6675 (container-internal ports unchanged), and updated `.env`'s `ACTIAN_VECTORAI_PORT` to `6674` accordingly. This project's own `local_data/` volume was verified to be freshly created and isolated from the other project's data.
+- **Shared `_normalize_tag` helper for untagged model names.** Ollama's `client.list()` returns fully-tagged names (e.g. `nomic-embed-text:latest`), but `.env` often configures a model without an explicit tag (e.g. `EMBEDDING_MODEL=nomic-embed-text`). A naive string-equality check between the two reports `model_available: False` even when the model is actually pulled. Fixed with a shared `_normalize_tag(name)` helper (`name` → `name:latest` when no tag is present) in `agent/llm_client.py`, reused by `memory/embeddings.py`'s `embedding_health_check()` and `agent/llm_client.py`'s own `health_check()`. Covered by a regression test in `tests/test_llm_client.py`.
+- **Protobuf version conflict resolved with a project-local `.venv` (discovered in step 5).** Installing `actian-vectorai-client` pulled in a `protobuf` version that conflicted with other tooling already installed outside the project. Rather than fight the conflict, the project was pinned to its own isolated `.venv/`, created before `pip install -r requirements.txt` and activated for every subsequent step. This keeps the project's dependency set fully isolated from whatever else is installed on the machine, and is now documented as its own setup step in the README.
+- **UUID-only `PointStruct.id` constraint (discovered in step 5).** The real `actian-vectorai-client` SDK only accepts a non-negative int or a valid UUID string as a point id — an arbitrary string (e.g. `"inc-1"`) raises a `ValidationError`. This directly shapes `Incident.incident_id`: it must always be generated as `str(uuid.uuid4())` for new incidents, or a deterministic `str(uuid.uuid5(uuid.NAMESPACE_URL, ...))` for reproducible seed data (used in `data/seed_incidents.json` and manual-chunk ids in `memory/manual.py`).
+- **JSON-based duplicate-call signature (step 9).** The agent loop's duplicate-tool-call detection originally built a signature as `(name, tuple(sorted(args.items())))`, which crashes with `TypeError: unhashable type: 'list'` the moment any tool argument is a list — which `finish_investigation` always has (`supporting_evidence`, `retrieved_incident_ids`, `manual_sources` are all lists). Fixed by using a stable JSON string (`json.dumps(args, sort_keys=True, default=str)`) as the signature instead, in `agent/harness.py`.
+
+## Architectural decision: `save_incident` is never model-callable
+
+Per section 17, nothing may be written to permanent memory until a human
+confirms it. `memory.incident_store.save_incident()` is deliberately **not**
+included in `AgentTools.tool_list()` and therefore never reaches
+`ollama.chat(tools=...)` — the model has no way to invoke it, directly or
+indirectly. This is locked in with an explicit test
+(`tests/test_tools.py::test_tool_list_does_not_include_save_incident`) so it
+can't regress silently in a later step. `save_incident` will only be called
+by step 10's human-confirmation UI flow, after a technician reviews and
+confirms (or corrects) the agent's `finish_investigation` output.
+
+## Current blocker
+
+`qwen3:4b-instruct` (the project's configured default `OLLAMA_MODEL`) has not
+been pulled yet on this machine — the pull was started but is slow over the
+current connection. As a result:
+
+- `scripts/check_agent.py` correctly exits early with a clear "model not
+ pulled" message when run against the real configured default, rather than
+ failing partway through.
+- Step 9's agent loop (`agent/harness.py`) and its Gradio wiring were
+ validated for real end-to-end behavior using two substitute local models
+ instead: `llama3.2:3b` (weaker — didn't reliably call
+ `finish_investigation`, correctly triggered the fallback path) and
+ `gemma4:e4b` (stronger — completed a full clean investigation through to
+ `finish_investigation`, all three UI panels populated correctly).
+- This gives good confidence the harness logic itself is correct (also
+ covered by fully-mocked unit tests in `tests/test_agent.py`), but step 9
+ should not be treated as **fully** closed until one real run against the
+ actual configured default (`qwen3:4b-instruct`) has been done via
+ `python scripts/check_agent.py`.
+
+## Docker container note
+
+Two Actian VectorAI containers currently exist on this machine, for two
+unrelated projects:
+
+- **This project**: `offline-troubleshooting-vectorai`, host ports
+ `6673-6675`, backed by this project's own `local_data/` directory.
+- **A different project** (`actian project/clinical-search`): container
+ `vectorai`, host ports `6573-6575`, backed by that project's own
+ `local_data/` directory.
+
+Do not stop, restart, rename, or otherwise touch the `vectorai` container —
+it belongs to the other project and is unrelated to this one.
diff --git a/ai_agents/offline_troubleshooting_agent/docs/OFFLINE_TEST_LOG_20260923T073425.md b/ai_agents/offline_troubleshooting_agent/docs/OFFLINE_TEST_LOG_20260923T073425.md
new file mode 100644
index 0000000..460a6c2
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/docs/OFFLINE_TEST_LOG_20260923T073425.md
@@ -0,0 +1,19 @@
+# Offline Test Log — ABORTED — still online
+
+Run at: 2026-09-23T07:34:25.320447
+
+```
+======================================================================
+OFFLINE TEST — network guard
+======================================================================
+Checking whether 1.1.1.1:53 is reachable...
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+STILL ONLINE — this does not look disconnected.
+A TCP connection to 1.1.1.1:53 succeeded,
+which means the network is still up. The offline test's whole point is
+proving this works with ZERO internet access, so running it now would
+prove nothing. Disconnect Wi-Fi / unplug the network, then re-run this
+script.
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+```
diff --git a/ai_agents/offline_troubleshooting_agent/docs/OFFLINE_TEST_LOG_20260923T073711.md b/ai_agents/offline_troubleshooting_agent/docs/OFFLINE_TEST_LOG_20260923T073711.md
new file mode 100644
index 0000000..b386747
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/docs/OFFLINE_TEST_LOG_20260923T073711.md
@@ -0,0 +1,19 @@
+# Offline Test Log — ABORTED — still online
+
+Run at: 2026-09-23T07:37:11.064971
+
+```
+======================================================================
+OFFLINE TEST — network guard
+======================================================================
+Checking whether 1.1.1.1:53 is reachable...
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+STILL ONLINE — this does not look disconnected.
+A TCP connection to 1.1.1.1:53 succeeded,
+which means the network is still up. The offline test's whole point is
+proving this works with ZERO internet access, so running it now would
+prove nothing. Disconnect Wi-Fi / unplug the network, then re-run this
+script.
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+```
diff --git a/ai_agents/offline_troubleshooting_agent/docs/OFFLINE_TEST_LOG_20260923T092644.md b/ai_agents/offline_troubleshooting_agent/docs/OFFLINE_TEST_LOG_20260923T092644.md
new file mode 100644
index 0000000..229979e
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/docs/OFFLINE_TEST_LOG_20260923T092644.md
@@ -0,0 +1,60 @@
+# Offline Test Log — PASS
+
+Run at: 2026-09-23T09:26:44.015261
+
+```
+======================================================================
+OFFLINE TEST — network guard
+======================================================================
+Checking whether 1.1.1.1:53 is reachable...
+OK — 1.1.1.1:53 unreachable within 2.0s. Proceeding as offline.
+
+======================================================================
+Local service health checks
+======================================================================
+Ollama / LLM: {'reachable': True, 'model_available': True, 'local_models': ['qwen3:4b-instruct', 'glm-ocr:latest', 'llama3.2:latest', 'gemma4:e4b', 'moondream:latest', 'nomic-embed-text:latest', 'llama3.2:3b']}
+Embedding model: {'reachable': True, 'model_available': True, 'local_models': ['qwen3:4b-instruct', 'glm-ocr:latest', 'llama3.2:latest', 'gemma4:e4b', 'moondream:latest', 'nomic-embed-text:latest', 'llama3.2:3b']}
+Actian VectorAI DB: {'reachable': True, 'title': 'Actian VectorAI DB', 'version': 'Actian VectorAI DB 1.0.1 / VDE 1.0.1'}
+
+======================================================================
+Triggering bearing fault
+======================================================================
+Current readings: temperature_c=91.73767338498399 vibration_mm_s=7.911920233993246 pressure_bar=4.970595871281932 status='fault' error_code='BRG-02' timestamp=datetime.datetime(2026, 9, 23, 9, 24, 29, 279283)
+
+======================================================================
+Running investigation
+======================================================================
+ [1] tool_calls so far: 1 | most recent: get_current_readings
+ [2] tool_calls so far: 2 | most recent: get_recent_history
+ [3] tool_calls so far: 3 | most recent: search_manual
+ [4] tool_calls so far: 4 | most recent: search_past_incidents
+ [5] tool_calls so far: 5 | most recent: search_manual
+ [6] tool_calls so far: 6 | most recent: search_past_incidents
+ [7] tool_calls so far: 7 | most recent: save_finding
+ [8] tool_calls so far: 8 | most recent: finish_investigation
+
+final_result: {'likely_cause': 'Worn bearing in the main shaft assembly', 'confidence': 0.95, 'recommendation': 'Inspect the bearing assembly for visible wear, play, or discoloration. Check lubrication condition and top up or replace lubricant if low or contaminated. If excessive wear is confirmed, replace the bearing. After repair, restart and confirm vibration and temperature return to normal ranges before returning the machine to service.', 'supporting_evidence': ['Current vibration reading is 8.09 mm/s, which exceeds the normal 1.5–3.0 mm/s range.', 'The BRG-02 error code is active, matching symptoms of bearing vibration warning.', 'Past incident with identical symptoms (high vibration and rising temperature) confirmed a worn bearing as the cause.', 'Manual section on bearing troubleshooting recommends the same inspection and repair steps.'], 'retrieved_incident_ids': ['eaca15e8-b09a-51d3-852d-efc893955a49', 'c43aa763-6248-5175-96e3-5ddae4391342', 'bc455f13-34e4-4704-8854-0d9a86f40dc9'], 'manual_sources': ['BRG-02 — Bearing vibration warning']}
+errors: []
+
+Reached finish_investigation: Y
+Investigation wall-clock time: 132.16s (2.2 min)
+
+======================================================================
+Checking recall of the offline-test reference incident
+======================================================================
+Baseline reference incident_id: bc455f13-34e4-4704-8854-0d9a86f40dc9
+Baseline confirmed_cause: 'Worn bearing in the main shaft assembly'
+search_incidents('bearing fault high vibration high temperature BRG-02') returned ids: ['eaca15e8-b09a-51d3-852d-efc893955a49', 'bc455f13-34e4-4704-8854-0d9a86f40dc9', '141954b3-97aa-4d33-91e1-7140b20cd76c', '4151d788-02fe-56ca-92f1-6744cd690d65', 'c43aa763-6248-5175-96e3-5ddae4391342']
+
+PASS: reference incident bc455f13-34e4-4704-8854-0d9a86f40dc9 was recalled by exact id match.
+
+======================================================================
+FINAL SUMMARY
+======================================================================
+Reached finish_investigation: Y
+Correct prior incident recalled: Y (id=bc455f13-34e4-4704-8854-0d9a86f40dc9)
+state.errors: []
+Total wall-clock time: 141.34s (2.4 min)
+
+OVERALL: PASS
+```
diff --git a/ai_agents/offline_troubleshooting_agent/docs/PROJECT_REFERENCE.md b/ai_agents/offline_troubleshooting_agent/docs/PROJECT_REFERENCE.md
new file mode 100644
index 0000000..9473622
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/docs/PROJECT_REFERENCE.md
@@ -0,0 +1,1183 @@
+# Offline Troubleshooting Agent with Actian VectorAI DB
+
+## Full Implementation Reference
+
+This document is the implementation reference for the coding agent. It expands the shorter project brief into a build-ready specification with enough detail to implement the project without guessing major product or architecture decisions.
+
+The goal is to build a fully local AI troubleshooting assistant that can diagnose simulated equipment faults, remember previous incidents, and continue using that memory after the application restarts and the internet is unavailable.
+
+The project should remain an AI engineering project, not an industrial-control project. The machine is simulated in Python. No real factory hardware, PLC integration, MQTT broker, OPC-UA, ROS stack, or industrial protocol is required for v1.
+
+## 1. Core Idea
+
+A simulated machine produces simple operational readings such as:
+
+- temperature
+- vibration
+- pressure
+- machine status
+- error code
+- timestamp
+
+The user can trigger a fault from the local UI.
+
+When a fault occurs, a local AI agent investigates by using a small set of tools:
+
+- inspect current machine readings
+- inspect recent sensor history
+- search local equipment documentation
+- search previous incidents stored in Actian VectorAI DB
+- compare current evidence with relevant previous incidents
+- produce a diagnosis and recommended action
+- save the confirmed resolution as a new persistent memory
+
+The important behavior is not simply local RAG over a manual. The agent should accumulate useful experience over time.
+
+A resolved incident becomes context for future incidents. If the application is restarted, that memory must still exist. If internet connectivity is removed, the agent must still be able to retrieve and use it.
+
+### Example
+
+First incident:
+
+```
+Temperature: 92°C
+Vibration: 8.1 mm/s
+Pressure: 5.0 bar
+Status: Warning
+```
+
+Agent investigates:
+- recent temperature trend
+- recent vibration trend
+- local manual
+- previous incidents
+
+No strong prior incident exists.
+
+Likely cause: Worn bearing
+
+Technician confirms: Bearing replaced, readings returned to normal.
+
+Incident is saved locally.
+
+Later incident:
+
+```
+Temperature: 89°C
+Vibration: 7.7 mm/s
+Pressure: 5.1 bar
+Status: Warning
+```
+
+Agent searches local memory.
+
+Similar incident found: High temperature + high vibration, Cause: worn bearing, Fix: bearing replacement, Outcome: resolved
+
+Recommendation: Inspect the bearing assembly first.
+
+The second case should still work after restarting the app with internet access disabled.
+
+## 2. What the Project Must Prove
+
+### 2.1 Local troubleshooting
+
+The agent can inspect machine data, local documentation, and local incident history without relying on cloud services.
+
+### 2.2 Persistent memory
+
+Resolved incidents are stored in Actian VectorAI DB and remain available across application restarts.
+
+### 2.3 Offline operation
+
+After all dependencies and local models have been installed, the running app can operate without internet access and still:
+
+- launch the UI
+- run the local LLM
+- generate embeddings locally
+- query Actian VectorAI DB
+- read local manuals
+- retrieve previous incidents
+- perform a new troubleshooting session
+- save a new incident
+
+## 3. Non-Goals
+
+Do not turn the project into a full industrial IoT platform.
+
+The first version does not need:
+
+- real PLC integration
+- MQTT
+- OPC-UA
+- real factory equipment
+- Raspberry Pi-specific code
+- ROS
+- computer vision
+- audio input
+- cloud LLM APIs
+- cloud embedding APIs
+- cloud-hosted vector databases
+- predictive maintenance ML models
+- real-time anomaly detection at production scale
+- autonomous control of machinery
+- multi-agent orchestration
+
+The simulated machine exists only to create believable local events for the AI agent to investigate.
+
+## 4. Recommended Tech Stack
+
+- Python: core application, simulator, tools, agent loop
+- Actian VectorAI DB: persistent local semantic memory and local vector retrieval
+- Ollama: local LLM inference
+- Local embedding model: offline embedding generation
+- Gradio: local web interface
+- Pandas: sensor history and tabular processing
+- Pydantic: structured schemas and agent state
+
+### Hardware assumption for v1
+
+The reference build should target a normal developer laptop rather than dedicated edge hardware. It must remain usable without a discrete GPU. GPU acceleration may improve speed when available, but the application should not require CUDA or a dedicated accelerator to function. Keep model size, retrieval depth, prompt size, and concurrent work conservative so the demo remains practical on limited RAM.
+
+### 4.1 Local LLM
+
+Use `qwen3:4b-instruct` through Ollama as the default model for v1. The default Ollama quantized build is roughly 2.5 GB, which keeps the project realistic for a modest laptop while still providing much stronger instruction following and tool-use behavior than older 1B-3B models.
+
+Default configuration:
+
+```
+Model: qwen3:4b-instruct
+Runtime: Ollama
+Quantization target: Q4_K_M / Ollama default quantized build
+Approximate model file size: ~2.5 GB
+```
+
+Keep the model configurable through `OLLAMA_MODEL`, but build and test the reference implementation against `qwen3:4b-instruct`.
+
+The project should be designed for constrained hardware rather than assuming a workstation-class GPU. Start with a modest context window and small retrieved payloads. Do not send entire manuals, full sensor histories, or every previous incident to the model. Retrieve only the few pieces of evidence needed for the current step.
+
+Recommended low-resource defaults:
+
+- keep the model context modest; start around 4K-8K tokens unless the laptop comfortably supports more
+- retrieve about 3 relevant manual chunks at a time
+- retrieve about 3 relevant past incidents at a time
+- keep manual chunks compact, roughly 400-800 tokens
+- summarize or truncate large tool outputs before returning them to the model
+- keep only recent tool interactions plus compact structured investigation state
+- avoid loading multiple LLMs simultaneously
+
+If `qwen3:4b-instruct` is too slow on the target laptop, allow a documented lower-resource fallback such as a small Phi-4 Mini quantized build, but do not silently change the default model.
+
+For the offline demo, the configured Ollama model must be a fully local model. Do not use Ollama cloud-backed model tags or any provider-backed fallback. Pull the model once during setup, then verify that inference still works after network access is removed.
+
+### 4.2 Embeddings
+
+Use a lightweight local embedding model. A practical default is `nomic-embed-text` through Ollama, which keeps both generation and embedding inference inside the same local runtime.
+
+Requirements:
+
+- no remote API calls during normal operation
+- lightweight enough for a modest laptop
+- suitable for semantic similarity over short incident summaries and manual chunks
+- downloaded before the offline demo
+- loadable and callable with the network disabled
+
+Keep the embedding model configurable through `EMBEDDING_MODEL`, but use `nomic-embed-text` as the reference default unless implementation testing shows a compatibility problem.
+
+### 4.3 Actian integration
+
+Use the current official Actian VectorAI DB local deployment and Python SDK/client instructions at implementation time.
+
+Do not invent package names, image tags, ports, or SDK methods if the current docs differ.
+
+The integration must support:
+
+- local database connection
+- collection/index creation
+- vector upsert
+- metadata storage
+- semantic similarity search
+- persistent local storage across restarts
+
+If Actian runs in Docker, use a mounted persistent volume so incidents are not lost when the container is restarted.
+
+## 5. High-Level Architecture
+
+```
+┌──────────────────────────────────────────────┐
+│ Gradio UI │
+│ │
+│ Machine Status | Investigation | Local Memory │
+└───────────────────────┬──────────────────────┘
+ │
+ ▼
+┌──────────────────────────────────────────────┐
+│ Troubleshooting Agent │
+│ │
+│ reasoning / tool choice / investigation state │
+└───────────────┬────────────────────────────────┘
+ │
+ ┌─────────┼──────────┬──────────────────┐
+ │ │ │ │
+ ▼ ▼ ▼ ▼
+ Current Sensor Manual Incident
+ Readings History Search Search
+ │ │ │ │
+ └─────────┴──────────┴───────────────────┘
+ │
+ ▼
+ Local data + Actian
+ │
+ ▼
+ Local Ollama model
+```
+
+No cloud service should be required during normal operation.
+
+## 6. Suggested Repository Structure
+
+```
+offline_troubleshooting_agent/
+│
+├── README.md
+├── requirements.txt
+├── .env.example
+├── app.py
+│
+├── agent/
+│ ├── __init__.py
+│ ├── harness.py
+│ ├── prompts.py
+│ ├── state.py
+│ └── tools.py
+│
+├── simulator/
+│ ├── __init__.py
+│ ├── machine.py
+│ ├── scenarios.py
+│ └── history.py
+│
+├── memory/
+│ ├── __init__.py
+│ ├── vectorai_client.py
+│ ├── embeddings.py
+│ └── incident_store.py
+│
+├── documents/
+│ ├── machine_manual.md
+│ └── troubleshooting_guide.md
+│
+├── data/
+│ ├── sensor_history.csv
+│ └── seed_incidents.json
+│
+├── models/
+│ └── schemas.py
+│
+├── ui/
+│ ├── __init__.py
+│ └── gradio_app.py
+│
+├── scripts/
+│ ├── seed_memory.py
+│ └── reset_demo.py
+│
+└── tests/
+ ├── test_simulator.py
+ ├── test_memory.py
+ ├── test_tools.py
+ ├── test_agent.py
+ └── test_offline_assumptions.py
+```
+
+The exact folder structure may be simplified, but keep the simulator, memory layer, agent logic, and UI separated.
+
+## 7. Machine Simulator
+
+The simulator should be intentionally simple and deterministic enough for demos and tests.
+
+### 7.1 Machine state
+
+Recommended fields:
+
+```
+temperature_c: float
+vibration_mm_s: float
+pressure_bar: float
+status: str
+error_code: str | None
+timestamp: datetime
+```
+
+Suggested status values:
+
+```
+running
+warning
+fault
+maintenance
+stopped
+```
+
+### 7.2 Normal operating range
+
+Example baseline:
+
+```
+Temperature: 65–75°C
+Vibration: 1.5–3.0 mm/s
+Pressure: 4.5–5.5 bar
+Status: running
+```
+
+These values are illustrative and are not meant to represent one specific real industrial machine.
+
+### 7.3 Fault scenarios
+
+Implement at least three fault types so the agent cannot simply memorize one response.
+
+#### Scenario A: Worn bearing
+
+Pattern:
+
+- temperature rises
+- vibration rises strongly
+- pressure stays normal
+
+Example state:
+
+```
+Temperature: 92°C
+Vibration: 8.0 mm/s
+Pressure: 5.0 bar
+Error code: BRG-02
+```
+
+Expected likely diagnosis: bearing wear / bearing issue
+
+Expected maintenance action: inspect bearing assembly, replace worn bearing if confirmed
+
+#### Scenario B: Cooling problem
+
+Pattern:
+
+- temperature rises
+- vibration remains near normal
+- pressure stays near normal
+
+Example state:
+
+```
+Temperature: 96°C
+Vibration: 2.3 mm/s
+Pressure: 5.1 bar
+Error code: TMP-04
+```
+
+Expected likely diagnosis: cooling airflow / cooling system problem
+
+Expected action: inspect cooling fan, vents, coolant path, or airflow
+
+#### Scenario C: Pressure loss
+
+Pattern:
+
+- pressure drops
+- temperature may be mildly elevated
+- vibration remains near normal
+
+Example state:
+
+```
+Temperature: 77°C
+Vibration: 2.4 mm/s
+Pressure: 2.8 bar
+Error code: PRS-03
+```
+
+Expected likely diagnosis: pressure leak / pressure system issue
+
+Expected action: inspect seals, hoses, fittings, or pressure path
+
+### 7.4 Simulator API
+
+Expose functions similar to:
+
+```
+get_current_readings()
+get_recent_history(limit=20)
+trigger_fault(fault_type)
+reset_machine()
+advance_simulation(steps=1)
+```
+
+The UI should allow the user to:
+
+- begin with normal operation
+- trigger one of the fault scenarios
+- reset the machine
+- optionally generate a short history leading into the fault
+
+## 8. Local Equipment Documentation
+
+Create a small fictional machine manual specifically for the demo.
+
+Do not use proprietary real-world manuals.
+
+The manual should include:
+
+- normal temperature range
+- normal vibration range
+- normal pressure range
+- error code descriptions
+- bearing troubleshooting guidance
+- cooling troubleshooting guidance
+- pressure troubleshooting guidance
+- basic safety disclaimer
+
+Example manual entry:
+
+```
+BRG-02 — Bearing vibration warning
+
+Symptoms:
+- elevated vibration
+- possible temperature increase
+
+Recommended inspection:
+1. stop the machine according to normal shutdown procedure
+2. inspect bearing assembly
+3. inspect lubrication condition
+4. replace bearing if excessive wear is confirmed
+```
+
+Split the manual into retrievable chunks during ingestion.
+
+Manual chunks and incident memories should remain logically separate even if they are stored in the same database instance.
+
+## 9. Incident Memory Model
+
+A resolved incident should be stored as structured metadata plus an embedding-friendly text representation.
+
+### 9.1 Suggested Pydantic schema
+
+```python
+class Incident(BaseModel):
+ incident_id: str
+ created_at: datetime
+ machine_id: str
+
+ symptoms: list[str]
+
+ temperature_c: float | None
+ vibration_mm_s: float | None
+ pressure_bar: float | None
+ error_code: str | None
+
+ diagnosis: str
+ confirmed_cause: str
+ fix_applied: str
+ outcome: str
+
+ notes: str | None = None
+```
+
+### 9.2 Embedding text
+
+Build a semantic representation similar to:
+
+```
+Machine: Machine A
+Symptoms: high temperature, high vibration
+Readings: temperature 92 C, vibration 8.1 mm/s, pressure 5.0 bar
+Error code: BRG-02
+Confirmed cause: worn bearing
+Fix applied: bearing replacement
+Outcome: resolved
+```
+
+Generate the embedding locally and store the vector together with the structured metadata in Actian.
+
+## 10. VectorAI DB Memory Design
+
+Prefer two logical collections/indexes if that maps cleanly to the current Actian API.
+
+### 10.1 manual_chunks
+
+Store:
+
+- chunk text
+- section title
+- source filename
+- optional component metadata
+- embedding vector
+
+### 10.2 incidents
+
+Store:
+
+- semantic incident text
+- incident ID
+- timestamp
+- diagnosis/fault type
+- readings metadata
+- confirmed resolution metadata
+- embedding vector
+
+If the current Actian setup prefers one collection plus metadata filtering, that is acceptable. Keep the logical distinction in application code.
+
+### 10.3 Similarity query
+
+For a new fault, build a query such as:
+
+```
+Machine fault with high temperature 91 C, high vibration 7.8 mm/s,
+normal pressure, error code BRG-02.
+```
+
+Retrieve the most relevant incidents.
+
+Return to the agent:
+
+- incident ID
+- relevance/similarity score if available
+- summary
+- confirmed cause
+- previous fix
+- timestamp
+
+The top vector match must not automatically become the diagnosis. Retrieved memory is evidence, not truth.
+
+## 11. Agent Responsibilities
+
+The model should decide:
+
+- what evidence it needs
+- which tool to call next
+- whether a previous incident is relevant
+- whether the manual supports or contradicts a possible explanation
+- whether the current evidence conflicts with retrieved memory
+- what diagnosis is most likely
+- what action to recommend
+- when enough evidence exists to finish
+
+Do not put the diagnosis inside the tools themselves.
+
+Avoid tools like:
+
+```
+diagnose_bearing_fault()
+find_root_cause()
+choose_fix()
+```
+
+Those would hide the interesting reasoning inside application logic.
+
+## 12. Agent Tools
+
+Recommended tool surface:
+
+**get_current_readings()** — Returns current simulated machine readings.
+
+**get_recent_history(limit=20)** — Returns recent readings in chronological order.
+
+**search_manual(query, top_k=3)** — Embeds the query locally and searches local manual chunks in Actian.
+
+**search_past_incidents(query, top_k=3)** — Searches incident memory in Actian.
+
+**save_finding(finding, evidence)** — Adds an important observation to the current investigation state.
+
+**save_incident(...)** — Called only after the user/technician confirms the real cause and fix.
+
+Save both:
+
+- structured incident metadata
+- semantic text + embedding
+
+**finish_investigation(...)** — Returns structured final output.
+
+Suggested fields:
+
+```
+likely_cause: str
+confidence: float
+recommendation: str
+supporting_evidence: list[str]
+retrieved_incident_ids: list[str]
+manual_sources: list[str]
+```
+
+## 13. Investigation State
+
+Suggested state model:
+
+```python
+class InvestigationState(BaseModel):
+ investigation_id: str
+ objective: str
+
+ current_readings: dict
+ findings: list[str]
+
+ retrieved_incidents: list[dict]
+ retrieved_manual_chunks: list[dict]
+
+ tool_calls: list[dict]
+ errors: list[str]
+
+ final_result: dict | None = None
+```
+
+Keep the state small and explicit.
+
+The first version does not need a large planning framework.
+
+## 14. Agent Loop
+
+A minimal loop is enough.
+
+```
+Receive fault / objective
+ ↓
+Send current state + tools to local LLM
+ ↓
+Model selects tool(s)
+ ↓
+Execute locally
+ ↓
+Return tool result
+ ↓
+Update investigation state
+ ↓
+Repeat
+ ↓
+finish_investigation()
+```
+
+Include:
+
+- maximum model rounds
+- maximum tool calls
+- basic duplicate-call detection
+- graceful tool error handling
+
+Do not overengineer reflection, planning graphs, or multi-agent behavior in v1.
+
+## 15. Prompt Requirements
+
+The system prompt should instruct the local model to:
+
+- act as a local equipment troubleshooting assistant
+- inspect evidence before diagnosing
+- never invent sensor readings
+- treat previous incidents as context, not guaranteed truth
+- use the manual where useful
+- distinguish current evidence from previous experience
+- avoid overconfidence when evidence is weak
+- recommend inspections rather than unsafe control actions
+- never instruct the user to bypass safety mechanisms
+- never directly control machinery
+- stop when enough evidence exists for a reasonable recommendation
+
+This is a simulation/demo assistant, not a certified industrial safety system.
+
+## 16. Gradio Interface
+
+Use Gradio locally.
+
+Do not require `share=True` or hosted Hugging Face features.
+
+The interface should have four obvious areas.
+
+### 16.1 Machine Status
+
+Display:
+
+```
+Machine A
+Temperature
+Vibration
+Pressure
+Status
+Error code
+```
+
+Controls:
+
+- Trigger Bearing Fault
+- Trigger Cooling Fault
+- Trigger Pressure Fault
+- Reset Machine
+
+A small chart of recent readings is optional but useful.
+
+### 16.2 Investigation
+
+Show only high-level agent activity and tool usage, not hidden chain-of-thought.
+
+Example:
+
+```
+✓ Checked current readings
+✓ Reviewed recent history
+✓ Searched equipment manual
+✓ Searched previous incidents
+● Comparing evidence...
+```
+
+Also show concise findings as they are saved.
+
+### 16.3 Retrieved Memory
+
+Show relevant previous incidents.
+
+Example:
+
+```
+Similar incident
+Date: 2026-09-10
+Symptoms: high temperature + high vibration
+Cause: worn bearing
+Fix: bearing replacement
+Similarity: 0.87
+```
+
+If none are useful:
+
+```
+No similar previous incident found.
+```
+
+### 16.4 Recommendation
+
+Display:
+
+- likely cause
+- confidence
+- recommendation
+- supporting evidence
+- manual references
+- past incidents used
+
+## 17. Incident Confirmation Flow
+
+Do not let the agent automatically write its own diagnosis into permanent memory as if it were ground truth.
+
+After the investigation, let the user confirm or correct the resolution.
+
+Example:
+
+```
+Agent diagnosis:
+Worn bearing
+
+Confirmed cause:
+[ Worn bearing ]
+
+Fix applied:
+[ Bearing replaced ]
+
+Outcome:
+[ Resolved ]
+
+[ Save resolved incident ]
+```
+
+The confirmed resolution is what should be written to Actian as durable memory.
+
+This prevents a bad AI guess from contaminating future retrieval.
+
+## 18. Seed Data
+
+Support two useful demo states.
+
+### 18.1 Fresh state
+
+No previous incidents.
+
+Use this for the first troubleshooting run.
+
+### 18.2 Seeded state
+
+Contains a few resolved incidents, for example:
+
+- bearing failure
+- cooling fan blockage
+- pressure leak
+- harmless vibration caused by a loose external panel
+
+Seed memories should be similar enough that semantic retrieval has to rank them meaningfully.
+
+Provide a reset script to clear or reseed the demo.
+
+## 19. Primary Demo Scenario
+
+The main demo should use the bearing fault.
+
+### Part 1: First incident
+
+1. Launch the local Gradio app.
+2. Start with normal readings.
+3. Trigger the bearing fault.
+4. Start an investigation.
+5. Agent checks readings and history.
+6. Agent searches the manual.
+7. Agent searches incident memory.
+8. No strong prior memory exists.
+9. Agent recommends inspecting the bearing.
+10. User confirms the cause was a worn bearing.
+11. User confirms bearing replacement fixed it.
+12. Save the incident to Actian.
+
+### Part 2: Persistence test
+
+1. Stop the Gradio application.
+2. Keep Actian persistent storage intact.
+3. Restart the application.
+4. Confirm the saved incident still appears in memory/search.
+
+### Part 3: Offline test
+
+1. Before disconnecting, pull `qwen3:4b-instruct` and the configured embedding model locally and run one successful inference/embedding request to confirm both are cached.
+2. Disable Wi-Fi or disconnect the network.
+3. Restart or continue the local application.
+4. Trigger a similar bearing fault.
+5. Start a new investigation.
+6. Agent searches Actian locally.
+7. Previous bearing incident is retrieved.
+8. Agent uses it as supporting context.
+9. Recommendation still works without internet.
+
+This is the main proof point of the project.
+
+## 20. Offline Requirements
+
+The coding agent must actively avoid accidental cloud dependencies.
+
+Before calling the project offline-capable, verify:
+
+- Gradio loads on localhost without internet
+- `qwen3:4b-instruct` responds through local Ollama with internet disabled
+- no Ollama cloud-backed model tag or provider fallback is configured
+- the embedding model loads and generates embeddings locally with internet disabled
+- Actian VectorAI DB is reachable locally
+- manual retrieval works locally
+- incident retrieval works locally
+- saved incident survives restart
+- no cloud API key is required for the core workflow
+
+If a model or Python library needs to download assets on first use, document that as a one-time setup step before going offline.
+
+Offline means the running application works after setup, not that installation can happen without internet.
+
+## 21. Offline Status Display
+
+The UI may show:
+
+```
+Deployment mode: LOCAL
+Internet status: OFFLINE
+Memory: Actian VectorAI DB
+LLM: Ollama
+Embeddings: Local
+```
+
+Do not make the app depend on a cloud service just to determine whether it is offline.
+
+Use a short connectivity check or a manual demo toggle if automatic network detection adds unnecessary fragility.
+
+The actual proof comes from running the demo disconnected, not from the badge itself.
+
+## 22. Persistence Test
+
+At minimum, manually or automatically validate:
+
+```
+save incident
+↓
+stop application
+↓
+restart application
+↓
+query incident memory
+↓
+incident still exists
+```
+
+If Actian runs in Docker, data must live in a persistent volume rather than the container filesystem.
+
+## 23. Memory Retrieval Tests
+
+Test semantic memory with several cases.
+
+### Exact repeat
+
+Query: `high temperature + high vibration + BRG-02`
+
+Expected: bearing incident ranks highly.
+
+### Similar wording
+
+Query: `machine running hot and shaking much more than normal`
+
+Expected: bearing incident still retrieves.
+
+### Conflicting case
+
+Query: `high temperature + normal vibration`
+
+Expected: cooling incident should outrank bearing memory if both exist.
+
+### Unrelated fault
+
+Query: `low pressure + normal vibration`
+
+Expected: pressure incident should rank ahead of bearing memory.
+
+The agent should not blindly accept the top vector result when current evidence conflicts with it.
+
+## 24. Error Handling
+
+Handle these cases cleanly:
+
+- Actian unavailable
+- Ollama unavailable
+- embedding model not downloaded
+- no manual matches
+- no incident matches
+- malformed model output
+- tool exception
+- duplicate tool call
+- max investigation rounds reached
+
+The UI should surface concise operational errors without crashing the whole application.
+
+## 25. Safety Boundaries
+
+This project is a simulation/demo.
+
+The agent must not:
+
+- directly control machinery
+- disable alarms
+- bypass interlocks
+- recommend unsafe physical actions
+- claim to replace trained maintenance staff
+
+Recommended wording:
+
+```
+Inspect the bearing assembly.
+Compare the current pattern with the previous bearing incident.
+Follow the equipment's normal shutdown and maintenance procedure.
+```
+
+Avoid unsafe wording such as:
+
+```
+Keep the machine running and remove the bearing guard.
+```
+
+## 26. Automated Tests
+
+Implement tests for the following.
+
+### Simulator
+
+- normal readings are within expected ranges
+- each fault scenario creates the intended pattern
+- reset returns the machine to normal
+
+### Incident model
+
+- required fields are enforced
+- incidents serialize and deserialize correctly
+
+### Memory
+
+- incident can be inserted
+- incident can be retrieved
+- similar wording retrieves relevant memory
+- metadata survives round-trip
+- persistence survives restart where practical
+
+### Manual retrieval
+
+- bearing query retrieves bearing guidance
+- cooling query retrieves cooling guidance
+- pressure query retrieves pressure guidance
+
+### Tools
+
+- current readings tool
+- recent history tool
+- manual search tool
+- incident search tool
+- incident save tool
+
+### Agent behavior
+
+Use mocked LLM output where useful so CI remains deterministic.
+
+### Offline assumptions
+
+Verify configured endpoints are local and the core app requires no cloud API key.
+
+## 27. Environment Configuration
+
+Suggested `.env.example`:
+
+```
+# Actian VectorAI DB
+ACTIAN_VECTORAI_HOST=
+ACTIAN_VECTORAI_PORT=
+ACTIAN_VECTORAI_INCIDENT_COLLECTION=
+ACTIAN_VECTORAI_MANUAL_COLLECTION=
+
+# Ollama
+OLLAMA_BASE_URL=http://localhost:11434
+OLLAMA_MODEL=qwen3:4b-instruct
+
+# Local embeddings
+EMBEDDING_MODEL=nomic-embed-text
+
+# Agent limits
+MAX_AGENT_ROUNDS=8
+MAX_TOOL_CALLS=20
+
+# Gradio
+GRADIO_SERVER_NAME=127.0.0.1
+GRADIO_SERVER_PORT=7860
+```
+
+Use the actual current Actian environment/configuration fields required by the official client.
+
+Do not commit secrets.
+
+## 28. README Requirements
+
+The README should explain:
+
+- what the project does
+- why local persistent memory matters
+- architecture
+- prerequisites
+- how to start Actian VectorAI DB locally
+- how to install/download the Ollama model
+- how to download/cache the embedding model
+- how to seed demo data
+- how to launch Gradio
+- how to run the first incident demo
+- how to perform the persistence test
+- how to perform the offline test
+- how to reset the demo
+- limitations
+- safety note
+
+Keep the README focused on reproducibility.
+
+## 29. Acceptance Criteria
+
+The project is ready when all of the following are true.
+
+### Functional
+
+- Gradio UI launches locally
+- machine simulator shows normal readings
+- at least 3 fault scenarios can be triggered
+- agent can inspect current readings
+- agent can inspect recent history
+- agent can search local manual content
+- agent can retrieve previous incidents
+- agent can produce a structured recommendation
+- user can confirm/correct the real cause and fix
+- confirmed incident is stored in Actian
+
+### Persistence
+
+- saved incident survives application restart
+- saved incident survives Actian container restart when using a persistent volume
+
+### Offline
+
+- application starts with internet disabled after setup
+- Ollama works offline
+- embeddings work offline
+- VectorAI search works offline
+- manual retrieval works offline
+- incident retrieval works offline
+- new incident can be saved offline
+
+### Demo quality
+
+- first bearing incident can be investigated and saved
+- second similar bearing incident retrieves the first
+- UI visibly shows retrieved memory
+- current evidence is separated from past-incident evidence
+- recommendation does not simply copy memory when current readings conflict
+
+## 30. Nice-to-Have Features
+
+Only add these after the core demo works reliably.
+
+- line chart of recent sensor readings
+- similarity scores in memory panel
+- incident timeline
+- export incident report to Markdown
+- multiple simulated machines
+- automatic fault stream
+- saved investigation history
+- resolved-incident dashboard
+- manual offline demo badge
+- selectable Ollama model
+- selectable embedding model
+
+Do not let nice-to-have features delay persistence and offline validation.
+
+## 31. Implementation Priorities
+
+Build in this order:
+
+1. machine simulator
+2. local Gradio UI
+3. local Ollama connection
+4. local embedding model
+5. Actian VectorAI DB connection
+6. manual ingestion and retrieval
+7. incident storage and retrieval
+8. agent tools
+9. agent loop
+10. confirmation + save flow
+11. persistence test
+12. offline test
+13. automated tests
+14. README polish
+
+Do not start with styling, charts, or complex agent planning.
+
+## 32. Final User Experience
+
+The finished project should be understandable without explaining the architecture first.
+
+A user opens the local Gradio app and sees a simulated machine operating normally.
+
+They trigger a fault.
+
+The agent investigates using local readings, local documentation, and Actian memory.
+
+The user confirms the real cause and fix.
+
+The incident is saved.
+
+The app is closed.
+
+The network is disconnected.
+
+The app is opened again.
+
+A similar fault is triggered.
+
+The agent retrieves the earlier incident and uses it as context for the new diagnosis.
+
+The project succeeds when the demo makes this sentence visibly true:
+
+**The AI can lose the internet without losing its memory.**
diff --git a/ai_agents/offline_troubleshooting_agent/documents/machine_manual.md b/ai_agents/offline_troubleshooting_agent/documents/machine_manual.md
new file mode 100644
index 0000000..1fbade9
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/documents/machine_manual.md
@@ -0,0 +1,58 @@
+# Machine A — Equipment Manual (Simulated)
+
+This is a fictional equipment manual written for a simulated demo machine.
+It does not describe any real industrial equipment.
+
+## Normal Operating Ranges
+
+Under normal operation, Machine A's sensors should read within the following
+ranges:
+
+- Temperature: 65–75°C
+- Vibration: 1.5–3.0 mm/s
+- Pressure: 4.5–5.5 bar
+- Status: running
+- Error code: none
+
+Readings that drift outside these ranges, or a status of "warning" or "fault",
+indicate a developing issue and warrant investigation before the condition
+worsens.
+
+## Error Codes
+
+The following error codes may appear on Machine A's control panel. Each one
+corresponds to a specific failure pattern and should be cross-referenced with
+the troubleshooting guide for detailed inspection steps.
+
+### BRG-02 — Bearing vibration warning
+
+Symptoms:
+- vibration significantly above the normal 1.5–3.0 mm/s range, often climbing
+ toward 7–8 mm/s or higher
+- temperature gradually rising above the normal range as friction increases
+- pressure remains within its normal range
+
+BRG-02 indicates the main shaft bearing assembly is showing signs of wear.
+See the troubleshooting guide's bearing section for inspection steps.
+
+### TMP-04 — Cooling system temperature warning
+
+Symptoms:
+- temperature rising well above the normal 65–75°C range, sometimes exceeding
+ 95°C
+- vibration remains near its normal range
+- pressure remains near its normal range
+
+TMP-04 indicates the cooling system is not removing heat effectively. See the
+troubleshooting guide's cooling section for inspection steps.
+
+### PRS-03 — Pressure loss warning
+
+Symptoms:
+- pressure dropping below the normal 4.5–5.5 bar range, sometimes below 3 bar
+- temperature may be mildly elevated above normal
+- vibration remains near its normal range
+
+PRS-03 indicates a loss of pressure somewhere in the system, most often from a
+seal, hose, or fitting. See the troubleshooting guide's pressure section for
+inspection steps.
diff --git a/ai_agents/offline_troubleshooting_agent/documents/troubleshooting_guide.md b/ai_agents/offline_troubleshooting_agent/documents/troubleshooting_guide.md
new file mode 100644
index 0000000..e3c636b
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/documents/troubleshooting_guide.md
@@ -0,0 +1,62 @@
+# Machine A — Troubleshooting Guide (Simulated)
+
+This is a fictional troubleshooting guide written for a simulated demo
+machine. It does not describe any real industrial equipment and should not be
+used to service real machinery.
+
+## Bearing Troubleshooting
+
+Elevated vibration, especially when paired with a gradual temperature
+increase and a normal pressure reading, points toward bearing wear (see
+BRG-02 in the equipment manual).
+
+Recommended inspection:
+1. stop the machine according to normal shutdown procedure
+2. inspect the bearing assembly for visible wear, play, or discoloration
+3. inspect the lubrication condition and top up or replace lubricant if low
+ or contaminated
+4. replace the bearing if excessive wear is confirmed
+5. after any repair, restart and confirm vibration and temperature return to
+ their normal ranges before returning the machine to service
+
+## Cooling Troubleshooting
+
+A steadily rising temperature with vibration and pressure remaining near
+normal points toward a cooling system problem rather than a mechanical fault
+(see TMP-04 in the equipment manual).
+
+Recommended inspection:
+1. stop the machine according to normal shutdown procedure
+2. inspect the cooling fan for obstruction or failure
+3. inspect intake and exhaust vents for dust or debris blockage
+4. inspect the coolant path (if equipped) for blockages or low coolant level
+5. after clearing any obstruction, restart and confirm temperature returns to
+ its normal range before returning the machine to service
+
+## Pressure Troubleshooting
+
+A drop in pressure, sometimes with mildly elevated temperature but normal
+vibration, points toward a pressure system leak (see PRS-03 in the equipment
+manual).
+
+Recommended inspection:
+1. stop the machine according to normal shutdown procedure
+2. inspect seals for cracking, hardening, or visible leakage
+3. inspect hoses and fittings for looseness or damage
+4. inspect the pressure path for any obvious external leak
+5. after resealing or replacing the affected part, restart and confirm
+ pressure returns to its normal range before returning the machine to
+ service
+
+## Safety Disclaimer
+
+This guide is for a simulated demo assistant only. It is not a certified
+industrial safety system and does not replace trained maintenance staff or
+the equipment's official documentation.
+
+Always follow the machine's normal shutdown and maintenance procedure before
+performing any inspection. Never bypass interlocks, disable alarms, or
+continue operating equipment that is showing a fault condition. Recommended
+actions in this guide are limited to inspections and standard maintenance
+steps — never a reason to remove safety guards or override safety mechanisms
+while a machine is running.
diff --git a/ai_agents/offline_troubleshooting_agent/memory/__init__.py b/ai_agents/offline_troubleshooting_agent/memory/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/ai_agents/offline_troubleshooting_agent/memory/embeddings.py b/ai_agents/offline_troubleshooting_agent/memory/embeddings.py
new file mode 100644
index 0000000..e2208b7
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/memory/embeddings.py
@@ -0,0 +1,64 @@
+import os
+
+from dotenv import load_dotenv
+
+from agent.llm_client import _normalize_tag, assert_local_only, get_client
+
+load_dotenv()
+
+DEFAULT_EMBEDDING_MODEL = "nomic-embed-text"
+DEFAULT_BASE_URL = "http://localhost:11434"
+
+
+def _configured_base_url() -> str:
+ return os.getenv("OLLAMA_BASE_URL", DEFAULT_BASE_URL)
+
+
+def _configured_embedding_model() -> str:
+ return os.getenv("EMBEDDING_MODEL", DEFAULT_EMBEDDING_MODEL)
+
+
+def embed_text(text: str) -> list[float]:
+ base_url = _configured_base_url()
+ model = _configured_embedding_model()
+ assert_local_only(base_url, model)
+
+ client = get_client()
+ response = client.embed(model=model, input=text)
+ return [float(value) for value in response.embeddings[0]]
+
+
+def embed_texts(texts: list[str]) -> list[list[float]]:
+ base_url = _configured_base_url()
+ model = _configured_embedding_model()
+ assert_local_only(base_url, model)
+
+ client = get_client()
+ response = client.embed(model=model, input=texts)
+ return [[float(value) for value in vector] for vector in response.embeddings]
+
+
+def embedding_health_check() -> dict:
+ base_url = _configured_base_url()
+ model = _configured_embedding_model()
+ assert_local_only(base_url, model)
+
+ client = get_client()
+ try:
+ response = client.list()
+ local_models = [m.model for m in response.models]
+ reachable = True
+ except Exception:
+ local_models = []
+ reachable = False
+
+ normalized_model = _normalize_tag(model)
+ model_available = any(
+ _normalize_tag(available) == normalized_model for available in local_models
+ )
+
+ return {
+ "reachable": reachable,
+ "model_available": model_available,
+ "local_models": local_models,
+ }
diff --git a/ai_agents/offline_troubleshooting_agent/memory/incident_store.py b/ai_agents/offline_troubleshooting_agent/memory/incident_store.py
new file mode 100644
index 0000000..8ce9f9c
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/memory/incident_store.py
@@ -0,0 +1,86 @@
+import os
+
+from dotenv import load_dotenv
+
+from memory.embeddings import embed_text
+from memory.vectorai_client import (
+ ensure_collection,
+ retrieve_points,
+ search as vectorai_search,
+ upsert_point,
+)
+from models.schemas import Incident
+
+load_dotenv()
+
+DEFAULT_INCIDENT_COLLECTION = "incidents"
+INCIDENT_EMBEDDING_DIM = 768
+
+
+def _configured_incident_collection() -> str:
+ return os.getenv("ACTIAN_VECTORAI_INCIDENT_COLLECTION", DEFAULT_INCIDENT_COLLECTION)
+
+
+def build_embedding_text(incident: Incident) -> str:
+ lines = [f"Machine: {incident.machine_id}"]
+
+ if incident.symptoms:
+ lines.append(f"Symptoms: {', '.join(incident.symptoms)}")
+
+ reading_parts = []
+ if incident.temperature_c is not None:
+ reading_parts.append(f"temperature {incident.temperature_c} C")
+ if incident.vibration_mm_s is not None:
+ reading_parts.append(f"vibration {incident.vibration_mm_s} mm/s")
+ if incident.pressure_bar is not None:
+ reading_parts.append(f"pressure {incident.pressure_bar} bar")
+ lines.append(
+ f"Readings: {', '.join(reading_parts)}" if reading_parts else "Readings: not recorded"
+ )
+
+ lines.append(f"Error code: {incident.error_code or 'none'}")
+ lines.append(f"Confirmed cause: {incident.confirmed_cause}")
+ lines.append(f"Fix applied: {incident.fix_applied}")
+ lines.append(f"Outcome: {incident.outcome}")
+
+ return "\n".join(lines)
+
+
+def save_incident(incident: Incident, collection: str | None = None) -> None:
+ target_collection = collection or _configured_incident_collection()
+
+ text = build_embedding_text(incident)
+ vector = embed_text(text)
+
+ ensure_collection(target_collection, dim=INCIDENT_EMBEDDING_DIM)
+ payload = incident.model_dump(mode="json")
+ upsert_point(target_collection, incident.incident_id, vector, payload)
+
+
+def get_incident(incident_id: str, collection: str | None = None) -> Incident | None:
+ target_collection = collection or _configured_incident_collection()
+ ensure_collection(target_collection, dim=INCIDENT_EMBEDDING_DIM)
+
+ results = retrieve_points(target_collection, [incident_id])
+ if not results:
+ return None
+
+ payload = results[0].get("payload")
+ if not payload:
+ return None
+
+ return Incident.model_validate(payload)
+
+
+def search_incidents(query: str, top_k: int = 3, collection: str | None = None) -> list[dict]:
+ target_collection = collection or _configured_incident_collection()
+ ensure_collection(target_collection, dim=INCIDENT_EMBEDDING_DIM)
+
+ vector = embed_text(query)
+ raw_results = vectorai_search(target_collection, vector, top_k)
+
+ results = []
+ for item in raw_results:
+ payload = item.get("payload") or {}
+ results.append({**payload, "id": item["id"], "score": item["score"]})
+ return results
diff --git a/ai_agents/offline_troubleshooting_agent/memory/manual.py b/ai_agents/offline_troubleshooting_agent/memory/manual.py
new file mode 100644
index 0000000..6bc84b0
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/memory/manual.py
@@ -0,0 +1,117 @@
+import os
+import re
+import uuid
+from pathlib import Path
+
+from dotenv import load_dotenv
+
+from memory.embeddings import embed_text, embed_texts
+from memory.vectorai_client import ensure_collection, search as vectorai_search, upsert_point
+
+load_dotenv()
+
+DEFAULT_MANUAL_COLLECTION = "manual_chunks"
+MANUAL_EMBEDDING_DIM = 768
+
+HEADING_PATTERN = re.compile(r"^(##|###)[ \t]+(.*)$", re.MULTILINE)
+H1_PATTERN = re.compile(r"^#[ \t]+(.*)$", re.MULTILINE)
+
+
+def _configured_manual_collection() -> str:
+ return os.getenv("ACTIAN_VECTORAI_MANUAL_COLLECTION", DEFAULT_MANUAL_COLLECTION)
+
+
+def _first_h1_title(text: str) -> str | None:
+ match = H1_PATTERN.search(text)
+ return match.group(1).strip() if match else None
+
+
+def _derive_component(heading: str, text: str) -> str:
+ haystack = f"{heading} {text}".lower()
+ if "bearing" in haystack or "brg" in haystack:
+ return "bearing"
+ if "cooling" in haystack or "tmp" in haystack:
+ return "cooling"
+ if "pressure" in haystack or "prs" in haystack:
+ return "pressure"
+ return "general"
+
+
+def _build_chunk(body: str, section_title: str, source_filename: str) -> dict:
+ return {
+ "text": body,
+ "section_title": section_title,
+ "source_filename": source_filename,
+ "component": _derive_component(section_title, body),
+ }
+
+
+def chunk_markdown_file(path: str) -> list[dict]:
+ text = Path(path).read_text(encoding="utf-8")
+ source_filename = Path(path).name
+
+ matches = list(HEADING_PATTERN.finditer(text))
+ chunks: list[dict] = []
+
+ preamble_end = matches[0].start() if matches else len(text)
+ preamble = text[:preamble_end].strip()
+ if preamble:
+ title = _first_h1_title(preamble) or "Introduction"
+ chunks.append(_build_chunk(preamble, title, source_filename))
+
+ for index, match in enumerate(matches):
+ start = match.start()
+ end = matches[index + 1].start() if index + 1 < len(matches) else len(text)
+ section_title = match.group(2).strip()
+ body = text[start:end].strip()
+ chunks.append(_build_chunk(body, section_title, source_filename))
+
+ return chunks
+
+
+def ingest_manual_documents(paths: list[str]) -> int:
+ collection = _configured_manual_collection()
+ ensure_collection(collection, dim=MANUAL_EMBEDDING_DIM)
+
+ total = 0
+ for path in paths:
+ chunks = chunk_markdown_file(path)
+ if not chunks:
+ continue
+
+ vectors = embed_texts([chunk["text"] for chunk in chunks])
+
+ for chunk, vector in zip(chunks, vectors):
+ point_id = str(
+ uuid.uuid5(
+ uuid.NAMESPACE_URL,
+ f"{chunk['source_filename']}:{chunk['section_title']}",
+ )
+ )
+ upsert_point(collection, point_id, vector, chunk)
+
+ total += len(chunks)
+
+ return total
+
+
+def search_manual_chunks(query: str, top_k: int = 3) -> list[dict]:
+ collection = _configured_manual_collection()
+ ensure_collection(collection, dim=MANUAL_EMBEDDING_DIM)
+ vector = embed_text(query)
+ raw_results = vectorai_search(collection, vector, top_k)
+
+ results = []
+ for item in raw_results:
+ payload = item.get("payload") or {}
+ results.append(
+ {
+ "id": item["id"],
+ "score": item["score"],
+ "text": payload.get("text"),
+ "section_title": payload.get("section_title"),
+ "source_filename": payload.get("source_filename"),
+ "component": payload.get("component"),
+ }
+ )
+ return results
diff --git a/ai_agents/offline_troubleshooting_agent/memory/vectorai_client.py b/ai_agents/offline_troubleshooting_agent/memory/vectorai_client.py
new file mode 100644
index 0000000..7ec4637
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/memory/vectorai_client.py
@@ -0,0 +1,89 @@
+import os
+
+from actian_vectorai import Distance, PointStruct, VectorAIClient, VectorParams
+from dotenv import load_dotenv
+
+load_dotenv()
+
+DEFAULT_HOST = "localhost"
+DEFAULT_PORT = "6574"
+
+
+def _configured_host() -> str:
+ return os.getenv("ACTIAN_VECTORAI_HOST", DEFAULT_HOST)
+
+
+def _configured_port() -> str:
+ return os.getenv("ACTIAN_VECTORAI_PORT", DEFAULT_PORT)
+
+
+def get_client() -> VectorAIClient:
+ url = f"{_configured_host()}:{_configured_port()}"
+ client = VectorAIClient(url)
+ client.connect()
+ return client
+
+
+def health_check() -> dict:
+ try:
+ client = get_client()
+ result = client.health_check()
+ return {"reachable": True, **result}
+ except Exception as exc:
+ return {"reachable": False, "error": str(exc)}
+
+
+def open_collection(name: str) -> None:
+ """Open a collection for read/write, reattaching to its on-disk data.
+
+ `client.collections.list()`/`exists()` reflect what's on disk, but a
+ collection isn't actually queryable after a server restart until it's
+ explicitly reopened here — the metadata and query-serving paths are
+ separate concerns in this engine. Verified empirically against the
+ installed SDK: calling this on a collection that's already open is a
+ no-op that returns True and raises nothing; only a genuinely
+ nonexistent collection raises CollectionNotFoundError.
+ """
+ client = get_client()
+ client.vde.open_collection(name)
+
+
+def ensure_collection(name: str, dim: int = 768) -> None:
+ client = get_client()
+
+ if client.collections.exists(name):
+ open_collection(name)
+ return
+
+ vectors_config = VectorParams(size=dim, distance=Distance.Cosine)
+ client.collections.create(name, vectors_config=vectors_config)
+ open_collection(name)
+
+
+def upsert_point(collection: str, point_id: int | str, vector: list[float], payload: dict) -> None:
+ client = get_client()
+ point = PointStruct(id=point_id, vector=vector, payload=payload)
+ client.points.upsert(collection, [point])
+
+
+def search(collection: str, vector: list[float], top_k: int = 5) -> list[dict]:
+ client = get_client()
+ raw_results = client.points.search(collection, vector=vector, limit=top_k)
+ return [
+ {"id": result.id, "score": result.score, "payload": result.payload}
+ for result in raw_results
+ ]
+
+
+def retrieve_points(collection: str, ids: list[str]) -> list[dict]:
+ client = get_client()
+ raw_results = client.points.get(collection, ids)
+ return [
+ {"id": result.id, "score": None, "payload": result.payload}
+ for result in raw_results
+ ]
+
+
+def delete_collection(name: str) -> None:
+ client = get_client()
+ client.collections.delete(name, strict=False)
diff --git a/ai_agents/offline_troubleshooting_agent/models/__init__.py b/ai_agents/offline_troubleshooting_agent/models/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/ai_agents/offline_troubleshooting_agent/models/schemas.py b/ai_agents/offline_troubleshooting_agent/models/schemas.py
new file mode 100644
index 0000000..f8ccf77
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/models/schemas.py
@@ -0,0 +1,35 @@
+from datetime import datetime
+from typing import Literal
+
+from pydantic import BaseModel
+
+FaultType = Literal["bearing", "cooling", "pressure"]
+
+
+class MachineReading(BaseModel):
+ temperature_c: float
+ vibration_mm_s: float
+ pressure_bar: float
+ status: str
+ error_code: str | None
+ timestamp: datetime
+
+
+class Incident(BaseModel):
+ incident_id: str
+ created_at: datetime
+ machine_id: str
+
+ symptoms: list[str]
+
+ temperature_c: float | None
+ vibration_mm_s: float | None
+ pressure_bar: float | None
+ error_code: str | None
+
+ diagnosis: str
+ confirmed_cause: str
+ fix_applied: str
+ outcome: str
+
+ notes: str | None = None
diff --git a/ai_agents/offline_troubleshooting_agent/requirements.txt b/ai_agents/offline_troubleshooting_agent/requirements.txt
new file mode 100644
index 0000000..659fa0d
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/requirements.txt
@@ -0,0 +1,7 @@
+pydantic>=2.10
+pandas
+pytest
+gradio
+python-dotenv
+ollama
+actian-vectorai-client
diff --git a/ai_agents/offline_troubleshooting_agent/scripts/check_actian.py b/ai_agents/offline_troubleshooting_agent/scripts/check_actian.py
new file mode 100644
index 0000000..88f6067
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/scripts/check_actian.py
@@ -0,0 +1,76 @@
+import os
+import sys
+import uuid
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from memory.vectorai_client import ( # noqa: E402
+ delete_collection,
+ ensure_collection,
+ health_check,
+ search,
+ upsert_point,
+)
+
+TEST_COLLECTION = "scratch_test_collection"
+TEST_DIM = 8
+TEST_VECTOR = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]
+# actian-vectorai-client's PointStruct only accepts a non-negative int or a
+# valid UUID string as an id — an arbitrary string like "scratch-point-1" is
+# rejected with a ValidationError.
+TEST_POINT_ID = str(uuid.uuid4())
+
+
+def main() -> None:
+ print("Checking local Actian VectorAI DB setup...")
+ result = health_check()
+ print(f"health_check result: {result}")
+
+ if not result["reachable"]:
+ print(
+ "\nFAIL: could not reach Actian VectorAI DB. "
+ "Make sure it is running (docker compose up -d) and try again."
+ )
+ return
+
+ # Delete any leftover scratch collection from a previous run first: this
+ # script always upserts the identical TEST_VECTOR, so a stale point from
+ # an earlier run would tie with today's fresh point at cosine similarity
+ # 1.0 and could win the top-1 slot non-deterministically (found during
+ # the persistence-fix verification).
+ print(f"\nClearing any leftover '{TEST_COLLECTION}' from a previous run...")
+ delete_collection(TEST_COLLECTION)
+
+ print(f"Ensuring collection '{TEST_COLLECTION}' exists (dim={TEST_DIM})...")
+ ensure_collection(TEST_COLLECTION, dim=TEST_DIM)
+
+ print(f"Upserting a dummy point (id={TEST_POINT_ID})...")
+ upsert_point(
+ TEST_COLLECTION,
+ TEST_POINT_ID,
+ TEST_VECTOR,
+ {"note": "check_actian.py smoke test point"},
+ )
+
+ print("Searching for it with the same vector...")
+ raw_top_result = search(TEST_COLLECTION, TEST_VECTOR, top_k=1)
+ print(f"normalized search result: {raw_top_result}")
+
+ if not raw_top_result:
+ print("\nFAIL: search returned no results.")
+ return
+
+ top = raw_top_result[0]
+ if str(top["id"]) != TEST_POINT_ID:
+ print(f"\nFAIL: expected top result id {TEST_POINT_ID!r}, got {top['id']!r}.")
+ return
+
+ print("\nPASS: Actian VectorAI DB is reachable, and upsert/search round-tripped correctly.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ai_agents/offline_troubleshooting_agent/scripts/check_agent.py b/ai_agents/offline_troubleshooting_agent/scripts/check_agent.py
new file mode 100644
index 0000000..0b26cb6
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/scripts/check_agent.py
@@ -0,0 +1,65 @@
+import os
+import sys
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from agent.harness import run_investigation # noqa: E402
+from agent.llm_client import health_check # noqa: E402
+from simulator.machine import Machine # noqa: E402
+from simulator.scenarios import FAULT_TARGETS, trigger_fault # noqa: E402
+
+
+def main() -> None:
+ print("Checking Ollama availability before running a real investigation...")
+ status = health_check()
+ print(f"health_check result: {status}")
+
+ if not status["reachable"]:
+ print("\nFAIL: Ollama is not reachable. Is it running?")
+ return
+
+ if not status["model_available"]:
+ print(
+ "\nFAIL: the configured OLLAMA_MODEL is not pulled locally yet. "
+ "Run `ollama pull qwen3:4b-instruct` (or your configured model) and try again."
+ )
+ return
+
+ print("\nSetting up simulated bearing fault...")
+ machine = Machine(seed=7)
+ trigger_fault(machine, "bearing")
+ machine.advance_simulation(steps=FAULT_TARGETS["bearing"].total_steps + 2)
+
+ print("Running investigation...\n")
+ final_state = None
+ for state in run_investigation(
+ machine, machine.history, "Investigate bearing fault on Machine A"
+ ):
+ final_state = state
+ last_call = state.tool_calls[-1]["name"] if state.tool_calls else "(none yet)"
+ print(f" tool_calls so far: {len(state.tool_calls)} | most recent: {last_call}")
+
+ print("\n--- final_result ---")
+ print(final_state.final_result)
+
+ print("\n--- errors ---")
+ print(final_state.errors)
+
+ ok = final_state.final_result is not None and not any(
+ error in ("model_ended_without_finish_investigation", "max_rounds_reached")
+ for error in final_state.errors
+ )
+ print(
+ "\nPASS: investigation reached a conclusion via finish_investigation."
+ if ok
+ else "\nFAIL: investigation did not cleanly reach finish_investigation "
+ "(see errors above — a fallback result was used)."
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ai_agents/offline_troubleshooting_agent/scripts/check_embeddings.py b/ai_agents/offline_troubleshooting_agent/scripts/check_embeddings.py
new file mode 100644
index 0000000..cc0c7b8
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/scripts/check_embeddings.py
@@ -0,0 +1,36 @@
+import os
+import sys
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from memory.embeddings import embed_text, embedding_health_check # noqa: E402
+
+
+def main() -> None:
+ print("Checking local embedding model setup...")
+ result = embedding_health_check()
+
+ print(f"reachable: {result['reachable']}")
+ print(f"model_available: {result['model_available']}")
+ print(f"local_models: {result['local_models']}")
+
+ if not result["reachable"]:
+ print("\nFAIL: could not reach the local Ollama server.")
+ return
+
+ if not result["model_available"]:
+ print("\nFAIL: configured EMBEDDING_MODEL is not pulled locally yet.")
+ return
+
+ vector = embed_text("bearing overheating vibration")
+ print(f"\nvector length: {len(vector)}")
+ print(f"first 5 values: {vector[:5]}")
+ print("\nPASS: embedding model is reachable, available, and generated a vector.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ai_agents/offline_troubleshooting_agent/scripts/check_ollama.py b/ai_agents/offline_troubleshooting_agent/scripts/check_ollama.py
new file mode 100644
index 0000000..7a45604
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/scripts/check_ollama.py
@@ -0,0 +1,35 @@
+import os
+import sys
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from agent.llm_client import generate_reply, health_check # noqa: E402
+
+
+def main() -> None:
+ print("Checking local Ollama setup...")
+ result = health_check()
+
+ print(f"reachable: {result['reachable']}")
+ print(f"model_available: {result['model_available']}")
+ print(f"local_models: {result['local_models']}")
+
+ if not result["reachable"]:
+ print("\nFAIL: could not reach the local Ollama server.")
+ return
+
+ if not result["model_available"]:
+ print("\nFAIL: configured OLLAMA_MODEL is not pulled locally yet.")
+ return
+
+ reply = generate_reply("Say OK if you can read this.")
+ print(f"\nmodel reply: {reply!r}")
+ print("\nPASS: Ollama is reachable, the model is available, and it responded.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ai_agents/offline_troubleshooting_agent/scripts/check_tools.py b/ai_agents/offline_troubleshooting_agent/scripts/check_tools.py
new file mode 100644
index 0000000..e949b9c
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/scripts/check_tools.py
@@ -0,0 +1,80 @@
+import json
+import os
+import sys
+import uuid
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from agent.state import InvestigationState # noqa: E402
+from agent.tools import AgentTools # noqa: E402
+from simulator.machine import Machine # noqa: E402
+from simulator.scenarios import FAULT_TARGETS, trigger_fault # noqa: E402
+
+
+def main() -> None:
+ print("Setting up simulated bearing fault...")
+ machine = Machine(seed=42)
+ trigger_fault(machine, "bearing")
+ machine.advance_simulation(steps=FAULT_TARGETS["bearing"].total_steps + 2)
+
+ state = InvestigationState(
+ investigation_id=str(uuid.uuid4()),
+ objective="Investigate bearing fault",
+ )
+ tools = AgentTools(machine=machine, history=machine.history, state=state)
+
+ print("\n--- get_current_readings ---")
+ readings = tools.get_current_readings()
+ print(readings)
+
+ print("\n--- get_recent_history(limit=10) ---")
+ history = tools.get_recent_history(limit=10)
+ print(f"{len(history)} readings returned")
+
+ print("\n--- search_manual('bearing') ---")
+ manual_results = tools.search_manual("bearing")
+ for result in manual_results:
+ print(f" score={result['score']:.4f} section_title={result['section_title']!r}")
+
+ print("\n--- search_past_incidents('bearing overheating') ---")
+ incident_results = tools.search_past_incidents("bearing overheating")
+ for result in incident_results:
+ print(f" score={result['score']:.4f} confirmed_cause={result.get('confirmed_cause')!r}")
+
+ print("\n--- save_finding(...) ---")
+ finding_confirmation = tools.save_finding(
+ "vibration and temperature both elevated, pressure normal",
+ f"current readings: {readings}",
+ )
+ print(finding_confirmation)
+
+ print("\n--- finish_investigation(...) ---")
+ final_result = tools.finish_investigation(
+ likely_cause="worn bearing",
+ confidence=0.75,
+ recommendation="Inspect the bearing assembly and lubrication condition.",
+ supporting_evidence=[
+ "vibration and temperature both elevated, pressure normal",
+ ],
+ retrieved_incident_ids=[r["id"] for r in incident_results],
+ manual_sources=[r["section_title"] for r in manual_results],
+ )
+ print(final_result)
+
+ print("\n--- final investigation state ---")
+ print(json.dumps(state.model_dump(mode="json"), indent=2, default=str))
+
+ ok = (
+ len(state.tool_calls) == 6
+ and len(state.findings) == 1
+ and state.final_result is not None
+ )
+ print("\nPASS: all six tools ran and state accumulated correctly." if ok else "\nFAIL: state did not accumulate as expected.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ai_agents/offline_troubleshooting_agent/scripts/diagnose_agent_speed.py b/ai_agents/offline_troubleshooting_agent/scripts/diagnose_agent_speed.py
new file mode 100644
index 0000000..c57506e
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/scripts/diagnose_agent_speed.py
@@ -0,0 +1,345 @@
+"""Diagnostic-only script: why is a real investigation against
+qwen3:4b-instruct so slow on this hardware?
+
+This does NOT fix anything. It measures five things in order and prints a
+report as it goes, so partial results are visible even if a later step
+hangs. See the numbered sections below.
+"""
+
+import json
+import os
+import sys
+import time
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from agent.llm_client import ( # noqa: E402
+ _configured_base_url,
+ _configured_model,
+ assert_local_only,
+ get_client,
+)
+from agent.prompts import SYSTEM_PROMPT, build_kickoff_message # noqa: E402
+from agent.state import InvestigationState # noqa: E402
+from agent.tools import AgentTools # noqa: E402
+from simulator.machine import Machine # noqa: E402
+from simulator.scenarios import FAULT_TARGETS, trigger_fault # noqa: E402
+
+
+def _header(title: str) -> None:
+ print("\n" + "=" * 78)
+ print(title)
+ print("=" * 78, flush=True)
+
+
+def _thinking_info(message) -> tuple[bool, int]:
+ thinking = getattr(message, "thinking", None)
+ length = len(thinking) if thinking else 0
+ return bool(thinking), length
+
+
+def step1_baseline() -> float:
+ _header("STEP 1: Baseline bare-model latency (no tools attached)")
+ client = get_client()
+ model = _configured_model()
+ print(f"model={model}")
+
+ messages = [{"role": "user", "content": "Say OK."}]
+ start = time.monotonic()
+ response = client.chat(model=model, messages=messages, think=False)
+ elapsed = time.monotonic() - start
+
+ has_thinking, thinking_len = _thinking_info(response.message)
+
+ print(f"\nElapsed: {elapsed:.2f}s")
+ print(f"Response content: {response.message.content!r}")
+ print(f"message.thinking populated despite think=False: {has_thinking} (length={thinking_len} chars)")
+ if has_thinking:
+ print(f"thinking excerpt: {response.message.thinking[:300]!r}")
+ return elapsed
+
+
+def step2_with_tools() -> float:
+ _header("STEP 2: Bare model + full tool schema, still one round")
+ client = get_client()
+ model = _configured_model()
+
+ machine = Machine(seed=99)
+ state = InvestigationState(
+ investigation_id="diag-step2",
+ objective="diagnostic",
+ current_readings=machine.get_current_readings().model_dump(mode="json"),
+ )
+ tools = AgentTools(machine=machine, history=machine.history, state=state)
+ tool_list = tools.tool_list()
+ print(f"attaching {len(tool_list)} tool schemas: {[fn.__name__ for fn in tool_list]}")
+
+ messages = [{"role": "user", "content": "Say OK."}]
+ start = time.monotonic()
+ response = client.chat(model=model, messages=messages, tools=tool_list, think=False)
+ elapsed = time.monotonic() - start
+
+ has_thinking, thinking_len = _thinking_info(response.message)
+
+ print(f"\nElapsed: {elapsed:.2f}s")
+ print(f"Response content: {response.message.content!r}")
+ print(f"tool_calls made (unprompted, unusual if any): {response.message.tool_calls}")
+ print(f"message.thinking populated: {has_thinking} (length={thinking_len} chars)")
+ return elapsed
+
+
+def step3_model_residency() -> None:
+ _header("STEP 3: Is the model staying loaded between calls?")
+ client = get_client()
+ model = _configured_model()
+
+ keep_alive_env = os.getenv("OLLAMA_KEEP_ALIVE")
+ print(f"OLLAMA_KEEP_ALIVE env var: {keep_alive_env!r} (Ollama's own default is 5m if unset)")
+
+ ps1 = client.ps()
+ print("\nollama.ps() immediately after step 1/2 calls:")
+ if not ps1.models:
+ print(" (no models currently loaded)")
+ for m in ps1.models:
+ print(f" - {m.model}: size_vram={getattr(m, 'size_vram', 'n/a')}, expires_at={getattr(m, 'expires_at', 'n/a')}")
+
+ print("\nWaiting 10 seconds...")
+ time.sleep(10)
+
+ ps2 = client.ps()
+ print("ollama.ps() after ~10s pause:")
+ if not ps2.models:
+ print(" (no models currently loaded)")
+ for m in ps2.models:
+ print(f" - {m.model}: size_vram={getattr(m, 'size_vram', 'n/a')}, expires_at={getattr(m, 'expires_at', 'n/a')}")
+
+ still_loaded = any(model in m.model or m.model in model for m in ps2.models)
+ print(f"\n{model!r} still shown as loaded after 10s pause: {still_loaded}")
+
+ # Cross-check against Ollama's own server log for actual reload events —
+ # more reliable than inferring eviction from two ps() snapshots 10s apart,
+ # since real investigation rounds are spaced much further apart than 10s.
+ log_path = os.path.join(
+ os.environ.get("LOCALAPPDATA", ""), "Ollama", "server.log"
+ )
+ print(f"\nChecking Ollama server log for model (re)load events: {log_path}")
+ if os.path.isfile(log_path):
+ try:
+ with open(log_path, encoding="utf-8", errors="replace") as fh:
+ lines = fh.readlines()
+ load_lines = [
+ line.strip() for line in lines if "load_tensors: offloaded" in line
+ ]
+ print(f"Found {len(load_lines)} 'load_tensors: offloaded' events in the log so far this session.")
+ print("Last 10 (each one is a full model (re)load into memory/VRAM):")
+ for line in load_lines[-10:]:
+ print(f" {line}")
+ if len(load_lines) >= 2:
+ print(
+ "\nIf this count keeps climbing by more than 1 per investigation "
+ "round, the model is being evicted and reloaded repeatedly — "
+ "each reload re-reads the model file from disk and re-uploads "
+ "layers to GPU, which is real wall-clock cost on top of inference."
+ )
+ except OSError as exc:
+ print(f"Could not read log file: {exc}")
+ else:
+ print("Log file not found at that path — skipping log cross-check.")
+
+
+def _message_char_count(messages: list) -> int:
+ total = 0
+ for m in messages:
+ if isinstance(m, dict):
+ total += len(str(m.get("content", "")))
+ else:
+ total += len(str(getattr(m, "content", "") or ""))
+ return total
+
+
+def step4_instrumented_investigation() -> None:
+ _header("STEP 4: Real investigation, instrumented (bearing fault)")
+ print(
+ "Note: this is a throwaway, instrumented re-implementation of "
+ "agent/harness.py's loop for measurement only — it omits the "
+ "no-tool-call nudge retry (unrelated to timing) and is NOT a "
+ "replacement for the real harness. agent/harness.py itself is "
+ "untouched.\n"
+ )
+
+ machine = Machine(seed=7)
+ trigger_fault(machine, "bearing")
+ machine.advance_simulation(steps=FAULT_TARGETS["bearing"].total_steps + 2)
+
+ objective = "Investigate bearing fault on Machine A"
+ current_readings = machine.get_current_readings().model_dump(mode="json")
+ state = InvestigationState(
+ investigation_id="diag-step4",
+ objective=objective,
+ current_readings=current_readings,
+ )
+ tools = AgentTools(machine=machine, history=machine.history, state=state)
+ dispatch = {fn.__name__: fn for fn in tools.tool_list()}
+
+ base_url = _configured_base_url()
+ model = _configured_model()
+ assert_local_only(base_url, model)
+ client = get_client()
+
+ messages: list = [
+ {"role": "system", "content": SYSTEM_PROMPT},
+ {"role": "user", "content": build_kickoff_message(objective, current_readings)},
+ ]
+
+ max_rounds = int(os.getenv("MAX_AGENT_ROUNDS", 8))
+ max_tool_calls = int(os.getenv("MAX_TOOL_CALLS", 20))
+ executed_signatures: set[str] = set()
+ total_tool_calls = 0
+ round_chat_times: list[float] = []
+
+ investigation_start = time.monotonic()
+
+ for round_num in range(1, max_rounds + 1):
+ msg_chars = _message_char_count(messages)
+ print(f"\n--- Round {round_num} ---")
+ print(f"messages so far: {len(messages)} entries, ~{msg_chars} chars total (rough token proxy)")
+
+ chat_start = time.monotonic()
+ response = client.chat(model=model, messages=messages, tools=list(dispatch.values()), think=False)
+ chat_elapsed = time.monotonic() - chat_start
+ round_chat_times.append(chat_elapsed)
+ print(f"ollama.chat() wall-clock time: {chat_elapsed:.2f}s")
+
+ has_thinking, thinking_len = _thinking_info(response.message)
+ print(f"message.thinking populated: {has_thinking} (length={thinking_len} chars)")
+
+ messages.append(response.message)
+ tool_calls = response.message.tool_calls
+
+ if not tool_calls:
+ content = response.message.content or ""
+ print(f"No tool calls this round. content: {content[:300]!r}")
+ print("(the real harness would attempt one nudge retry here — skipped in this diagnostic)")
+ break
+
+ for call in tool_calls:
+ if total_tool_calls >= max_tool_calls:
+ print("max_tool_calls reached mid-round — stopping.")
+ break
+
+ name = call.function.name
+ args = dict(call.function.arguments or {})
+ signature = f"{name}:{json.dumps(args, sort_keys=True, default=str)}"
+ print(f" tool_call: {name}({args})")
+
+ if signature in executed_signatures:
+ print(" -> duplicate signature, skipped (not re-executed)")
+ messages.append(
+ {
+ "role": "tool",
+ "tool_name": name,
+ "content": "Skipped: identical call already made this investigation.",
+ }
+ )
+ total_tool_calls += 1
+ continue
+
+ executed_signatures.add(signature)
+ fn = dispatch.get(name)
+ tool_start = time.monotonic()
+ try:
+ result = fn(**args) if fn else f"Unknown tool '{name}'"
+ messages.append({"role": "tool", "tool_name": name, "content": str(result)})
+ except Exception as exc: # noqa: BLE001
+ messages.append({"role": "tool", "tool_name": name, "content": f"Tool error: {exc}"})
+ tool_elapsed = time.monotonic() - tool_start
+ print(f" tool execution time (Python function, not the model): {tool_elapsed:.3f}s")
+
+ total_tool_calls += 1
+
+ if state.final_result is not None:
+ print("\nfinish_investigation reached — stopping instrumented loop.")
+ break
+
+ if total_tool_calls >= max_tool_calls:
+ print("\nmax_tool_calls reached — stopping instrumented loop.")
+ break
+
+ total_elapsed = time.monotonic() - investigation_start
+
+ _header("STEP 4 SUMMARY")
+ print(f"Total instrumented investigation wall-clock time: {total_elapsed:.2f}s ({total_elapsed / 60:.1f} min)")
+ print(f"Per-round ollama.chat() times (s): {[round(t, 2) for t in round_chat_times]}")
+ if round_chat_times:
+ avg = sum(round_chat_times) / len(round_chat_times)
+ max_t = max(round_chat_times)
+ print(f" average: {avg:.2f}s, max: {max_t:.2f}s ({'outlier present' if max_t > 2 * avg else 'roughly uniform'})")
+ if state.final_result:
+ print(f"\nfinal_result: {state.final_result}")
+ else:
+ print("\nNo final_result produced within this diagnostic run's round limit.")
+
+
+def step5_system_basics() -> None:
+ _header("STEP 5: System basics")
+
+ try:
+ import psutil
+
+ total_ram_gb = psutil.virtual_memory().total / (1024**3)
+ print(f"Total RAM: {total_ram_gb:.1f} GiB")
+ except ImportError:
+ print("psutil not installed — skipping RAM check (install psutil for this, or check manually).")
+
+ print(f"\nOLLAMA_MODEL configured: {_configured_model()}")
+ try:
+ client = get_client()
+ for m in client.list().models:
+ if _configured_model() in m.model or m.model in _configured_model():
+ print(f"On-disk size per `ollama list`: {m.size / (1024**3):.2f} GiB (digest={m.digest[:12]})")
+ except Exception as exc: # noqa: BLE001
+ print(f"Could not query `ollama list` for on-disk size: {exc}")
+
+ log_path = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Ollama", "server.log")
+ print(f"\nChecking Ollama server log for GPU/backend detection: {log_path}")
+ if os.path.isfile(log_path):
+ try:
+ with open(log_path, encoding="utf-8", errors="replace") as fh:
+ lines = fh.readlines()
+ gpu_lines = [
+ line.strip()
+ for line in lines
+ if any(
+ kw in line
+ for kw in ("gpu memory", "library=", "offloaded", "CPU_Mapped", "n_threads")
+ )
+ ]
+ print(f"Found {len(gpu_lines)} matching log lines. Last 12:")
+ for line in gpu_lines[-12:]:
+ print(f" {line}")
+ except OSError as exc:
+ print(f"Could not read log file: {exc}")
+ else:
+ print("Log file not found at that path — GPU/backend detection must be checked manually.")
+
+
+def main() -> None:
+ print("Diagnostic run started — no fixes are being applied, this only measures.\n")
+
+ t1 = step1_baseline()
+ t2 = step2_with_tools()
+ step3_model_residency()
+ step4_instrumented_investigation()
+ step5_system_basics()
+
+ _header("HEADLINE NUMBERS")
+ print(f"Step 1 (baseline, no tools): {t1:.2f}s")
+ print(f"Step 2 (baseline + tool schemas): {t2:.2f}s (delta vs step 1: {t2 - t1:+.2f}s)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ai_agents/offline_troubleshooting_agent/scripts/maintenance_rebuild_index.py b/ai_agents/offline_troubleshooting_agent/scripts/maintenance_rebuild_index.py
new file mode 100644
index 0000000..efab506
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/scripts/maintenance_rebuild_index.py
@@ -0,0 +1,59 @@
+"""Operator tool — NOT run automatically, and not called from
+ensure_collection() (a rebuild has real cost).
+
+Run this manually if search results ever seem degraded after heavy
+re-ingestion churn against an already-open collection (as seen once during
+step 9's fix-up debugging: repeated re-ingestion left manual_chunks
+returning empty results for small top_k values until its index was
+rebuilt). It rebuilds the HNSW index for the manual and incident
+collections and prints before/after stats so you can see what changed.
+
+Usage:
+ python scripts/maintenance_rebuild_index.py
+"""
+
+import os
+import sys
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from memory.incident_store import _configured_incident_collection # noqa: E402
+from memory.manual import _configured_manual_collection # noqa: E402
+from memory.vectorai_client import get_client # noqa: E402
+
+
+def _print_stats(client, name: str, label: str) -> None:
+ stats = client.vde.get_stats(name)
+ print(
+ f" {label}: total_vectors={stats.total_vectors}, "
+ f"indexed_vectors={stats.indexed_vectors}, "
+ f"deleted_vectors={stats.deleted_vectors}, "
+ f"storage_bytes={stats.storage_bytes}, "
+ f"index_memory_bytes={stats.index_memory_bytes}"
+ )
+
+
+def rebuild(name: str) -> None:
+ client = get_client()
+ print(f"\n--- {name} ---")
+ _print_stats(client, name, "before")
+
+ client.vde.rebuild_index(name)
+ print(" rebuild_index() called.")
+
+ _print_stats(client, name, "after")
+
+
+def main() -> None:
+ collections = [_configured_manual_collection(), _configured_incident_collection()]
+ print(f"Rebuilding HNSW index for: {collections}")
+ for name in collections:
+ rebuild(name)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ai_agents/offline_troubleshooting_agent/scripts/offline_test.py b/ai_agents/offline_troubleshooting_agent/scripts/offline_test.py
new file mode 100644
index 0000000..ff85c10
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/scripts/offline_test.py
@@ -0,0 +1,218 @@
+"""Section 19 Part 3 — THE OFFLINE TEST.
+
+Run this AFTER disconnecting the network, in its own terminal, with no
+further involvement needed. It is fully self-contained:
+
+ python scripts/offline_test.py
+
+It first guards against accidentally running "offline" while still online
+(a real network connection would silently invalidate the whole test), then
+triggers a bearing fault, runs a real investigation, and checks whether the
+reference incident saved during the online setup phase
+(data/offline_test_baseline.json) is recalled from local memory with zero
+internet access. Results are written to a timestamped file under docs/ so
+they survive even if the terminal closes before reconnecting.
+"""
+
+import json
+import os
+import sys
+import time
+from datetime import datetime
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from util.network_status import NETWORK_CHECK_HOST, NETWORK_CHECK_PORT, is_online # noqa: E402
+
+PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+BASELINE_PATH = os.path.join(PROJECT_ROOT, "data", "offline_test_baseline.json")
+
+NETWORK_GUARD_TIMEOUT = 2.0
+
+SEARCH_QUERY = "bearing fault high vibration high temperature BRG-02"
+
+
+class _Log:
+ """Prints each line immediately and buffers it for the markdown report."""
+
+ def __init__(self) -> None:
+ self.lines: list[str] = []
+
+ def __call__(self, line: str = "") -> None:
+ print(line, flush=True)
+ self.lines.append(line)
+
+
+log = _Log()
+
+
+def _write_log_file(status: str) -> str:
+ timestamp = datetime.now().strftime("%Y%m%dT%H%M%S")
+ log_path = os.path.join(PROJECT_ROOT, "docs", f"OFFLINE_TEST_LOG_{timestamp}.md")
+ os.makedirs(os.path.dirname(log_path), exist_ok=True)
+ with open(log_path, "w", encoding="utf-8") as fh:
+ fh.write(f"# Offline Test Log — {status}\n\n")
+ fh.write(f"Run at: {datetime.now().isoformat()}\n\n")
+ fh.write("```\n")
+ fh.write("\n".join(log.lines))
+ fh.write("\n```\n")
+ return log_path
+
+
+def main() -> None:
+ overall_start = time.monotonic()
+
+ # ------------------------------------------------------------------
+ # 1. Network-reachability guard
+ # ------------------------------------------------------------------
+ log("=" * 70)
+ log("OFFLINE TEST — network guard")
+ log("=" * 70)
+ log(f"Checking whether {NETWORK_CHECK_HOST}:{NETWORK_CHECK_PORT} is reachable...")
+
+ if is_online(timeout=NETWORK_GUARD_TIMEOUT):
+ log("")
+ log("!" * 70)
+ log("STILL ONLINE — this does not look disconnected.")
+ log(f"A TCP connection to {NETWORK_CHECK_HOST}:{NETWORK_CHECK_PORT} succeeded, ")
+ log("which means the network is still up. The offline test's whole point is")
+ log("proving this works with ZERO internet access, so running it now would")
+ log("prove nothing. Disconnect Wi-Fi / unplug the network, then re-run this")
+ log("script.")
+ log("!" * 70)
+ log_path = _write_log_file("ABORTED — still online")
+ log(f"\n(Full log written to {log_path})")
+ sys.exit(1)
+
+ log(f"OK — {NETWORK_CHECK_HOST}:{NETWORK_CHECK_PORT} unreachable within "
+ f"{NETWORK_GUARD_TIMEOUT}s. Proceeding as offline.\n")
+
+ # These are imported only after the guard passes, so a failed guard exits
+ # fast without needing local services to be initialized.
+ from agent.harness import run_investigation
+ from agent.llm_client import health_check as llm_health_check
+ from memory.embeddings import embedding_health_check
+ from memory.incident_store import search_incidents
+ from memory.vectorai_client import health_check as vectorai_health_check
+ from simulator.machine import Machine
+ from simulator.scenarios import FAULT_TARGETS, trigger_fault
+
+ # ------------------------------------------------------------------
+ # 2. Local service health checks
+ # ------------------------------------------------------------------
+ log("=" * 70)
+ log("Local service health checks")
+ log("=" * 70)
+
+ llm_status = llm_health_check()
+ log(f"Ollama / LLM: {llm_status}")
+
+ embed_status = embedding_health_check()
+ log(f"Embedding model: {embed_status}")
+
+ vectorai_status = vectorai_health_check()
+ log(f"Actian VectorAI DB: {vectorai_status}")
+ log("")
+
+ # ------------------------------------------------------------------
+ # 3. Trigger the same bearing fault
+ # ------------------------------------------------------------------
+ log("=" * 70)
+ log("Triggering bearing fault")
+ log("=" * 70)
+ machine = Machine(seed=7)
+ machine.reset_machine()
+ trigger_fault(machine, "bearing")
+ machine.advance_simulation(steps=FAULT_TARGETS["bearing"].total_steps + 2)
+ log(f"Current readings: {machine.get_current_readings()}\n")
+
+ # ------------------------------------------------------------------
+ # 4. Real investigation
+ # ------------------------------------------------------------------
+ log("=" * 70)
+ log("Running investigation")
+ log("=" * 70)
+
+ investigation_start = time.monotonic()
+ final_state = None
+ round_num = 0
+ last_count = 0
+ for state in run_investigation(machine, machine.history, "Investigate bearing fault on Machine A"):
+ final_state = state
+ if len(state.tool_calls) != last_count:
+ last_count = len(state.tool_calls)
+ round_num += 1
+ last_call = state.tool_calls[-1]["name"] if state.tool_calls else "(none yet)"
+ log(f" [{round_num}] tool_calls so far: {last_count} | most recent: {last_call}")
+ investigation_elapsed = time.monotonic() - investigation_start
+
+ reached_finish = final_state is not None and final_state.final_result is not None and not any(
+ error in ("model_ended_without_finish_investigation", "max_rounds_reached")
+ for error in final_state.errors
+ )
+ log(f"\nfinal_result: {final_state.final_result if final_state else None}")
+ log(f"errors: {final_state.errors if final_state else 'N/A'}")
+ log(f"\nReached finish_investigation: {'Y' if reached_finish else 'N'}")
+ log(f"Investigation wall-clock time: {investigation_elapsed:.2f}s ({investigation_elapsed / 60:.1f} min)\n")
+
+ # ------------------------------------------------------------------
+ # 5. Check whether the offline-test reference incident is recalled
+ # ------------------------------------------------------------------
+ log("=" * 70)
+ log("Checking recall of the offline-test reference incident")
+ log("=" * 70)
+
+ baseline_id = None
+ baseline_cause = None
+ if not os.path.isfile(BASELINE_PATH):
+ log(f"FAIL: baseline file not found at {BASELINE_PATH}.")
+ log("(Part A's online setup must run first, while still connected.)")
+ recalled = False
+ found_ids: list[str] = []
+ else:
+ with open(BASELINE_PATH, encoding="utf-8") as fh:
+ baseline = json.load(fh)
+ baseline_id = baseline["incident_id"]
+ baseline_cause = baseline.get("confirmed_cause")
+ log(f"Baseline reference incident_id: {baseline_id}")
+ log(f"Baseline confirmed_cause: {baseline_cause!r}")
+
+ search_results = search_incidents(SEARCH_QUERY, top_k=5)
+ found_ids = [item.get("id") for item in search_results]
+ log(f"search_incidents({SEARCH_QUERY!r}) returned ids: {found_ids}")
+
+ recalled = baseline_id in found_ids
+ if recalled:
+ log(f"\nPASS: reference incident {baseline_id} was recalled by exact id match.")
+ else:
+ log(f"\nFAIL: reference incident {baseline_id} was NOT among the returned ids.")
+
+ # ------------------------------------------------------------------
+ # 6. Final summary
+ # ------------------------------------------------------------------
+ total_elapsed = time.monotonic() - overall_start
+
+ log("\n" + "=" * 70)
+ log("FINAL SUMMARY")
+ log("=" * 70)
+ log(f"Reached finish_investigation: {'Y' if reached_finish else 'N'}")
+ log(
+ f"Correct prior incident recalled: {'Y' if recalled else 'N'}"
+ + (f" (id={baseline_id})" if baseline_id else " (no baseline to compare)")
+ )
+ log(f"state.errors: {final_state.errors if final_state else 'N/A'}")
+ log(f"Total wall-clock time: {total_elapsed:.2f}s ({total_elapsed / 60:.1f} min)")
+
+ overall_pass = reached_finish and recalled
+ log(f"\nOVERALL: {'PASS' if overall_pass else 'FAIL'}")
+
+ log_path = _write_log_file("PASS" if overall_pass else "FAIL")
+ log(f"\n(Full log written to {log_path})")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ai_agents/offline_troubleshooting_agent/scripts/persistence_test.py b/ai_agents/offline_troubleshooting_agent/scripts/persistence_test.py
new file mode 100644
index 0000000..93b354b
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/scripts/persistence_test.py
@@ -0,0 +1,151 @@
+"""Persistence test (section 22): prove a genuinely NEW incident survives a
+real Actian VectorAI DB container restart, verified from a fresh process.
+
+Usage:
+ python scripts/persistence_test.py --mode save
+ # ... restart the offline-troubleshooting-vectorai container ...
+ python scripts/persistence_test.py --mode verify
+"""
+
+import argparse
+import json
+import os
+import sys
+import uuid
+from datetime import datetime
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from memory.incident_store import get_incident, save_incident, search_incidents # noqa: E402
+from models.schemas import Incident # noqa: E402
+
+PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+BASELINE_PATH = os.path.join(PROJECT_ROOT, "data", "persistence_test_baseline.json")
+
+MARKER_INCIDENT_ID = str(uuid.uuid5(uuid.NAMESPACE_URL, "persistence-test-marker"))
+MARKER_CONFIRMED_CAUSE = "PERSISTENCE TEST MARKER - safe to ignore/delete"
+SEARCH_QUERY = "persistence test marker safe to ignore"
+
+
+def _build_marker_incident() -> Incident:
+ return Incident(
+ incident_id=MARKER_INCIDENT_ID,
+ created_at=datetime.now(),
+ machine_id="Machine A",
+ symptoms=["persistence test marker"],
+ temperature_c=999.9,
+ vibration_mm_s=999.9,
+ pressure_bar=999.9,
+ error_code="TEST-00",
+ diagnosis="Not a real diagnosis — written by scripts/persistence_test.py.",
+ confirmed_cause=MARKER_CONFIRMED_CAUSE,
+ fix_applied="N/A — persistence test only, no real fix.",
+ outcome="persistence-test",
+ notes=(
+ "Written by scripts/persistence_test.py --mode save to verify Actian "
+ "VectorAI DB data survives a container restart (section 22)."
+ ),
+ )
+
+
+def run_save() -> None:
+ incident = _build_marker_incident()
+ save_incident(incident)
+
+ baseline = incident.model_dump(mode="json")
+ os.makedirs(os.path.dirname(BASELINE_PATH), exist_ok=True)
+ with open(BASELINE_PATH, "w", encoding="utf-8") as fh:
+ json.dump(baseline, fh, indent=2)
+
+ print(f"Saved persistence-test marker incident: {incident.incident_id}")
+ print("Field values written:")
+ for key, value in baseline.items():
+ print(f" {key}: {value!r}")
+ print(f"\nBaseline saved to: {BASELINE_PATH}")
+ print(
+ "\nNow restart the Actian VectorAI DB container, e.g.:\n"
+ " docker compose restart offline-troubleshooting-vectorai\n"
+ "then run: python scripts/persistence_test.py --mode verify"
+ )
+
+
+def _diff_fields(baseline: dict, retrieved: dict) -> list[str]:
+ mismatches = []
+ all_keys = sorted(set(baseline.keys()) | set(retrieved.keys()))
+ for key in all_keys:
+ base_val = baseline.get(key, "<missing>")
+ retr_val = retrieved.get(key, "<missing>")
+ if base_val != retr_val:
+ mismatches.append(f" {key}: expected {base_val!r}, got {retr_val!r}")
+ return mismatches
+
+
+def run_verify() -> None:
+ if not os.path.isfile(BASELINE_PATH):
+ print(f"FAIL: no baseline file found at {BASELINE_PATH}.")
+ print("Run `python scripts/persistence_test.py --mode save` first.")
+ sys.exit(1)
+
+ with open(BASELINE_PATH, encoding="utf-8") as fh:
+ baseline = json.load(fh)
+
+ print(f"Loaded baseline for incident_id={baseline['incident_id']}")
+
+ failures: list[str] = []
+
+ print("\n--- get_incident() ---")
+ retrieved = get_incident(baseline["incident_id"])
+ if retrieved is None:
+ print("FAIL: get_incident() returned None — record not found.")
+ failures.append("get_incident() returned None")
+ else:
+ retrieved_dump = retrieved.model_dump(mode="json")
+ mismatches = _diff_fields(baseline, retrieved_dump)
+ if mismatches:
+ print("FAIL: field mismatch(es) between baseline and retrieved record:")
+ for line in mismatches:
+ print(line)
+ failures.append(f"{len(mismatches)} field mismatch(es) via get_incident()")
+ else:
+ print("PASS: every field matches the saved baseline exactly.")
+
+ print("\n--- search_incidents() ---")
+ search_results = search_incidents(SEARCH_QUERY, top_k=5)
+ found_ids = [item.get("id") for item in search_results]
+ if baseline["incident_id"] in found_ids:
+ print(f"PASS: marker incident found via search_incidents() (query={SEARCH_QUERY!r}).")
+ print(f" matched ids returned: {found_ids}")
+ else:
+ print(f"FAIL: marker incident NOT found via search_incidents() (query={SEARCH_QUERY!r}).")
+ print(f" ids returned instead: {found_ids}")
+ failures.append("marker incident not found via search_incidents()")
+
+ print("\n" + "=" * 60)
+ if not failures:
+ print("PASS: persistence test succeeded — the marker incident survived")
+ print("the container restart, verified from this fresh process, via")
+ print("both get_incident() and search_incidents().")
+ else:
+ print("FAIL: persistence test did not fully pass. Issues:")
+ for failure in failures:
+ print(f" - {failure}")
+ sys.exit(1)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--mode", choices=["save", "verify"], required=True)
+ args = parser.parse_args()
+
+ if args.mode == "save":
+ run_save()
+ else:
+ run_verify()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ai_agents/offline_troubleshooting_agent/scripts/reset_demo.py b/ai_agents/offline_troubleshooting_agent/scripts/reset_demo.py
new file mode 100644
index 0000000..c1c5faa
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/scripts/reset_demo.py
@@ -0,0 +1,46 @@
+import argparse
+import os
+import sys
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))
+PROJECT_ROOT = os.path.dirname(SCRIPTS_DIR)
+sys.path.insert(0, PROJECT_ROOT)
+sys.path.insert(0, SCRIPTS_DIR)
+
+from seed_memory import clear_incidents_collection, seed_incidents # noqa: E402
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(
+ description="Reset the local Actian memory layer (incidents collection only)."
+ )
+ parser.add_argument(
+ "--reseed",
+ action="store_true",
+ help="After clearing, reload data/seed_incidents.json into the incidents collection.",
+ )
+ args = parser.parse_args()
+
+ print("Clearing incidents collection...")
+ clear_incidents_collection()
+ print("incidents collection cleared.")
+
+ if args.reseed:
+ print("Reseeding demo incidents...")
+ count = seed_incidents()
+ print(f"incidents seeded: {count}")
+ else:
+ print("No reseed requested — incidents collection left empty.")
+
+ print(
+ "\nNote: this only resets the Actian memory layer. It does not touch the running "
+ "simulator's in-memory machine state — use the Gradio app's 'Reset Machine' button for that."
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ai_agents/offline_troubleshooting_agent/scripts/seed_memory.py b/ai_agents/offline_troubleshooting_agent/scripts/seed_memory.py
new file mode 100644
index 0000000..2ff11de
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/scripts/seed_memory.py
@@ -0,0 +1,84 @@
+import argparse
+import json
+import os
+import sys
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, PROJECT_ROOT)
+
+from memory.incident_store import _configured_incident_collection, save_incident # noqa: E402
+from memory.manual import ingest_manual_documents # noqa: E402
+from memory.vectorai_client import delete_collection, ensure_collection # noqa: E402
+from models.schemas import Incident # noqa: E402
+
+MANUAL_PATHS = [
+ os.path.join(PROJECT_ROOT, "documents", "machine_manual.md"),
+ os.path.join(PROJECT_ROOT, "documents", "troubleshooting_guide.md"),
+]
+SEED_INCIDENTS_PATH = os.path.join(PROJECT_ROOT, "data", "seed_incidents.json")
+INCIDENT_EMBEDDING_DIM = 768
+
+
+def load_seed_incidents(path: str = SEED_INCIDENTS_PATH) -> list[Incident]:
+ with open(path, "r", encoding="utf-8") as f:
+ raw = json.load(f)
+ return [Incident.model_validate(item) for item in raw]
+
+
+def clear_incidents_collection(collection: str | None = None) -> None:
+ target_collection = collection or _configured_incident_collection()
+ delete_collection(target_collection)
+ ensure_collection(target_collection, dim=INCIDENT_EMBEDDING_DIM)
+
+
+def seed_incidents(collection: str | None = None) -> int:
+ incidents = load_seed_incidents()
+ for incident in incidents:
+ save_incident(incident, collection=collection)
+ return len(incidents)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(
+ description="Seed local memory (manual chunks + optionally demo incidents)."
+ )
+ parser.add_argument(
+ "--mode",
+ choices=["fresh", "seeded"],
+ default="fresh",
+ help="'fresh': manual only, incidents collection cleared to empty. "
+ "'seeded': manual plus demo incidents from data/seed_incidents.json.",
+ )
+ args = parser.parse_args()
+
+ print(f"Seeding manual memory (mode={args.mode})...")
+ manual_count = ingest_manual_documents(MANUAL_PATHS)
+ print(f"manual chunks ingested: {manual_count}")
+
+ if args.mode == "fresh":
+ print("\nClearing incidents collection for a fresh (zero-incident) state...")
+ clear_incidents_collection()
+ print("incidents collection cleared.")
+
+ if manual_count > 0:
+ print("\nPASS: manual documents ingested, incidents collection is empty.")
+ else:
+ print("\nFAIL: no manual chunks were ingested.")
+ return
+
+ print("\nSeeding demo incidents...")
+ incident_count = seed_incidents()
+ print(f"incidents seeded: {incident_count}")
+
+ if manual_count > 0 and incident_count > 0:
+ print("\nPASS: manual documents and demo incidents seeded successfully.")
+ else:
+ print("\nFAIL: seeding did not complete as expected.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ai_agents/offline_troubleshooting_agent/simulator/__init__.py b/ai_agents/offline_troubleshooting_agent/simulator/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/ai_agents/offline_troubleshooting_agent/simulator/history.py b/ai_agents/offline_troubleshooting_agent/simulator/history.py
new file mode 100644
index 0000000..7092e38
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/simulator/history.py
@@ -0,0 +1,30 @@
+import pandas as pd
+
+from models.schemas import MachineReading
+
+READING_COLUMNS = [
+ "temperature_c",
+ "vibration_mm_s",
+ "pressure_bar",
+ "status",
+ "error_code",
+ "timestamp",
+]
+
+
+class History:
+ def __init__(self, max_length: int = 200):
+ self._max_length = max_length
+ self._df = pd.DataFrame(columns=READING_COLUMNS)
+
+ def append_reading(self, reading: MachineReading) -> None:
+ row = pd.DataFrame([reading.model_dump()])
+ if self._df.empty:
+ self._df = row
+ else:
+ self._df = pd.concat([self._df, row], ignore_index=True)
+ if len(self._df) > self._max_length:
+ self._df = self._df.iloc[-self._max_length :].reset_index(drop=True)
+
+ def get_recent_history(self, limit: int = 20) -> pd.DataFrame:
+ return self._df.tail(limit).reset_index(drop=True)
diff --git a/ai_agents/offline_troubleshooting_agent/simulator/machine.py b/ai_agents/offline_troubleshooting_agent/simulator/machine.py
new file mode 100644
index 0000000..5eed178
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/simulator/machine.py
@@ -0,0 +1,126 @@
+import random
+from dataclasses import dataclass
+from datetime import datetime
+
+from models.schemas import FaultType, MachineReading
+from simulator.history import History
+
+TEMP_RANGE = (65.0, 75.0)
+VIBRATION_RANGE = (1.5, 3.0)
+PRESSURE_RANGE = (4.5, 5.5)
+
+IDLE_TEMP_JITTER = 0.5
+IDLE_VIBRATION_JITTER = 0.1
+IDLE_PRESSURE_JITTER = 0.1
+
+FAULT_TEMP_NOISE = 0.3
+FAULT_VIBRATION_NOISE = 0.1
+FAULT_PRESSURE_NOISE = 0.05
+
+
+@dataclass(frozen=True)
+class FaultTarget:
+ fault_type: FaultType
+ temperature_c: float
+ vibration_mm_s: float
+ pressure_bar: float
+ error_code: str
+ total_steps: int = 8
+
+
+def _clamp(value: float, low: float, high: float) -> float:
+ return max(low, min(high, value))
+
+
+def _lerp(start: float, end: float, frac: float) -> float:
+ return start + (end - start) * frac
+
+
+class Machine:
+ def __init__(self, seed: int | None = None, history_max_length: int = 200):
+ self._rng = random.Random(seed)
+ self.history = History(max_length=history_max_length)
+ self._active_fault: FaultTarget | None = None
+ self._fault_start: MachineReading | None = None
+ self._fault_step = 0
+ self.state: MachineReading
+ self.reset_machine()
+
+ def get_current_readings(self) -> MachineReading:
+ return self.state
+
+ def reset_machine(self) -> None:
+ self._active_fault = None
+ self._fault_start = None
+ self._fault_step = 0
+ self.state = MachineReading(
+ temperature_c=self._rng.uniform(*TEMP_RANGE),
+ vibration_mm_s=self._rng.uniform(*VIBRATION_RANGE),
+ pressure_bar=self._rng.uniform(*PRESSURE_RANGE),
+ status="running",
+ error_code=None,
+ timestamp=datetime.now(),
+ )
+
+ def start_fault(self, target: FaultTarget) -> None:
+ self._active_fault = target
+ self._fault_start = self.state
+ self._fault_step = 0
+
+ def advance_simulation(self, steps: int = 1) -> None:
+ for _ in range(steps):
+ if self._active_fault is not None:
+ self._advance_fault_step()
+ else:
+ self._advance_idle_step()
+ self.history.append_reading(self.state)
+
+ def _advance_idle_step(self) -> None:
+ temp = _clamp(
+ self.state.temperature_c + self._rng.uniform(-IDLE_TEMP_JITTER, IDLE_TEMP_JITTER),
+ *TEMP_RANGE,
+ )
+ vibration = _clamp(
+ self.state.vibration_mm_s
+ + self._rng.uniform(-IDLE_VIBRATION_JITTER, IDLE_VIBRATION_JITTER),
+ *VIBRATION_RANGE,
+ )
+ pressure = _clamp(
+ self.state.pressure_bar
+ + self._rng.uniform(-IDLE_PRESSURE_JITTER, IDLE_PRESSURE_JITTER),
+ *PRESSURE_RANGE,
+ )
+ self.state = MachineReading(
+ temperature_c=temp,
+ vibration_mm_s=vibration,
+ pressure_bar=pressure,
+ status="running",
+ error_code=None,
+ timestamp=datetime.now(),
+ )
+
+ def _advance_fault_step(self) -> None:
+ assert self._active_fault is not None
+ assert self._fault_start is not None
+ target = self._active_fault
+ self._fault_step += 1
+ frac = min(self._fault_step / target.total_steps, 1.0)
+
+ temp = _lerp(self._fault_start.temperature_c, target.temperature_c, frac)
+ temp += self._rng.uniform(-FAULT_TEMP_NOISE, FAULT_TEMP_NOISE)
+
+ vibration = _lerp(self._fault_start.vibration_mm_s, target.vibration_mm_s, frac)
+ vibration = max(0.0, vibration + self._rng.uniform(-FAULT_VIBRATION_NOISE, FAULT_VIBRATION_NOISE))
+
+ pressure = _lerp(self._fault_start.pressure_bar, target.pressure_bar, frac)
+ pressure = max(0.0, pressure + self._rng.uniform(-FAULT_PRESSURE_NOISE, FAULT_PRESSURE_NOISE))
+
+ reached_target = frac >= 1.0
+ self.state = MachineReading(
+ temperature_c=temp,
+ vibration_mm_s=vibration,
+ pressure_bar=pressure,
+ status="fault" if reached_target else "warning",
+ error_code=target.error_code if reached_target else None,
+ timestamp=datetime.now(),
+ )
diff --git a/ai_agents/offline_troubleshooting_agent/simulator/scenarios.py b/ai_agents/offline_troubleshooting_agent/simulator/scenarios.py
new file mode 100644
index 0000000..fd38849
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/simulator/scenarios.py
@@ -0,0 +1,30 @@
+from models.schemas import FaultType
+from simulator.machine import FaultTarget, Machine
+
+FAULT_TARGETS: dict[FaultType, FaultTarget] = {
+ "bearing": FaultTarget(
+ fault_type="bearing",
+ temperature_c=92.0,
+ vibration_mm_s=8.0,
+ pressure_bar=5.0,
+ error_code="BRG-02",
+ ),
+ "cooling": FaultTarget(
+ fault_type="cooling",
+ temperature_c=96.0,
+ vibration_mm_s=2.3,
+ pressure_bar=5.1,
+ error_code="TMP-04",
+ ),
+ "pressure": FaultTarget(
+ fault_type="pressure",
+ temperature_c=77.0,
+ vibration_mm_s=2.4,
+ pressure_bar=2.8,
+ error_code="PRS-03",
+ ),
+}
+
+
+def trigger_fault(machine: Machine, fault_type: FaultType) -> None:
+ machine.start_fault(FAULT_TARGETS[fault_type])
diff --git a/ai_agents/offline_troubleshooting_agent/tests/__init__.py b/ai_agents/offline_troubleshooting_agent/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/ai_agents/offline_troubleshooting_agent/tests/test_agent.py b/ai_agents/offline_troubleshooting_agent/tests/test_agent.py
new file mode 100644
index 0000000..cff64cc
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/tests/test_agent.py
@@ -0,0 +1,427 @@
+from types import SimpleNamespace
+
+import agent.harness as harness_module
+from agent.tools import AgentTools
+from simulator.machine import Machine
+
+
+def _tool_call(name, arguments):
+ return SimpleNamespace(function=SimpleNamespace(name=name, arguments=arguments))
+
+
+def _response(tool_calls, content=""):
+ return SimpleNamespace(
+ message=SimpleNamespace(role="assistant", content=content, tool_calls=tool_calls)
+ )
+
+
+class ScriptedChat:
+ def __init__(self, responses):
+ self._responses = list(responses)
+ self.call_count = 0
+
+ def __call__(self, model, messages, tools, think=False):
+ self.call_count += 1
+ if not self._responses:
+ raise AssertionError(
+ f"chat() called more times than scripted (call #{self.call_count})"
+ )
+ item = self._responses.pop(0)
+ if isinstance(item, BaseException):
+ raise item
+ return item
+
+
+def _patch_healthy_services(monkeypatch):
+ monkeypatch.setattr(
+ harness_module,
+ "llm_health_check",
+ lambda: {"reachable": True, "model_available": True, "local_models": []},
+ )
+ monkeypatch.setattr(
+ harness_module, "vectorai_health_check", lambda: {"reachable": True}
+ )
+
+
+def _patch_chat(monkeypatch, responses):
+ scripted = ScriptedChat(responses)
+ fake_client = SimpleNamespace(chat=scripted)
+ monkeypatch.setattr(harness_module, "get_client", lambda: fake_client)
+ return scripted
+
+
+def _patch_search_manual(monkeypatch, results=None):
+ if results is None:
+ results = [
+ {
+ "id": "chunk-1",
+ "score": 0.9,
+ "text": "Bearing guidance text.",
+ "section_title": "Bearing Troubleshooting",
+ "source_filename": "troubleshooting_guide.md",
+ "component": "bearing",
+ }
+ ]
+ call_log: list[dict] = []
+
+ def search_manual(self, query, top_k=3):
+ call_log.append({"query": query, "top_k": top_k})
+ self.state.retrieved_manual_chunks.extend(results)
+ return results
+
+ monkeypatch.setattr(AgentTools, "search_manual", search_manual)
+ return call_log
+
+
+def _new_machine_and_history():
+ machine = Machine(seed=1)
+ return machine, machine.history
+
+
+def test_happy_path_finishes_and_stops_after_finish_investigation(monkeypatch):
+ _patch_healthy_services(monkeypatch)
+ manual_log = _patch_search_manual(monkeypatch)
+
+ final_args = dict(
+ likely_cause="worn bearing",
+ confidence=0.8,
+ recommendation="Inspect the bearing assembly.",
+ supporting_evidence=["vibration elevated"],
+ retrieved_incident_ids=[],
+ manual_sources=["Bearing Troubleshooting"],
+ )
+
+ responses = [
+ _response([_tool_call("get_current_readings", {})]),
+ _response([_tool_call("search_manual", {"query": "bearing", "top_k": 3})]),
+ _response([_tool_call("finish_investigation", final_args)]),
+ ]
+ scripted = _patch_chat(monkeypatch, responses)
+
+ machine, history = _new_machine_and_history()
+
+ states = list(
+ harness_module.run_investigation(machine, history, "Investigate bearing fault")
+ )
+
+ final_state = states[-1]
+ assert final_state.final_result == final_args
+ assert scripted.call_count == 3
+ assert len(manual_log) == 1
+
+
+def test_duplicate_call_detection_does_not_re_execute_underlying_tool(monkeypatch):
+ _patch_healthy_services(monkeypatch)
+ manual_log = _patch_search_manual(monkeypatch)
+
+ duplicate_call = _tool_call("search_manual", {"query": "bearing", "top_k": 3})
+ final_args = dict(
+ likely_cause="worn bearing",
+ confidence=0.7,
+ recommendation="Inspect the bearing assembly.",
+ supporting_evidence=[],
+ retrieved_incident_ids=[],
+ manual_sources=[],
+ )
+
+ responses = [
+ _response([duplicate_call]),
+ _response([duplicate_call]),
+ _response([_tool_call("finish_investigation", final_args)]),
+ ]
+ scripted = _patch_chat(monkeypatch, responses)
+
+ machine, history = _new_machine_and_history()
+
+ states = list(
+ harness_module.run_investigation(machine, history, "Investigate bearing fault")
+ )
+
+ final_state = states[-1]
+ assert final_state.final_result == final_args
+ assert scripted.call_count == 3
+ # The underlying AgentTools.search_manual must have run only once, even
+ # though the model requested the identical call twice.
+ assert len(manual_log) == 1
+
+
+def test_max_rounds_fallback_when_model_never_finishes(monkeypatch):
+ _patch_healthy_services(monkeypatch)
+
+ responses = [
+ _response([_tool_call("save_finding", {"finding": "f1", "evidence": "e1"})]),
+ _response([_tool_call("save_finding", {"finding": "f2", "evidence": "e2"})]),
+ ]
+ scripted = _patch_chat(monkeypatch, responses)
+
+ machine, history = _new_machine_and_history()
+
+ states = list(
+ harness_module.run_investigation(
+ machine, history, "Investigate bearing fault", max_rounds=2
+ )
+ )
+
+ final_state = states[-1]
+ assert scripted.call_count == 2
+ assert "max_rounds_reached" in final_state.errors
+ assert final_state.final_result is not None
+ assert final_state.final_result["confidence"] == 0.0
+ assert final_state.final_result["likely_cause"].startswith("Undetermined")
+
+
+def test_tool_exception_is_recorded_and_loop_continues(monkeypatch):
+ _patch_healthy_services(monkeypatch)
+
+ def search_past_incidents(self, query, top_k=3):
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(AgentTools, "search_past_incidents", search_past_incidents)
+
+ final_args = dict(
+ likely_cause="worn bearing",
+ confidence=0.6,
+ recommendation="Inspect the bearing assembly.",
+ supporting_evidence=[],
+ retrieved_incident_ids=[],
+ manual_sources=[],
+ )
+
+ responses = [
+ _response([_tool_call("search_past_incidents", {"query": "test", "top_k": 3})]),
+ _response([_tool_call("finish_investigation", final_args)]),
+ ]
+ scripted = _patch_chat(monkeypatch, responses)
+
+ machine, history = _new_machine_and_history()
+
+ # If the tool exception propagated out of run_investigation instead of
+ # being recorded and handled, this call would raise and fail the test.
+ states = list(
+ harness_module.run_investigation(machine, history, "Investigate bearing fault")
+ )
+
+ final_state = states[-1]
+ assert scripted.call_count == 2
+ assert any(
+ error.startswith("tool_error:search_past_incidents") for error in final_state.errors
+ )
+ assert final_state.final_result == final_args
+
+
+def test_nudge_recovers_when_model_calls_tool_on_retry(monkeypatch):
+ _patch_healthy_services(monkeypatch)
+
+ final_args = dict(
+ likely_cause="worn bearing",
+ confidence=0.75,
+ recommendation="Inspect the bearing assembly.",
+ supporting_evidence=[],
+ retrieved_incident_ids=[],
+ manual_sources=[],
+ )
+
+ responses = [
+ _response([], content="I think it might be a worn bearing, let me think..."),
+ _response([_tool_call("finish_investigation", final_args)]),
+ ]
+ scripted = ScriptedChat(responses)
+ captured_messages: list[list] = []
+
+ def capturing_chat(model, messages, tools, think=False):
+ captured_messages.append(list(messages))
+ return scripted(model, messages, tools, think=think)
+
+ monkeypatch.setattr(
+ harness_module, "get_client", lambda: SimpleNamespace(chat=capturing_chat)
+ )
+
+ machine, history = _new_machine_and_history()
+
+ states = list(
+ harness_module.run_investigation(machine, history, "Investigate bearing fault")
+ )
+
+ final_state = states[-1]
+ # The nudge must have produced the model's real finish_investigation
+ # result, not the synthesized fallback.
+ assert final_state.final_result == final_args
+ assert scripted.call_count == 2
+
+ nudge_text = "You didn't call a tool"
+ nudge_messages_in_second_call = [
+ m
+ for m in captured_messages[1]
+ if isinstance(m, dict) and m.get("role") == "user" and nudge_text in m.get("content", "")
+ ]
+ assert len(nudge_messages_in_second_call) == 1
+ assert any(
+ error.startswith("model_ended_without_tool_call:") for error in final_state.errors
+ )
+ assert "model_ended_without_finish_investigation" not in final_state.errors
+
+
+def test_nudge_does_not_help_falls_back_exactly_as_before(monkeypatch):
+ _patch_healthy_services(monkeypatch)
+
+ responses = [
+ _response([], content="Thinking out loud, no tool call yet."),
+ _response([], content="Still no tool call after the nudge."),
+ ]
+ scripted = _patch_chat(monkeypatch, responses)
+
+ machine, history = _new_machine_and_history()
+
+ states = list(
+ harness_module.run_investigation(machine, history, "Investigate bearing fault")
+ )
+
+ final_state = states[-1]
+ # Exactly one nudge attempt: the original call plus one retry, then
+ # terminal handling — a third chat() call would raise inside
+ # ScriptedChat, so this also proves no second nudge was attempted.
+ assert scripted.call_count == 2
+ assert "model_ended_without_finish_investigation" in final_state.errors
+ assert (
+ sum(
+ 1
+ for error in final_state.errors
+ if error.startswith("model_ended_without_tool_call:")
+ )
+ == 2
+ )
+ assert final_state.final_result is not None
+ assert final_state.final_result["confidence"] == 0.0
+ assert final_state.final_result["likely_cause"].startswith("Undetermined")
+
+
+def test_connectivity_precheck_skips_model_calls_when_ollama_unreachable(monkeypatch):
+ monkeypatch.setattr(
+ harness_module,
+ "llm_health_check",
+ lambda: {"reachable": False, "model_available": False, "local_models": []},
+ )
+
+ def _get_client_should_not_be_called():
+ raise AssertionError("get_client should not have been called")
+
+ def _vectorai_health_check_should_not_be_called():
+ raise AssertionError("vectorai_health_check should not have been called")
+
+ monkeypatch.setattr(harness_module, "get_client", _get_client_should_not_be_called)
+ monkeypatch.setattr(
+ harness_module, "vectorai_health_check", _vectorai_health_check_should_not_be_called
+ )
+
+ machine, history = _new_machine_and_history()
+
+ states = list(
+ harness_module.run_investigation(machine, history, "Investigate bearing fault")
+ )
+
+ assert len(states) == 1
+ assert states[0].errors == ["Ollama is not reachable — is it running?"]
+ assert states[0].final_result is not None
+
+
+def test_connectivity_precheck_skips_model_calls_when_actian_unreachable(monkeypatch):
+ monkeypatch.setattr(
+ harness_module,
+ "llm_health_check",
+ lambda: {"reachable": True, "model_available": True, "local_models": []},
+ )
+ monkeypatch.setattr(
+ harness_module, "vectorai_health_check", lambda: {"reachable": False}
+ )
+
+ def _get_client_should_not_be_called():
+ raise AssertionError("get_client should not have been called")
+
+ monkeypatch.setattr(harness_module, "get_client", _get_client_should_not_be_called)
+
+ machine, history = _new_machine_and_history()
+
+ states = list(
+ harness_module.run_investigation(machine, history, "Investigate bearing fault")
+ )
+
+ assert len(states) == 1
+ assert states[0].errors == [
+ "Actian VectorAI DB is not reachable — is the container running "
+ "(docker compose up -d)?"
+ ]
+ assert states[0].final_result is not None
+
+
+def test_mid_investigation_connection_loss_falls_back_gracefully(monkeypatch):
+ _patch_healthy_services(monkeypatch)
+ manual_log = _patch_search_manual(monkeypatch)
+
+ responses = [
+ _response([_tool_call("search_manual", {"query": "bearing", "top_k": 3})]),
+ ConnectionError(
+ "Failed to connect to Ollama. Please check that Ollama is downloaded, "
+ "running and accessible."
+ ),
+ ]
+ scripted = _patch_chat(monkeypatch, responses)
+
+ machine, history = _new_machine_and_history()
+
+ # If the connection error propagated out of run_investigation() instead
+ # of being caught and turned into a fallback, this call would raise and
+ # fail the test.
+ states = list(
+ harness_module.run_investigation(machine, history, "Investigate bearing fault")
+ )
+
+ final_state = states[-1]
+ assert scripted.call_count == 2
+ assert any(
+ error.startswith("llm_connection_lost_mid_investigation")
+ for error in final_state.errors
+ )
+ assert final_state.final_result is not None
+ assert final_state.final_result["confidence"] == 0.0
+ assert final_state.final_result["likely_cause"].startswith("Undetermined")
+ # The fallback must reuse evidence already gathered before the
+ # connection was lost (round 1's search_manual), not just an empty stub.
+ assert final_state.final_result["manual_sources"] == ["Bearing Troubleshooting"]
+ assert len(manual_log) == 1
+
+
+def test_malformed_finish_investigation_args_recorded_and_continues(monkeypatch):
+ _patch_healthy_services(monkeypatch)
+
+ valid_args = dict(
+ likely_cause="worn bearing",
+ confidence=0.8,
+ recommendation="Inspect the bearing assembly.",
+ supporting_evidence=[],
+ retrieved_incident_ids=[],
+ manual_sources=[],
+ )
+ missing_confidence_args = {k: v for k, v in valid_args.items() if k != "confidence"}
+
+ responses = [
+ _response([_tool_call("finish_investigation", missing_confidence_args)]),
+ _response([_tool_call("finish_investigation", valid_args)]),
+ ]
+ scripted = _patch_chat(monkeypatch, responses)
+
+ machine, history = _new_machine_and_history()
+
+ # A TypeError from the missing required argument must be caught by the
+ # existing tool-execution try/except, not propagate and crash the loop.
+ states = list(
+ harness_module.run_investigation(machine, history, "Investigate bearing fault")
+ )
+
+ final_state = states[-1]
+ assert scripted.call_count == 2
+ assert any(
+ error.startswith("tool_error:finish_investigation") for error in final_state.errors
+ )
+ # The investigation continues past the malformed call and reaches a real
+ # finish_investigation once the model retries with valid arguments.
+ assert final_state.final_result == valid_args
diff --git a/ai_agents/offline_troubleshooting_agent/tests/test_confirmation.py b/ai_agents/offline_troubleshooting_agent/tests/test_confirmation.py
new file mode 100644
index 0000000..7980e34
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/tests/test_confirmation.py
@@ -0,0 +1,120 @@
+from agent.confirmation import build_default_review_fields, build_incident_from_review
+from agent.state import InvestigationState
+
+
+def _state_with_result(**result_overrides) -> InvestigationState:
+ result = dict(
+ likely_cause="Worn bearing",
+ confidence=0.9,
+ recommendation="Inspect the bearing assembly.",
+ supporting_evidence=["vibration elevated", "temperature elevated"],
+ retrieved_incident_ids=[],
+ manual_sources=[],
+ )
+ result.update(result_overrides)
+ return InvestigationState(
+ investigation_id="inv-1",
+ objective="Investigate bearing fault",
+ final_result=result,
+ )
+
+
+def test_build_default_review_fields_flags_bearing_fault_shape():
+ state = _state_with_result()
+ current_readings = {
+ "temperature_c": 92.0,
+ "vibration_mm_s": 8.1,
+ "pressure_bar": 5.0,
+ "error_code": "BRG-02",
+ }
+
+ fields = build_default_review_fields(state, current_readings)
+
+ assert fields["confirmed_cause"] == "Worn bearing"
+ assert fields["fix_applied"] == "Inspect the bearing assembly."
+ assert fields["outcome"] == "resolved"
+ assert "vibration elevated" in fields["notes"]
+ assert "temperature elevated" in fields["notes"]
+ assert set(fields["symptoms"]) == {"elevated temperature", "elevated vibration"}
+ assert "low pressure" not in fields["symptoms"]
+ assert "elevated pressure" not in fields["symptoms"]
+
+
+def test_build_default_review_fields_flags_pressure_fault_shape():
+ state = _state_with_result(likely_cause="Pressure leak")
+ current_readings = {
+ "temperature_c": 77.0,
+ "vibration_mm_s": 2.4,
+ "pressure_bar": 2.8,
+ "error_code": "PRS-03",
+ }
+
+ fields = build_default_review_fields(state, current_readings)
+
+ # 77.0C is mildly above the 65-75C baseline too, per the pressure-loss
+ # scenario in the project reference — both symptoms are expected.
+ assert set(fields["symptoms"]) == {"low pressure", "elevated temperature"}
+
+
+def test_build_default_review_fields_normal_readings_have_no_symptoms():
+ state = _state_with_result()
+ current_readings = {
+ "temperature_c": 70.0,
+ "vibration_mm_s": 2.0,
+ "pressure_bar": 5.0,
+ "error_code": None,
+ }
+
+ fields = build_default_review_fields(state, current_readings)
+
+ assert fields["symptoms"] == []
+
+
+def test_build_incident_from_review_preserves_model_diagnosis_and_human_correction():
+ # This is the critical safety guarantee: a human correcting the model's
+ # guess must never overwrite the record of what the model actually said.
+ state = _state_with_result(likely_cause="Worn bearing")
+ current_readings = {
+ "temperature_c": 92.0,
+ "vibration_mm_s": 8.1,
+ "pressure_bar": 5.0,
+ "error_code": "BRG-02",
+ }
+
+ incident = build_incident_from_review(
+ state,
+ current_readings,
+ confirmed_cause="Loose access panel (not actually a bearing issue)",
+ fix_applied="Refastened the access panel.",
+ outcome="resolved",
+ notes="Technician found the vibration was from a loose panel, not the bearing.",
+ symptoms=["elevated vibration"],
+ )
+
+ assert incident.diagnosis == "Worn bearing"
+ assert incident.confirmed_cause == "Loose access panel (not actually a bearing issue)"
+ assert incident.diagnosis != incident.confirmed_cause
+ assert incident.fix_applied == "Refastened the access panel."
+ assert incident.temperature_c == 92.0
+ assert incident.vibration_mm_s == 8.1
+ assert incident.pressure_bar == 5.0
+ assert incident.error_code == "BRG-02"
+ assert incident.machine_id == "Machine A"
+
+
+def test_build_incident_from_review_keeps_confirmed_cause_when_human_agrees():
+ state = _state_with_result(likely_cause="Worn bearing")
+ current_readings = {"temperature_c": 92.0, "vibration_mm_s": 8.1, "pressure_bar": 5.0}
+
+ incident = build_incident_from_review(
+ state,
+ current_readings,
+ confirmed_cause="Worn bearing",
+ fix_applied="Bearing replaced.",
+ outcome="resolved",
+ notes="",
+ symptoms=["elevated vibration", "elevated temperature"],
+ )
+
+ assert incident.diagnosis == "Worn bearing"
+ assert incident.confirmed_cause == "Worn bearing"
diff --git a/ai_agents/offline_troubleshooting_agent/tests/test_embeddings.py b/ai_agents/offline_troubleshooting_agent/tests/test_embeddings.py
new file mode 100644
index 0000000..40d82f4
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/tests/test_embeddings.py
@@ -0,0 +1,54 @@
+from types import SimpleNamespace
+
+import pytest
+
+import memory.embeddings as embeddings_module
+
+
+class FakeClient:
+ def __init__(self, response):
+ self._response = response
+ self.calls: list[dict] = []
+
+ def embed(self, model, input):
+ self.calls.append({"model": model, "input": input})
+ return self._response
+
+
+def test_embed_text_returns_plain_list_of_floats(monkeypatch):
+ monkeypatch.delenv("OLLAMA_API_KEY", raising=False)
+ fake_client = FakeClient(SimpleNamespace(embeddings=[[0.1, 0.2, 0.3]]))
+ monkeypatch.setattr(embeddings_module, "get_client", lambda: fake_client)
+
+ result = embeddings_module.embed_text("bearing overheating vibration")
+
+ assert result == [0.1, 0.2, 0.3]
+ assert isinstance(result, list)
+ assert all(isinstance(value, float) for value in result)
+
+
+def test_embed_texts_returns_batch_in_input_order(monkeypatch):
+ monkeypatch.delenv("OLLAMA_API_KEY", raising=False)
+ fake_client = FakeClient(SimpleNamespace(embeddings=[[1.0, 2.0], [3.0, 4.0]]))
+ monkeypatch.setattr(embeddings_module, "get_client", lambda: fake_client)
+
+ result = embeddings_module.embed_texts(["first symptom", "second symptom"])
+
+ assert result == [[1.0, 2.0], [3.0, 4.0]]
+ assert fake_client.calls[0]["input"] == ["first symptom", "second symptom"]
+
+
+def test_embed_text_raises_via_assert_local_only_for_cloud_model(monkeypatch):
+ monkeypatch.delenv("OLLAMA_API_KEY", raising=False)
+ monkeypatch.setenv("EMBEDDING_MODEL", "nomic-embed-text:cloud")
+
+ with pytest.raises(RuntimeError):
+ embeddings_module.embed_text("anything")
+
+
+def test_embed_texts_raises_via_assert_local_only_for_cloud_model(monkeypatch):
+ monkeypatch.delenv("OLLAMA_API_KEY", raising=False)
+ monkeypatch.setenv("EMBEDDING_MODEL", "nomic-embed-text:cloud")
+
+ with pytest.raises(RuntimeError):
+ embeddings_module.embed_texts(["anything"])
diff --git a/ai_agents/offline_troubleshooting_agent/tests/test_incident_store.py b/ai_agents/offline_troubleshooting_agent/tests/test_incident_store.py
new file mode 100644
index 0000000..7401753
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/tests/test_incident_store.py
@@ -0,0 +1,144 @@
+import uuid
+from datetime import datetime
+
+import pytest
+from pydantic import ValidationError
+
+from memory.embeddings import embedding_health_check
+from memory.incident_store import get_incident, save_incident, search_incidents
+from memory.vectorai_client import delete_collection, health_check as vectorai_health_check
+from models.schemas import Incident
+
+TEST_COLLECTION = "incidents_test_scratch"
+
+
+def _services_reachable() -> bool:
+ try:
+ embedding_status = embedding_health_check()
+ vectorai_status = vectorai_health_check()
+ except Exception:
+ return False
+
+ return bool(
+ embedding_status.get("reachable")
+ and embedding_status.get("model_available")
+ and vectorai_status.get("reachable")
+ )
+
+
+SERVICES_REACHABLE = _services_reachable()
+
+
+def _build_incident(**overrides) -> Incident:
+ base = dict(
+ incident_id=str(uuid.uuid4()),
+ created_at=datetime(2026, 9, 20, 10, 0, 0),
+ machine_id="Machine A",
+ symptoms=["high temperature", "high vibration"],
+ temperature_c=92.0,
+ vibration_mm_s=8.1,
+ pressure_bar=5.0,
+ error_code="BRG-02",
+ diagnosis="Likely worn bearing.",
+ confirmed_cause="worn bearing",
+ fix_applied="bearing replacement",
+ outcome="resolved",
+ notes=None,
+ )
+ base.update(overrides)
+ return Incident(**base)
+
+
+def test_incident_missing_required_field_raises_validation_error():
+ with pytest.raises(ValidationError):
+ Incident(
+ incident_id=str(uuid.uuid4()),
+ created_at=datetime(2026, 9, 20, 10, 0, 0),
+ machine_id="Machine A",
+ symptoms=["high vibration"],
+ temperature_c=92.0,
+ vibration_mm_s=8.1,
+ pressure_bar=5.0,
+ error_code="BRG-02",
+ # diagnosis intentionally omitted
+ confirmed_cause="worn bearing",
+ fix_applied="bearing replacement",
+ outcome="resolved",
+ )
+
+
+def test_incident_round_trips_through_dump_and_validate():
+ incident = _build_incident()
+ dumped = incident.model_dump(mode="json")
+ restored = Incident.model_validate(dumped)
+ assert restored == incident
+
+
+ not SERVICES_REACHABLE,
+ reason="Requires a live local embedding model and a live Actian VectorAI instance.",
+)
+class TestIncidentStoreIntegration:
+ @classmethod
+ @pytest.fixture(scope="class", autouse=True)
+ def _cleanup_test_collection(cls):
+ yield
+ delete_collection(TEST_COLLECTION)
+
+ def test_save_and_get_incident_round_trips(self):
+ incident = _build_incident()
+ save_incident(incident, collection=TEST_COLLECTION)
+
+ fetched = get_incident(incident.incident_id, collection=TEST_COLLECTION)
+
+ assert fetched is not None
+ assert fetched.incident_id == incident.incident_id
+ assert fetched.confirmed_cause == incident.confirmed_cause
+ assert fetched.diagnosis == incident.diagnosis
+ assert fetched.temperature_c == incident.temperature_c
+ assert fetched.vibration_mm_s == incident.vibration_mm_s
+
+ def test_search_incidents_ranks_bearing_above_pressure_for_similar_wording(self):
+ bearing_incident = _build_incident(
+ incident_id=str(uuid.uuid4()),
+ symptoms=["high temperature", "high vibration"],
+ temperature_c=92.0,
+ vibration_mm_s=8.1,
+ pressure_bar=5.0,
+ error_code="BRG-02",
+ diagnosis="Likely worn bearing.",
+ confirmed_cause="worn bearing",
+ fix_applied="bearing replacement",
+ )
+ pressure_incident = _build_incident(
+ incident_id=str(uuid.uuid4()),
+ symptoms=["low pressure", "mildly elevated temperature"],
+ temperature_c=77.0,
+ vibration_mm_s=2.4,
+ pressure_bar=2.8,
+ error_code="PRS-03",
+ diagnosis="Likely pressure system leak.",
+ confirmed_cause="seal leak",
+ fix_applied="replaced seal",
+ )
+
+ save_incident(bearing_incident, collection=TEST_COLLECTION)
+ save_incident(pressure_incident, collection=TEST_COLLECTION)
+
+ # top_k is wider than 2 deliberately: this collection is shared across
+ # the tests in this class (per the spec's single dedicated test
+ # collection), so an earlier test's saved incident can also be
+ # present here. We only care that bearing outranks pressure, not that
+ # pressure is literally the #2 result.
+ results = search_incidents(
+ "machine running hot and shaking more than normal",
+ top_k=10,
+ collection=TEST_COLLECTION,
+ )
+
+ ids_in_order = [result["incident_id"] for result in results]
+ assert bearing_incident.incident_id in ids_in_order
+ assert pressure_incident.incident_id in ids_in_order
+ assert ids_in_order.index(bearing_incident.incident_id) < ids_in_order.index(
+ pressure_incident.incident_id
+ )
diff --git a/ai_agents/offline_troubleshooting_agent/tests/test_llm_client.py b/ai_agents/offline_troubleshooting_agent/tests/test_llm_client.py
new file mode 100644
index 0000000..9994079
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/tests/test_llm_client.py
@@ -0,0 +1,45 @@
+from types import SimpleNamespace
+
+import pytest
+
+import agent.llm_client as llm_client_module
+from agent.llm_client import assert_local_only
+
+
+def test_assert_local_only_raises_for_cloud_base_url(monkeypatch):
+ monkeypatch.delenv("OLLAMA_API_KEY", raising=False)
+ with pytest.raises(RuntimeError):
+ assert_local_only("https://ollama.com", "qwen3:4b-instruct")
+
+
[email protected]("model", ["gpt-oss:120b-cloud", "gpt-oss-120b-cloud"])
+def test_assert_local_only_raises_for_cloud_model(model, monkeypatch):
+ monkeypatch.delenv("OLLAMA_API_KEY", raising=False)
+ with pytest.raises(RuntimeError):
+ assert_local_only("http://localhost:11434", model)
+
+
+def test_assert_local_only_raises_when_api_key_set(monkeypatch):
+ monkeypatch.setenv("OLLAMA_API_KEY", "some-cloud-key")
+ with pytest.raises(RuntimeError):
+ assert_local_only("http://localhost:11434", "qwen3:4b-instruct")
+
+
+def test_assert_local_only_passes_for_normal_local_config(monkeypatch):
+ monkeypatch.delenv("OLLAMA_API_KEY", raising=False)
+ assert_local_only("http://localhost:11434", "qwen3:4b-instruct")
+
+
+def test_health_check_matches_untagged_model_against_latest_tag(monkeypatch):
+ monkeypatch.delenv("OLLAMA_API_KEY", raising=False)
+ monkeypatch.setenv("OLLAMA_BASE_URL", "http://localhost:11434")
+ monkeypatch.setenv("OLLAMA_MODEL", "qwen3")
+
+ fake_models = [SimpleNamespace(model="qwen3:latest")]
+ fake_client = SimpleNamespace(list=lambda: SimpleNamespace(models=fake_models))
+ monkeypatch.setattr(llm_client_module, "get_client", lambda: fake_client)
+
+ result = llm_client_module.health_check()
+
+ assert result["reachable"] is True
+ assert result["model_available"] is True
diff --git a/ai_agents/offline_troubleshooting_agent/tests/test_manual.py b/ai_agents/offline_troubleshooting_agent/tests/test_manual.py
new file mode 100644
index 0000000..7d94b3b
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/tests/test_manual.py
@@ -0,0 +1,58 @@
+import os
+
+import pytest
+
+from memory.embeddings import embedding_health_check
+from memory.manual import ingest_manual_documents, search_manual_chunks
+from memory.vectorai_client import health_check as vectorai_health_check
+
+PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+MANUAL_PATHS = [
+ os.path.join(PROJECT_ROOT, "documents", "machine_manual.md"),
+ os.path.join(PROJECT_ROOT, "documents", "troubleshooting_guide.md"),
+]
+
+
+def _services_reachable() -> bool:
+ try:
+ embedding_status = embedding_health_check()
+ vectorai_status = vectorai_health_check()
+ except Exception:
+ return False
+
+ return bool(
+ embedding_status.get("reachable")
+ and embedding_status.get("model_available")
+ and vectorai_status.get("reachable")
+ )
+
+
+SERVICES_REACHABLE = _services_reachable()
+
+pytestmark = pytest.mark.skipif(
+ not SERVICES_REACHABLE,
+ reason="Requires a live local embedding model and a live Actian VectorAI instance.",
+)
+
+
[email protected](scope="module", autouse=True)
+def _seed_manual_collection():
+ ingest_manual_documents(MANUAL_PATHS)
+
+
+def test_bearing_query_retrieves_bearing_component():
+ results = search_manual_chunks("bearing vibration overheating", top_k=3)
+ components = [result["component"] for result in results]
+ assert "bearing" in components
+
+
+def test_cooling_query_retrieves_cooling_component():
+ results = search_manual_chunks("cooling fan airflow overheating", top_k=3)
+ components = [result["component"] for result in results]
+ assert "cooling" in components
+
+
+def test_pressure_query_retrieves_pressure_component():
+ results = search_manual_chunks("pressure drop leak seal", top_k=3)
+ components = [result["component"] for result in results]
+ assert "pressure" in components
diff --git a/ai_agents/offline_troubleshooting_agent/tests/test_network_status.py b/ai_agents/offline_troubleshooting_agent/tests/test_network_status.py
new file mode 100644
index 0000000..7f4dfec
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/tests/test_network_status.py
@@ -0,0 +1,41 @@
+import socket
+from contextlib import contextmanager
+
+from util.network_status import is_online
+
+
+@contextmanager
+def _fake_socket(open_succeeds: bool):
+ class FakeConnection:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ return False
+
+ def fake_create_connection(address, timeout=None):
+ if open_succeeds:
+ return FakeConnection()
+ raise OSError("connection refused")
+
+ yield fake_create_connection
+
+
+def test_is_online_returns_true_when_connection_succeeds(monkeypatch):
+ with _fake_socket(open_succeeds=True) as fake_create_connection:
+ monkeypatch.setattr(socket, "create_connection", fake_create_connection)
+ assert is_online(timeout=1.0) is True
+
+
+def test_is_online_returns_false_when_connection_fails(monkeypatch):
+ with _fake_socket(open_succeeds=False) as fake_create_connection:
+ monkeypatch.setattr(socket, "create_connection", fake_create_connection)
+ assert is_online(timeout=1.0) is False
+
+
+def test_is_online_returns_false_on_timeout(monkeypatch):
+ def fake_create_connection(address, timeout=None):
+ raise TimeoutError("timed out")
+
+ monkeypatch.setattr(socket, "create_connection", fake_create_connection)
+ assert is_online(timeout=1.0) is False
diff --git a/ai_agents/offline_troubleshooting_agent/tests/test_safety.py b/ai_agents/offline_troubleshooting_agent/tests/test_safety.py
new file mode 100644
index 0000000..fdd64c2
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/tests/test_safety.py
@@ -0,0 +1,66 @@
+import inspect
+
+from agent.prompts import SYSTEM_PROMPT
+from agent.state import InvestigationState
+from agent.tools import AgentTools
+from memory.incident_store import save_incident
+from simulator.machine import Machine
+
+# Every public method on Machine that changes its operating state. If a tool
+# method's source references any of these, it has actuation capability it
+# shouldn't have (per section 25: the agent must never directly control
+# machinery).
+FORBIDDEN_MACHINE_MUTATORS = {"reset_machine", "start_fault", "advance_simulation", "trigger_fault"}
+
+
+def _build_tools() -> AgentTools:
+ machine = Machine(seed=1)
+ state = InvestigationState(
+ investigation_id="safety-test",
+ objective="test",
+ current_readings=machine.get_current_readings().model_dump(mode="json"),
+ )
+ return AgentTools(machine=machine, history=machine.history, state=state)
+
+
+def test_tool_methods_never_reference_machine_mutating_operations():
+ tools = _build_tools()
+ for fn in tools.tool_list():
+ source = inspect.getsource(fn)
+ for forbidden in FORBIDDEN_MACHINE_MUTATORS:
+ assert forbidden not in source, (
+ f"{fn.__name__} references '{forbidden}', a machine-mutating operation — "
+ "the tool surface must have zero actuation capability, by design."
+ )
+
+
+def test_save_incident_is_never_in_tool_list():
+ tools = _build_tools()
+ tool_names = {fn.__name__ for fn in tools.tool_list()}
+ assert "save_incident" not in tool_names
+ assert save_incident not in tools.tool_list()
+
+
+def test_system_prompt_contains_required_safety_language():
+ prompt = SYSTEM_PROMPT.lower()
+
+ assert "simulation" in prompt or "demo" in prompt, (
+ "prompt must frame this as a simulation/demo assistant"
+ )
+ assert "not a certified" in prompt, (
+ "prompt must explicitly disclaim being a certified safety system"
+ )
+
+ assert "bypass" in prompt and "interlock" in prompt, (
+ "prompt must instruct the model to never bypass interlocks"
+ )
+ assert "bypass" in prompt and ("safety mechanism" in prompt or "alarm" in prompt), (
+ "prompt must instruct the model to never disable alarms / bypass safety mechanisms"
+ )
+
+ assert "directly control" in prompt and "machin" in prompt, (
+ "prompt must state the agent never directly controls machinery"
+ )
+
+ assert "inspect" in prompt, "prompt must recommend inspection as the safe alternative"
+ assert "unsafe" in prompt, "prompt must warn against unsafe control actions"
diff --git a/ai_agents/offline_troubleshooting_agent/tests/test_simulator.py b/ai_agents/offline_troubleshooting_agent/tests/test_simulator.py
new file mode 100644
index 0000000..d3291b9
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/tests/test_simulator.py
@@ -0,0 +1,92 @@
+import pytest
+
+from simulator.machine import (
+ Machine,
+ PRESSURE_RANGE,
+ TEMP_RANGE,
+ VIBRATION_RANGE,
+)
+from simulator.scenarios import FAULT_TARGETS, trigger_fault
+
+
+def test_idle_readings_stay_within_baseline_ranges():
+ machine = Machine(seed=42)
+
+ for _ in range(200):
+ machine.advance_simulation()
+ reading = machine.get_current_readings()
+ assert TEMP_RANGE[0] <= reading.temperature_c <= TEMP_RANGE[1]
+ assert VIBRATION_RANGE[0] <= reading.vibration_mm_s <= VIBRATION_RANGE[1]
+ assert PRESSURE_RANGE[0] <= reading.pressure_bar <= PRESSURE_RANGE[1]
+ assert reading.status == "running"
+ assert reading.error_code is None
+
+ history = machine.history.get_recent_history(limit=200)
+ assert len(history) == 200
+
+
+ "fault_type,error_code",
+ [("bearing", "BRG-02"), ("cooling", "TMP-04"), ("pressure", "PRS-03")],
+)
+def test_fault_scenarios_reach_intended_error_code(fault_type, error_code):
+ machine = Machine(seed=7)
+ trigger_fault(machine, fault_type)
+ machine.advance_simulation(steps=FAULT_TARGETS[fault_type].total_steps + 5)
+
+ reading = machine.get_current_readings()
+ assert reading.error_code == error_code
+ assert reading.status == "fault"
+
+
+def test_bearing_fault_pattern():
+ machine = Machine(seed=7)
+ trigger_fault(machine, "bearing")
+ machine.advance_simulation(steps=FAULT_TARGETS["bearing"].total_steps + 5)
+
+ reading = machine.get_current_readings()
+ assert reading.temperature_c > TEMP_RANGE[1]
+ assert reading.vibration_mm_s > VIBRATION_RANGE[1] * 2
+ assert PRESSURE_RANGE[0] - 0.5 <= reading.pressure_bar <= PRESSURE_RANGE[1] + 0.5
+
+
+def test_cooling_fault_pattern():
+ machine = Machine(seed=7)
+ trigger_fault(machine, "cooling")
+ machine.advance_simulation(steps=FAULT_TARGETS["cooling"].total_steps + 5)
+
+ reading = machine.get_current_readings()
+ assert reading.temperature_c > TEMP_RANGE[1]
+ assert VIBRATION_RANGE[0] - 0.5 <= reading.vibration_mm_s <= VIBRATION_RANGE[1] + 0.5
+ assert PRESSURE_RANGE[0] - 0.5 <= reading.pressure_bar <= PRESSURE_RANGE[1] + 0.5
+
+
+def test_pressure_fault_pattern():
+ machine = Machine(seed=7)
+ trigger_fault(machine, "pressure")
+ machine.advance_simulation(steps=FAULT_TARGETS["pressure"].total_steps + 5)
+
+ reading = machine.get_current_readings()
+ assert reading.pressure_bar < PRESSURE_RANGE[0]
+ assert reading.temperature_c > TEMP_RANGE[1]
+ assert VIBRATION_RANGE[0] - 0.5 <= reading.vibration_mm_s <= VIBRATION_RANGE[1] + 0.5
+
+
+def test_reset_machine_returns_to_normal_baseline_after_fault():
+ machine = Machine(seed=3)
+ trigger_fault(machine, "bearing")
+ machine.advance_simulation(steps=FAULT_TARGETS["bearing"].total_steps + 5)
+ assert machine.get_current_readings().error_code == "BRG-02"
+
+ machine.reset_machine()
+ reading = machine.get_current_readings()
+ assert TEMP_RANGE[0] <= reading.temperature_c <= TEMP_RANGE[1]
+ assert VIBRATION_RANGE[0] <= reading.vibration_mm_s <= VIBRATION_RANGE[1]
+ assert PRESSURE_RANGE[0] <= reading.pressure_bar <= PRESSURE_RANGE[1]
+ assert reading.status == "running"
+ assert reading.error_code is None
+
+ machine.advance_simulation(steps=5)
+ reading = machine.get_current_readings()
+ assert reading.error_code is None
+ assert reading.status == "running"
diff --git a/ai_agents/offline_troubleshooting_agent/tests/test_tools.py b/ai_agents/offline_troubleshooting_agent/tests/test_tools.py
new file mode 100644
index 0000000..06a6f83
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/tests/test_tools.py
@@ -0,0 +1,144 @@
+import uuid
+
+import pytest
+
+from agent.state import InvestigationState
+from agent.tools import AgentTools
+from memory.embeddings import embedding_health_check
+from memory.vectorai_client import health_check as vectorai_health_check
+from simulator.machine import Machine
+
+
+def _services_reachable() -> bool:
+ try:
+ embedding_status = embedding_health_check()
+ vectorai_status = vectorai_health_check()
+ except Exception:
+ return False
+
+ return bool(
+ embedding_status.get("reachable")
+ and embedding_status.get("model_available")
+ and vectorai_status.get("reachable")
+ )
+
+
+SERVICES_REACHABLE = _services_reachable()
+
+
+def _build_tools(seed: int = 1) -> AgentTools:
+ machine = Machine(seed=seed)
+ state = InvestigationState(
+ investigation_id=str(uuid.uuid4()), objective="Investigate test fault"
+ )
+ return AgentTools(machine=machine, history=machine.history, state=state)
+
+
+def test_get_current_readings_returns_dict_and_logs_call():
+ tools = _build_tools()
+
+ result = tools.get_current_readings()
+
+ assert isinstance(result, dict)
+ expected_keys = {
+ "temperature_c",
+ "vibration_mm_s",
+ "pressure_bar",
+ "status",
+ "error_code",
+ "timestamp",
+ }
+ assert expected_keys <= set(result.keys())
+ assert len(tools.state.tool_calls) == 1
+ assert tools.state.tool_calls[0]["name"] == "get_current_readings"
+
+
+def test_get_recent_history_returns_list_of_dicts_and_logs_call():
+ tools = _build_tools()
+ tools.machine.advance_simulation(steps=5)
+
+ result = tools.get_recent_history(limit=3)
+
+ assert isinstance(result, list)
+ assert len(result) == 3
+ assert all(isinstance(item, dict) for item in result)
+ assert len(tools.state.tool_calls) == 1
+ assert tools.state.tool_calls[0]["name"] == "get_recent_history"
+ assert tools.state.tool_calls[0]["args"] == {"limit": 3}
+
+
+def test_save_finding_appends_to_findings_and_logs_call():
+ tools = _build_tools()
+
+ confirmation = tools.save_finding("vibration is elevated", "vibration reading of 8 mm/s")
+
+ assert confirmation == "Finding recorded."
+ assert tools.state.findings == [
+ "vibration is elevated (evidence: vibration reading of 8 mm/s)"
+ ]
+ assert len(tools.state.tool_calls) == 1
+ assert tools.state.tool_calls[0]["name"] == "save_finding"
+
+
+def test_finish_investigation_stores_final_result_and_logs_call():
+ tools = _build_tools()
+
+ result = tools.finish_investigation(
+ likely_cause="worn bearing",
+ confidence=0.8,
+ recommendation="Inspect the bearing assembly.",
+ supporting_evidence=["vibration is elevated"],
+ retrieved_incident_ids=[],
+ manual_sources=["BRG-02 — Bearing vibration warning"],
+ )
+
+ assert result["likely_cause"] == "worn bearing"
+ assert result["confidence"] == 0.8
+ assert tools.state.final_result == result
+ assert len(tools.state.tool_calls) == 1
+ assert tools.state.tool_calls[0]["name"] == "finish_investigation"
+
+
+def test_tool_list_does_not_include_save_incident():
+ tools = _build_tools()
+
+ names = [tool.__name__ for tool in tools.tool_list()]
+
+ assert "save_incident" not in names
+ assert names == [
+ "get_current_readings",
+ "get_recent_history",
+ "search_manual",
+ "search_past_incidents",
+ "save_finding",
+ "finish_investigation",
+ ]
+
+
+ not SERVICES_REACHABLE,
+ reason="Requires a live local embedding model and a live Actian VectorAI instance.",
+)
+def test_search_manual_populates_retrieved_manual_chunks():
+ tools = _build_tools()
+
+ results = tools.search_manual("bearing vibration overheating", top_k=3)
+
+ assert results
+ assert tools.state.retrieved_manual_chunks == results
+ assert len(tools.state.tool_calls) == 1
+ assert tools.state.tool_calls[0]["name"] == "search_manual"
+
+
+ not SERVICES_REACHABLE,
+ reason="Requires a live local embedding model and a live Actian VectorAI instance.",
+)
+def test_search_past_incidents_populates_retrieved_incidents():
+ tools = _build_tools()
+
+ results = tools.search_past_incidents("high temperature and high vibration", top_k=3)
+
+ assert tools.state.retrieved_incidents == results
+ assert len(tools.state.tool_calls) == 1
+ assert tools.state.tool_calls[0]["name"] == "search_past_incidents"
diff --git a/ai_agents/offline_troubleshooting_agent/tests/test_vectorai_client.py b/ai_agents/offline_troubleshooting_agent/tests/test_vectorai_client.py
new file mode 100644
index 0000000..13c0288
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/tests/test_vectorai_client.py
@@ -0,0 +1,143 @@
+from types import SimpleNamespace
+
+from actian_vectorai import Distance, PointStruct
+
+import memory.vectorai_client as vectorai_module
+
+
+class FakeCollections:
+ def __init__(self, existing_names=()):
+ self.create_calls: list[dict] = []
+ self.exists_calls: list[str] = []
+ self._existing = set(existing_names)
+
+ def exists(self, name):
+ self.exists_calls.append(name)
+ return name in self._existing
+
+ def create(self, name, *, vectors_config=None, **kwargs):
+ self.create_calls.append({"name": name, "vectors_config": vectors_config})
+ self._existing.add(name)
+
+
+class FakeVde:
+ def __init__(self):
+ self.open_calls: list[str] = []
+
+ def open_collection(self, name):
+ self.open_calls.append(name)
+ return True
+
+
+class FakePoints:
+ def __init__(self, search_results=None):
+ self.upsert_calls: list[dict] = []
+ self.search_calls: list[dict] = []
+ self._search_results = search_results or []
+
+ def upsert(self, collection_name, points):
+ self.upsert_calls.append({"collection_name": collection_name, "points": points})
+
+ def search(self, collection_name, vector, *, limit=10, **kwargs):
+ self.search_calls.append(
+ {"collection_name": collection_name, "vector": vector, "limit": limit}
+ )
+ return self._search_results
+
+
+class FakeClientThatFailsHealthCheck:
+ def health_check(self):
+ raise ConnectionError("connection refused")
+
+
+def test_ensure_collection_creates_and_opens_when_missing(monkeypatch):
+ fake_collections = FakeCollections(existing_names=())
+ fake_vde = FakeVde()
+ fake_client = SimpleNamespace(collections=fake_collections, vde=fake_vde)
+ monkeypatch.setattr(vectorai_module, "get_client", lambda: fake_client)
+
+ vectorai_module.ensure_collection("manual_chunks", dim=768)
+
+ assert fake_collections.exists_calls == ["manual_chunks"]
+ assert len(fake_collections.create_calls) == 1
+ call = fake_collections.create_calls[0]
+ assert call["name"] == "manual_chunks"
+ assert call["vectors_config"].size == 768
+ assert call["vectors_config"].distance == Distance.Cosine
+ assert fake_vde.open_calls == ["manual_chunks"]
+
+
+def test_ensure_collection_reopens_without_creating_when_already_exists(monkeypatch):
+ # This is the specific behavior that prevents a restart-time reopen from
+ # shadowing real on-disk data with an empty freshly-created collection.
+ fake_collections = FakeCollections(existing_names=("manual_chunks",))
+ fake_vde = FakeVde()
+ fake_client = SimpleNamespace(collections=fake_collections, vde=fake_vde)
+ monkeypatch.setattr(vectorai_module, "get_client", lambda: fake_client)
+
+ vectorai_module.ensure_collection("manual_chunks", dim=768)
+
+ assert fake_collections.exists_calls == ["manual_chunks"]
+ assert fake_collections.create_calls == []
+ assert fake_vde.open_calls == ["manual_chunks"]
+
+
+def test_open_collection_calls_vde_open_collection(monkeypatch):
+ fake_vde = FakeVde()
+ fake_client = SimpleNamespace(vde=fake_vde)
+ monkeypatch.setattr(vectorai_module, "get_client", lambda: fake_client)
+
+ vectorai_module.open_collection("incidents")
+
+ assert fake_vde.open_calls == ["incidents"]
+
+
+def test_upsert_point_builds_point_struct_and_calls_upsert(monkeypatch):
+ # PointStruct.id only accepts a non-negative int or a valid UUID string
+ # (confirmed against the real actian-vectorai-client SDK), so this uses
+ # a UUID rather than an arbitrary string like "inc-1".
+ point_id = "12345678-1234-5678-1234-567812345678"
+
+ fake_points = FakePoints()
+ fake_client = SimpleNamespace(points=fake_points)
+ monkeypatch.setattr(vectorai_module, "get_client", lambda: fake_client)
+
+ vectorai_module.upsert_point(
+ "incidents", point_id, [0.1, 0.2, 0.3], {"cause": "worn bearing"}
+ )
+
+ assert len(fake_points.upsert_calls) == 1
+ call = fake_points.upsert_calls[0]
+ assert call["collection_name"] == "incidents"
+ assert len(call["points"]) == 1
+
+ point = call["points"][0]
+ assert isinstance(point, PointStruct)
+ assert point.id == point_id
+ assert point.vector == [0.1, 0.2, 0.3]
+ assert point.payload == {"cause": "worn bearing"}
+
+
+def test_search_calls_client_with_right_args_and_normalizes_result(monkeypatch):
+ fake_result = SimpleNamespace(id="inc-1", score=0.87, payload={"cause": "worn bearing"})
+ fake_points = FakePoints(search_results=[fake_result])
+ fake_client = SimpleNamespace(points=fake_points)
+ monkeypatch.setattr(vectorai_module, "get_client", lambda: fake_client)
+
+ results = vectorai_module.search("incidents", [0.1, 0.2, 0.3], top_k=3)
+
+ assert fake_points.search_calls == [
+ {"collection_name": "incidents", "vector": [0.1, 0.2, 0.3], "limit": 3}
+ ]
+ assert results == [{"id": "inc-1", "score": 0.87, "payload": {"cause": "worn bearing"}}]
+
+
+def test_health_check_returns_unreachable_without_raising(monkeypatch):
+ monkeypatch.setattr(
+ vectorai_module, "get_client", lambda: FakeClientThatFailsHealthCheck()
+ )
+
+ result = vectorai_module.health_check()
+
+ assert result["reachable"] is False
+ assert "connection refused" in result["error"]
diff --git a/ai_agents/offline_troubleshooting_agent/ui/__init__.py b/ai_agents/offline_troubleshooting_agent/ui/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/ai_agents/offline_troubleshooting_agent/ui/gradio_app.py b/ai_agents/offline_troubleshooting_agent/ui/gradio_app.py
new file mode 100644
index 0000000..4a728ae
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/ui/gradio_app.py
@@ -0,0 +1,344 @@
+import gradio as gr
+
+from agent.confirmation import build_default_review_fields, build_incident_from_review
+from agent.harness import run_investigation
+from memory.incident_store import save_incident
+from models.schemas import MachineReading
+from simulator.machine import Machine
+from simulator.scenarios import trigger_fault
+from util.network_status import is_online
+
+machine = Machine()
+
+TICK_SECONDS = 1
+NETWORK_CHECK_SECONDS = 5
+
+TOOL_LABELS = {
+ "get_current_readings": "Checked current readings",
+ "get_recent_history": "Reviewed recent history",
+ "search_manual": "Searched equipment manual",
+ "search_past_incidents": "Searched previous incidents",
+}
+
+INITIAL_INVESTIGATION_MD = "### Investigation\n\n" + "\n".join(
+ f"- ○ {label}" for label in TOOL_LABELS.values()
+)
+INITIAL_MEMORY_MD = "### Retrieved Memory\n\nNo similar previous incident found."
+INITIAL_RECOMMENDATION_MD = "### Recommendation\n\n_Not started yet._"
+
+
+def _format_status(reading: MachineReading) -> tuple[str, str, str, str, str]:
+ return (
+ f"{reading.temperature_c:.1f}",
+ f"{reading.vibration_mm_s:.2f}",
+ f"{reading.pressure_bar:.2f}",
+ reading.status,
+ reading.error_code or "None",
+ )
+
+
+def _current_status() -> tuple[str, str, str, str, str]:
+ return _format_status(machine.get_current_readings())
+
+
+def _network_status_markdown() -> str:
+ if is_online():
+ return "🟢 **Online**"
+ return "🔴 **Offline** (running locally)"
+
+
+def _tick() -> tuple[str, str, str, str, str]:
+ machine.advance_simulation(1)
+ return _current_status()
+
+
+def _trigger_bearing() -> tuple[str, str, str, str, str]:
+ trigger_fault(machine, "bearing")
+ return _current_status()
+
+
+def _trigger_cooling() -> tuple[str, str, str, str, str]:
+ trigger_fault(machine, "cooling")
+ return _current_status()
+
+
+def _trigger_pressure() -> tuple[str, str, str, str, str]:
+ trigger_fault(machine, "pressure")
+ return _current_status()
+
+
+def _reset() -> tuple[str, str, str, str, str]:
+ machine.reset_machine()
+ return _current_status()
+
+
+def _build_investigation_objective() -> str:
+ reading = machine.get_current_readings()
+ if reading.error_code:
+ return (
+ f"Investigate {reading.error_code} fault on Machine A "
+ f"(status: {reading.status})."
+ )
+ return f"Investigate current condition of Machine A (status: {reading.status})."
+
+
+def _format_investigation_markdown(state) -> str:
+ completed_tool_names = {call["name"] for call in state.tool_calls}
+ checklist_lines = [
+ f"- {'✓' if name in completed_tool_names else '○'} {label}"
+ for name, label in TOOL_LABELS.items()
+ ]
+ sections = ["### Investigation", "\n".join(checklist_lines)]
+
+ if state.findings:
+ finding_lines = [f"- {finding}" for finding in state.findings]
+ sections.append("**Findings:**\n" + "\n".join(finding_lines))
+
+ return "\n\n".join(sections)
+
+
+def _format_retrieved_memory_markdown(state) -> str:
+ if not state.retrieved_incidents:
+ return "### Retrieved Memory\n\nNo similar previous incident found."
+
+ lines = ["### Retrieved Memory", ""]
+ for incident in state.retrieved_incidents:
+ created_at = incident.get("created_at", "unknown date")
+ symptoms = incident.get("symptoms") or []
+ symptoms_text = ", ".join(symptoms) if symptoms else "not recorded"
+ score = incident.get("score")
+ similarity = f"{score:.2f}" if isinstance(score, (int, float)) else "n/a"
+
+ lines.append("**Similar incident**")
+ lines.append(f"- Date: {created_at}")
+ lines.append(f"- Symptoms: {symptoms_text}")
+ lines.append(f"- Cause: {incident.get('confirmed_cause', 'unknown')}")
+ lines.append(f"- Fix: {incident.get('fix_applied', 'unknown')}")
+ lines.append(f"- Similarity: {similarity}")
+ lines.append("")
+
+ return "\n".join(lines).rstrip()
+
+
+def _format_recommendation_markdown(state) -> str:
+ if state.final_result is None:
+ return "### Recommendation\n\n_Investigation in progress..._"
+
+ result = state.final_result
+ lines = [
+ "### Recommendation",
+ "",
+ f"**Likely cause:** {result.get('likely_cause')}",
+ f"**Confidence:** {result.get('confidence')}",
+ f"**Recommendation:** {result.get('recommendation')}",
+ ]
+
+ evidence = result.get("supporting_evidence") or []
+ if evidence:
+ lines.append("")
+ lines.append("**Supporting evidence:**")
+ lines.extend(f"- {item}" for item in evidence)
+
+ manual_sources = result.get("manual_sources") or []
+ if manual_sources:
+ lines.append("")
+ lines.append("**Manual references:**")
+ lines.extend(f"- {item}" for item in manual_sources)
+
+ incident_ids = result.get("retrieved_incident_ids") or []
+ if incident_ids:
+ lines.append("")
+ lines.append("**Past incidents used:**")
+ lines.extend(f"- {item}" for item in incident_ids)
+
+ return "\n".join(lines)
+
+
+OUTCOME_OPTIONS = ["resolved", "unresolved", "needs follow-up"]
+
+
+def _run_investigation():
+ objective = _build_investigation_objective()
+ for state in run_investigation(machine, machine.history, objective):
+ review_ready = state.final_result is not None
+
+ if review_ready:
+ defaults = build_default_review_fields(state, state.current_readings)
+ confirmed_cause_update = defaults["confirmed_cause"]
+ fix_applied_update = defaults["fix_applied"]
+ outcome_update = defaults["outcome"]
+ notes_update = defaults["notes"]
+ symptoms_update = ", ".join(defaults["symptoms"])
+ else:
+ confirmed_cause_update = gr.update()
+ fix_applied_update = gr.update()
+ outcome_update = gr.update()
+ notes_update = gr.update()
+ symptoms_update = gr.update()
+
+ yield (
+ _format_investigation_markdown(state),
+ _format_retrieved_memory_markdown(state),
+ _format_recommendation_markdown(state),
+ state,
+ gr.update(visible=review_ready),
+ confirmed_cause_update,
+ fix_applied_update,
+ outcome_update,
+ notes_update,
+ symptoms_update,
+ "",
+ )
+
+
+def _confirm_and_save(
+ investigation_state, confirmed_cause, fix_applied, outcome, notes, symptoms_text
+):
+ if investigation_state is None or investigation_state.final_result is None:
+ return gr.update(visible=True), "No completed investigation to save."
+
+ symptoms = [s.strip() for s in symptoms_text.split(",") if s.strip()]
+ incident = build_incident_from_review(
+ investigation_state,
+ investigation_state.current_readings,
+ confirmed_cause=confirmed_cause,
+ fix_applied=fix_applied,
+ outcome=outcome,
+ notes=notes,
+ symptoms=symptoms,
+ )
+ save_incident(incident)
+
+ return gr.update(visible=False), f"Saved incident `{incident.incident_id}` to memory."
+
+
+def _discard_review():
+ return gr.update(visible=False), "Discarded — nothing was saved to memory."
+
+
+def build_app() -> gr.Blocks:
+ with gr.Blocks(
+ title="Offline Troubleshooting Agent",
+ analytics_enabled=False,
+ ) as app:
+ gr.Markdown("# Offline Troubleshooting Agent — Machine A")
+ network_status_md = gr.Markdown(value=_network_status_markdown())
+
+ with gr.Row():
+ temperature = gr.Textbox(label="Temperature (°C)", interactive=False)
+ vibration = gr.Textbox(label="Vibration (mm/s)", interactive=False)
+ pressure = gr.Textbox(label="Pressure (bar)", interactive=False)
+ status = gr.Textbox(label="Status", interactive=False)
+ error_code = gr.Textbox(label="Error code", interactive=False)
+
+ status_outputs = [temperature, vibration, pressure, status, error_code]
+
+ with gr.Row():
+ bearing_btn = gr.Button("Trigger Bearing Fault")
+ cooling_btn = gr.Button("Trigger Cooling Fault")
+ pressure_btn = gr.Button("Trigger Pressure Fault")
+ reset_btn = gr.Button("Reset Machine")
+
+ bearing_btn.click(
+ fn=_trigger_bearing, inputs=None, outputs=status_outputs, api_name="trigger_bearing"
+ )
+ cooling_btn.click(
+ fn=_trigger_cooling, inputs=None, outputs=status_outputs, api_name="trigger_cooling"
+ )
+ pressure_btn.click(
+ fn=_trigger_pressure, inputs=None, outputs=status_outputs, api_name="trigger_pressure"
+ )
+ reset_btn.click(fn=_reset, inputs=None, outputs=status_outputs, api_name="reset_machine")
+
+ timer = gr.Timer(TICK_SECONDS)
+ timer.tick(fn=_tick, inputs=None, outputs=status_outputs, api_name="tick")
+
+ # Separate, slower timer purely for the network status badge, kept
+ # decoupled from the 1-second simulation timer so a network check
+ # never adds lag to the machine readings updating every second. This
+ # is purely informational display, not a gate on any functionality.
+ network_timer = gr.Timer(NETWORK_CHECK_SECONDS)
+ network_timer.tick(
+ fn=_network_status_markdown,
+ inputs=None,
+ outputs=[network_status_md],
+ api_name="network_status_tick",
+ )
+
+ app.load(fn=_current_status, inputs=None, outputs=status_outputs, api_name="current_status")
+ app.load(
+ fn=_network_status_markdown,
+ inputs=None,
+ outputs=[network_status_md],
+ api_name="network_status_on_load",
+ )
+
+ start_investigation_btn = gr.Button("Start Investigation")
+
+ with gr.Row():
+ investigation_md = gr.Markdown(value=INITIAL_INVESTIGATION_MD)
+ retrieved_memory_md = gr.Markdown(value=INITIAL_MEMORY_MD)
+ recommendation_md = gr.Markdown(value=INITIAL_RECOMMENDATION_MD)
+
+ investigation_state = gr.State(None)
+
+ with gr.Group(visible=False) as review_group:
+ gr.Markdown(
+ "### Review & Confirm\n\nEdit anything below before saving — nothing is "
+ "written to memory until you click Confirm."
+ )
+ confirmed_cause_tb = gr.Textbox(label="Confirmed cause", interactive=True)
+ fix_applied_tb = gr.Textbox(label="Fix applied", interactive=True)
+ outcome_dd = gr.Dropdown(
+ label="Outcome", choices=OUTCOME_OPTIONS, value="resolved", interactive=True
+ )
+ notes_tb = gr.Textbox(label="Notes", interactive=True, lines=3)
+ symptoms_tb = gr.Textbox(
+ label="Symptoms (comma-separated)", interactive=True
+ )
+ with gr.Row():
+ confirm_btn = gr.Button("Confirm & Save to Memory", variant="primary")
+ discard_btn = gr.Button("Discard (don't save)")
+ save_status_md = gr.Markdown(value="")
+
+ start_investigation_btn.click(
+ fn=_run_investigation,
+ inputs=None,
+ outputs=[
+ investigation_md,
+ retrieved_memory_md,
+ recommendation_md,
+ investigation_state,
+ review_group,
+ confirmed_cause_tb,
+ fix_applied_tb,
+ outcome_dd,
+ notes_tb,
+ symptoms_tb,
+ save_status_md,
+ ],
+ api_name="start_investigation",
+ )
+
+ confirm_btn.click(
+ fn=_confirm_and_save,
+ inputs=[
+ investigation_state,
+ confirmed_cause_tb,
+ fix_applied_tb,
+ outcome_dd,
+ notes_tb,
+ symptoms_tb,
+ ],
+ outputs=[review_group, save_status_md],
+ api_name="confirm_and_save",
+ )
+
+ discard_btn.click(
+ fn=_discard_review,
+ inputs=None,
+ outputs=[review_group, save_status_md],
+ api_name="discard_review",
+ )
+
+ return app
diff --git a/ai_agents/offline_troubleshooting_agent/util/__init__.py b/ai_agents/offline_troubleshooting_agent/util/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/ai_agents/offline_troubleshooting_agent/util/network_status.py b/ai_agents/offline_troubleshooting_agent/util/network_status.py
new file mode 100644
index 0000000..402315e
--- /dev/null
+++ b/ai_agents/offline_troubleshooting_agent/util/network_status.py
@@ -0,0 +1,17 @@
+import socket
+
+NETWORK_CHECK_HOST = "1.1.1.1"
+NETWORK_CHECK_PORT = 53
+
+
+def is_online(timeout: float = 1.0) -> bool:
+ """Best-effort check for internet connectivity.
+
+ Attempts a short-timeout TCP connection to a public address. Returns
+ True if it succeeds (online), False if it fails or times out (offline).
+ """
+ try:
+ with socket.create_connection((NETWORK_CHECK_HOST, NETWORK_CHECK_PORT), timeout=timeout):
+ return True
+ except OSError:
+ return False