SIGNAL

TODAY

INTEL

SETUP

DOCS

ADMIN

CLIENTS

OPS

SALES

📖 DOCS NAVIGATION

🔍


📖 SecondBrain Docs

V2.5

Full reference documentation for the SecondBrain autonomous IT MSP intelligence platform.

1. System Overview

SecondBrain V2.5 — Autonomous IT MSP Intelligence

SecondBrain is an autonomous IT operations assistant built for Fieldstone, a dental IT MSP. It ingests emails, tracks tickets, detects patterns across clients, and surfaces intelligence to Scott (the operator) via a PM dashboard and Pilot (Discord bot).

Core Capabilities

📧

Email ingestion → ticket creation

IMAP, idempotent via Message-ID

📊

Signal scoring per ticket

readiness, trust, expectation, constraint, decision

🔍

Cross-client intelligence

outbreak detection, at-risk alerting

🧠

Node-based knowledge base

tool nodes, client nodes, living documentation

🤖

AI wrapper (sb_ai.py)

provider-agnostic, OAuth2 primary, API key fallback

🦾

Discord bot (Pilot)

14 commands for field operations

📋

PM Dashboard

tickets, signals, intel, setup, docs


2. Architecture

SecondBrain operates as a pipeline from raw email to actionable intelligence:

Email (IMAP)

Incoming client support emails

ingest_emails_imap.py

Deduplication via Message-ID

extract_and_store_entities()

cross_client_intel.py — writes to ticket_entities

run_intel_cycle()

Outbreak detection + at-risk flagging

second_brain.db (SQLite)

tickets · signals · tools · cross_client_events

api.py (FastAPI :8100)

REST + OAuth endpoints

fieldstoneFront (:3000)

/pm · /pm/intel · /pm/setup · /pm/docs

discord_bot.py (Pilot)

14 commands for field ops


3. Node-Based Knowledge Base

Nodes are entities — tools and clients — that store both static (manually written) and dynamic (auto-learned from tickets) knowledge. Every tool and client has a Markdown node file that grows richer over time as tickets are resolved.

Node Types

TypeExamplesLocation
Tool NodeEaglesoft, DEXIS, Carestream, Veeamkb/nodes/tools/*.md
Client NodeFieldstown Dental, Mountain Brookkb/nodes/clients/*.md
Global SOPsField Tech Guidelines, Triage Playbookskb/*.md

Node Structure — Two Layers

Static Layer

Manually written. Known issues, vendor contacts, SOPs, integration notes. Preserved through every auto-regeneration cycle.

Dynamic Layer

Auto-generated below the sentinel marker. Learned from resolved tickets and outbreak history. Updated by closed_ticket_ingest.py on each run.

Sentinel Marker

<!-- SENTINEL: AUTO-GENERATED BELOW — DO NOT EDIT -->

Anything ABOVE this line is preserved through every regeneration.
Anything BELOW is overwritten by closed_ticket_ingest.py on each run.

Knowledge Flow

Ticket resolved → resolution_notes saved
       ↓
closed_ticket_ingest.py
       ↓
Extract: tool mentioned + fix applied
       ↓
Append to tool node dynamic layer (below sentinel)
       ↓
Next same issue → AI finds it → grounded answer

4. Cross-Client Intelligence

The intelligence layer detects when the same tool causes issues across multiple clients simultaneously — enabling proactive response before additional clients are affected.

How It Works

1

Every ticket ingested → AI extracts tool mentions → ticket_entities table

2

Correlation engine checks: N clients + same tool + time window

3

If threshold hit → cross-client event created with classification

4

At-risk clients identified (use same tool, no open ticket yet)

5

Pilot alerted, dashboard updated

Event Classifications

ClassificationTriggerAction
active_outbreak2+ clients, same tool, 4hr windowImmediate Pilot alert
update_relatedMonday morning patternCheck vendor release notes
recurringSame tool, 3rd+ occurrence in 90 daysCreate permanent SOP
regional_outageMultiple clients, same ISPCheck ISP status
vendor_triggeredMatches vendor update dayContact vendor support

Tool Risk Score

Each tool gets a 0–100 risk score based on active ticket count across all clients using that tool.

>50 — HIGH25–50 — MEDIUM<25 — LOW

At-Risk Logic

Example: Outbreak detected for Eaglesoft → any client mapped to Eaglesoft in client_tools but with no open ticket is flagged as at-risk and surfaced in /api/intel/atrisk and the !atrisk Pilot command.


5. AI Wrapper (sb_ai.py)

sb_ai.py is a provider-agnostic AI layer that routes requests through a priority chain, handles response caching, and tracks token usage and costs.

Provider Priority Chain

PriorityProviderWhen Active
🥇 PRIMARYOAuth2 Bearer tokenAI_OAUTH_PROVIDER env var is set
🥈 SECONDARYDirect API key (OpenAI / Anthropic / Ollama)OAuth not configured
🥉 TERTIARYFallback URLAI_FALLBACK_URL is set

Available Functions

ask(prompt, task_type='fast')        # General purpose
summarize(text, max_words=30)        # Summarize email / ticket
classify(text, categories)           # Classify ticket type
draft_reply(title, notes, client)    # Draft client response
analyze_signal(signal_dict)          # AI signal commentary
query_kb(question, kb_text)          # KB-grounded Q&A

Model Routing

task_type='fast'

Routes to AI_FAST_MODEL
Used for classification, summarization, signal extraction

task_type='strong'

Routes to AI_STRONG_MODEL
Used for KB Q&A, draft replies, deep analysis

OAuth2 Providers

google (Vertex AI)azure (Azure OpenAI)openaicustom

Features

SQLite response caching with configurable TTL

Per-call token and cost tracking stored in ai_usage table

Daily budget guard with configurable spend cap

Automatic token refresh with 60s expiry buffer

Graceful fallback chain — never crashes on provider failure


6. Pilot Discord Commands

Pilot is the Discord bot interface for field operations. All 14 commands are available from any Discord channel the bot has access to.

CommandDescription
!ingestTrigger email ingestion manually
!brief <client>Generate and email prep brief for client
!signalsShow all client signal scores
!calendarShow upcoming appointments
!summaryDaily summary of open tickets
!ticket <id>Show full ticket details
!note <id> <text>Add note to ticket + append to resolution_notes
!digestSend daily digest email
!resetReset conversation context
!helpShow all commands
!tool <tool_id>Show tool node: risk score, clients, known issues
!outbreakShow all active cross-client outbreaks
!atriskList all at-risk clients
!clients <tool_id>List all clients using a tool

7. Signal Model

Every ticket has 5 signal dimensions scored automatically by AI during ingestion. Signals evolve as new emails arrive on the ticket thread.

SignalValuesMeaning
readiness_signal🟢 HIGH / 🟡 MEDIUM / 🔴 LOWClient's operational urgency
trust_signal📈 RISING / ➡️ NEUTRAL / 📉 DECLININGRelationship health trajectory
expectation_signalFree text (captured)Client's stated expectation
constraint_signalFree text (captured)Time / resource constraints
decision_signalFree text (captured)Pending decisions required

Numeric Scores

readiness_score

0 – 100

Numeric form of readiness_signal

trust_score

0 – 100

Numeric form of trust_signal

Composite

Weighted average

Shown in PM dashboard ticket cards


8. API Reference

All endpoints served by api.py on port 8100.

Tickets

MethodEndpointDescription
GET/api/ticketsAll tickets
GET/api/tickets/{key}Single ticket by key
GET/api/signalsAll signal scores

Intelligence

MethodEndpointDescription
GET/api/intel/outbreaksActive outbreaks {events:[], count:0}
GET/api/intel/atriskAt-risk clients {at_risk:[], count:0}
POST/api/intel/runTrigger intel cycle manually
GET/api/intel/tool/{id}/scoreTool risk score (0-100)

Nodes / Tools

MethodEndpointDescription
GET/api/nodes/toolsAll tools {tools:[...]}
GET/api/nodes/tools/{id}Tool detail + KB markdown

Settings

MethodEndpointDescription
GET/api/settingsAll settings (sensitive fields masked)
POST/api/settingsSave settings to .env
POST/api/settings/test/aiTest AI connection
POST/api/settings/test/emailTest email / IMAP connection
GET/api/settings/ai/usageAI token / cost stats

OAuth

MethodEndpointDescription
GET/api/oauth/initiate?provider=XStart OAuth flow → redirect to provider
GET/api/oauth/callbackOAuth callback handler
GET/api/oauth/status?provider=XPoll for OAuth completion

9. Setup Guide

Follow these steps in order to get SecondBrain fully operational:

1

Configure Email (IMAP)

Go to /pm/setup → Email / IMAP section. Enter IMAP host, port, username, and password.

2

Set AI Provider

AI Configuration section → Set API Base URL, API Key, fast model ID, and strong model ID.

3

Configure OAuth (Optional)

AI OAuth 2.0 section → Select provider (Google / Azure / OpenAI / custom) → click Connect.

4

Set Discord Token

Discord section → Paste bot token. Ensure Pilot has message + read permissions in your server.

5

Set GitHub Token

GitHub section → Personal access token for KB sync (if using a GitHub-hosted knowledge base).

6

Test Connections

Use the Test buttons for AI and Email to verify configuration before saving.

7

Save All Settings

Click Save All Settings. Changes are written to .env immediately.

8

Restart API

Apply config changes by restarting the API server:

pkill uvicorn && uvicorn api:app --host 0.0.0.0 --port 8100

10. Database Schema

SecondBrain uses a single SQLite file at second_brain/second_brain.db. Below are all key tables with column definitions.

tickets

Core ticket table

ColumnTypeNotes
idINTEGERPRIMARY KEY autoincrement
ticket_keyTEXTUnique key e.g. TK-2024-001
titleTEXTTicket subject
statusTEXTopen | in_progress | closed
priorityTEXThigh | medium | low
client_keyTEXTFK → client identifier
created_atTEXTISO timestamp
closed_atTEXTISO timestamp or NULL
resolution_notesTEXTFree text resolution
readiness_signalTEXTHIGH | MEDIUM | LOW
trust_signalTEXTRISING | NEUTRAL | DECLINING
readiness_scoreINTEGER0–100
trust_scoreINTEGER0–100
lifecycle_statusTEXTactive | archived
tools

Software tools in the MSP fleet

ColumnTypeNotes
idTEXTSlug e.g. eaglesoft
nameTEXTDisplay name
vendorTEXTVendor company
categoryTEXTpms | imaging | backup | network
vendor_support_urlTEXTSupport portal URL
known_issuesTEXTFreetext known issues
update_sensitivityTEXThigh | medium | low
client_tools

Maps which tools each client uses

ColumnTypeNotes
client_idTEXTFK → client
tool_idTEXTFK → tools.id
versionTEXTInstalled version
install_notesTEXTOptional notes
ticket_entities

AI/keyword extracted tool mentions per ticket

ColumnTypeNotes
ticket_keyTEXTFK → tickets.ticket_key
client_idTEXTExtracted client
tool_idTEXTExtracted tool
confidenceREAL0.0–1.0
extraction_methodTEXTkeyword | ai
created_atTEXTISO timestamp
cross_client_events

Detected outbreak and correlation events

ColumnTypeNotes
idINTEGERPRIMARY KEY
tool_idTEXTAffected tool
detected_atTEXTISO timestamp
affected_clientsTEXTJSON array of client IDs
at_risk_clientsTEXTJSON array of at-risk IDs
classificationTEXTactive_outbreak | update_related | recurring | ...
root_causeTEXTAI-generated root cause
statusTEXTopen | resolved
resolution_notesTEXTHow it was resolved
ai_usage

AI token and cost tracking per call

ColumnTypeNotes
idINTEGERPRIMARY KEY
modelTEXTModel identifier
tokens_usedINTEGERTotal tokens
cost_usdREALEstimated cost
created_atTEXTISO timestamp

SecondBrain V2.5 — Fieldstone Dental IT MSP Platform