Skip to content

Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.

feat(knowledge-cortex): add Gmail knowledge mining plugin

Jez900d920ecc18
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 85052783..2b1d9e1f 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -45,7 +45,7 @@
},
{
"name": "writing",
- "description": "Australian business English writing style for professional communications.",
+ "description": "Business English writing styles (AU, US, UK, NZ) and professional document skills (resumes, proposals, awards, strategy).",
"source": "./plugins/writing",
"category": "productivity"
},
@@ -60,6 +60,12 @@
"description": "Manage WordPress sites: content creation, blog posts, media, Elementor page editing, and WP-CLI workflows.",
"source": "./plugins/wordpress",
"category": "productivity"
+ },
+ {
+ "name": "knowledge-cortex",
+ "description": "Mine Gmail history into portable flat files. Extracts contacts, clients, communications, and knowledge facts using AI extraction.",
+ "source": "./plugins/knowledge-cortex",
+ "category": "productivity"
}
]
}
diff --git a/CLAUDE.md b/CLAUDE.md
index ea6f68ae..4991bbdb 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -16,7 +16,7 @@ Production workflow skills for Claude Code CLI. Each skill guides Claude through
```
claude-skills/
-├── plugins/ # 9 installable plugins
+├── plugins/ # 10 installable plugins
│ ├── cloudflare/ # Cloudflare Workers, Hono, D1/Drizzle, Vite, TanStack Start
│ │ └── skills/
│ │ ├── cloudflare-worker-builder/
@@ -62,6 +62,10 @@ claude-skills/
│ │ ├── shopify-setup/
│ │ ├── shopify-products/
│ │ └── shopify-content/
+│ ├── knowledge-cortex/ # Gmail knowledge mining
+│ │ └── skills/
+│ │ ├── cortex-mine/
+│ │ └── cortex-query/
│ ├── wordpress/ # WordPress content & Elementor
│ │ └── skills/
│ │ ├── wordpress-setup/
diff --git a/README.md b/README.md
index 60d48f49..a278749c 100644
--- a/README.md
+++ b/README.md
@@ -14,9 +14,10 @@ Workflow skills for [Claude Code](https://claude.com/claude-code) that produce t
| **design-assets** | color-palette, favicon-gen, icon-set-generator, image-processing | Colour palettes, favicons, SVG icons, image processing |
| **integrations** | google-chat-messages, google-apps-script, elevenlabs-agents, mcp-builder | Google Chat webhooks, Apps Script, ElevenLabs agents, MCP servers |
| **dev-tools** | project-health, dev-session, team-update, github-release, brains-trust, git-workflow, ux-audit, responsiveness-check, agent-browser | Project health audits, session tracking, team updates, releases, multi-model brains trust, git workflows, UX audits, responsive testing, browser automation |
+| **knowledge-cortex** | cortex-mine, cortex-query | Mine Gmail into portable flat files — contacts, clients, communications, knowledge facts |
| **shopify** | shopify-setup, shopify-products, shopify-content | Shopify API setup, product management, content pages, blog posts |
| **wordpress** | wordpress-setup, wordpress-content, wordpress-elementor | WordPress WP-CLI access, content management, Elementor page editing |
-| **writing** | aussie-business-english | Australian business English writing style |
+| **writing** | aussie-business-english, us-business-english, uk-business-english, nz-business-english, resume-cover-letter, proposal-writer, award-application, strategy-document | Regional business English (AU/US/UK/NZ) + professional documents (resumes, proposals, awards, strategy) |
## Install
@@ -31,6 +32,7 @@ Workflow skills for [Claude Code](https://claude.com/claude-code) that produce t
/plugin install web-design@jezweb-skills
/plugin install design-assets@jezweb-skills
/plugin install integrations@jezweb-skills
+/plugin install knowledge-cortex@jezweb-skills
/plugin install shopify@jezweb-skills
/plugin install wordpress@jezweb-skills
/plugin install writing@jezweb-skills
@@ -50,7 +52,7 @@ See [CLAUDE.md](CLAUDE.md) for development details.
This repo started as a collection of 105 skills — many were informational reference guides (CSS patterns, API docs, framework cheatsheets). With Claude's expanded training data and built-in capabilities, those reference skills became redundant.
-**v2** restructured into 9 installable plugins containing 33 skills that produce tangible output. Each one earns its place.
+**v2** restructured into 10 installable plugins containing 42 skills that produce tangible output. Each one earns its place.
The full v1 collection is preserved and usable:
diff --git a/plugins/knowledge-cortex/.claude-plugin/plugin.json b/plugins/knowledge-cortex/.claude-plugin/plugin.json
new file mode 100644
index 00000000..2d13e246
--- /dev/null
+++ b/plugins/knowledge-cortex/.claude-plugin/plugin.json
@@ -0,0 +1,8 @@
+{
+ "name": "knowledge-cortex",
+ "description": "Mine Gmail history into portable flat files (~/.cortex/). Extracts contacts, clients, communications, and knowledge facts using AI extraction.",
+ "author": {
+ "name": "Jeremy Dawes / Jezweb",
+ "email": "[email protected]"
+ }
+}
diff --git a/plugins/knowledge-cortex/skills/cortex-mine/SKILL.md b/plugins/knowledge-cortex/skills/cortex-mine/SKILL.md
new file mode 100644
index 00000000..0641606b
--- /dev/null
+++ b/plugins/knowledge-cortex/skills/cortex-mine/SKILL.md
@@ -0,0 +1,93 @@
+---
+name: cortex-mine
+description: >
+ Mine Gmail history into a local flat-file knowledge base (~/.cortex/).
+ Use when asked to "run the cortex", "mine emails", "cortex run", "cortex dry run",
+ "set up the cortex", "cortex from DATE", or "mine my inbox".
+ Extracts contacts, clients, communications and knowledge facts into portable JSONL/JSON files.
+ Requires gws CLI and ANTHROPIC_API_KEY.
+---
+
+# Knowledge Cortex — Mine
+
+Mine your Gmail history into structured flat files — contacts, clients, communications, and key facts — stored in `~/.cortex/`. No server required. Files you own.
+
+## When invoked
+
+Read `{skill_path}/references/file-schema.md` for the storage format before any file operations.
+
+## Commands
+
+| What user says | Action |
+|----------------|--------|
+| "run the cortex" / "cortex run" | Run mining pass |
+| "cortex dry run" | Mine without writing — pass `--dry-run` |
+| "cortex from DATE" | Mine from specific date — pass `--from YYYY-MM-DD` |
+| "set up the cortex" | Run first-time setup |
+
+## Setup (first run)
+
+Check prerequisites:
+```bash
+which gws || echo "MISSING: npm install -g @googleworkspace/cli"
+python3 -c "import anthropic" 2>/dev/null || echo "MISSING: pip install anthropic"
+ls ~/.cortex/state.json 2>/dev/null || echo "FIRST RUN"
+```
+
+If `gws` missing: tell user `npm install -g @googleworkspace/cli` then `gws auth setup`.
+If `anthropic` missing: tell user `pip install anthropic` (or `pip install anthropic --break-system-packages` on managed Python).
+If first run: initialise storage.
+
+```bash
+mkdir -p ~/.cortex/originals
+echo '{}' > ~/.cortex/contacts.json
+echo '{}' > ~/.cortex/clients.json
+touch ~/.cortex/communications.jsonl ~/.cortex/knowledge.jsonl ~/.cortex/files.jsonl
+```
+
+Write `~/.cortex/state.json`:
+```json
+{"version":"1.0","cursors":{"gmail":null},"last_run":null,"totals":{"contacts":0,"clients":0,"communications":0,"knowledge":0,"files":0},"runs":[]}
+```
+
+## Mining
+
+```bash
+python3 {skill_path}/scripts/cortex-mine.py
+python3 {skill_path}/scripts/cortex-mine.py --dry-run
+python3 {skill_path}/scripts/cortex-mine.py --from 2024-01-01
+python3 {skill_path}/scripts/cortex-mine.py --batch-size 25
+```
+
+The script prints a run report on completion. Show it to the user verbatim.
+
+**Common errors:**
+- `gws: command not found` — install gws CLI
+- `AuthError` / `403` — run `gws auth setup`
+- `ANTHROPIC_API_KEY not set` — set env var or add to `~/.cortex/.env`
+- `ModuleNotFoundError: anthropic` — `pip install anthropic`
+
+## Scheduling
+
+- Claude Code Desktop: Cowork > Scheduled > New Task > `Run the cortex-mine skill` > Daily
+- CLI: `/loop 24h run the cortex-mine skill`
+- Cron: `0 6 * * * cd ~ && ANTHROPIC_API_KEY=sk-... python3 /path/to/cortex-mine.py`
+
+## Exporting data
+
+See `{skill_path}/references/export-adapters.md` for patterns to export cortex data to Obsidian, SQLite, Notion, CRM systems, or custom APIs.
+
+## Environment
+
+| Variable | Default | Purpose |
+|----------|---------|---------|
+| `CORTEX_DIR` | `~/.cortex` | Storage root |
+| `ANTHROPIC_API_KEY` | — | Required for extraction |
+| `CORTEX_BATCH_SIZE` | `50` | Threads per run |
+| `CORTEX_OWNER_EMAIL` | — | Your email — excluded from contacts |
+
+## References
+
+- File schemas: `{skill_path}/references/file-schema.md`
+- Pre-filter rules: `{skill_path}/references/prefilter-patterns.md`
+- Export patterns: `{skill_path}/references/export-adapters.md`
diff --git a/plugins/knowledge-cortex/skills/cortex-mine/references/export-adapters.md b/plugins/knowledge-cortex/skills/cortex-mine/references/export-adapters.md
new file mode 100644
index 00000000..28a3218a
--- /dev/null
+++ b/plugins/knowledge-cortex/skills/cortex-mine/references/export-adapters.md
@@ -0,0 +1,81 @@
+# Export Adapters
+
+Cortex data lives in portable flat files. Export to any system using the patterns below.
+
+## Quick export
+
+```bash
+# CSV (for spreadsheets, CRM imports, Notion)
+python3 cortex-query.py export contacts --format csv > contacts.csv
+python3 cortex-query.py export clients --format csv > clients.csv
+python3 cortex-query.py export knowledge --format csv > knowledge.csv
+python3 cortex-query.py export communications --format csv > comms.csv
+
+# JSON (for APIs, scripts, databases)
+python3 cortex-query.py export contacts --format json > contacts-export.json
+```
+
+## Obsidian / Markdown vault
+
+Convert contacts to individual markdown files with YAML frontmatter:
+
+```bash
+# For each contact, create a .md file
+jq -r 'to_entries[] | .value | "---\nemail: \(.email)\ncompany: \(.company // "unknown")\nrole: \(.role // "unknown")\n---\n# \(.name // .email)\n\nLast seen: \(.last_seen)\nThreads: \(.thread_count)"' ~/.cortex/contacts.json
+```
+
+Knowledge facts map to daily notes or tagged entries. Communications map to a log file per client.
+
+## SQLite
+
+```bash
+# Create SQLite database from flat files
+sqlite3 cortex.db <<'SQL'
+CREATE TABLE contacts (name TEXT, email TEXT PRIMARY KEY, phone TEXT, role TEXT, company TEXT, company_domain TEXT, first_seen TEXT, last_seen TEXT, thread_count INTEGER);
+CREATE TABLE clients (name TEXT, domain TEXT PRIMARY KEY, industry TEXT, abn TEXT, first_seen TEXT, last_seen TEXT, thread_count INTEGER);
+CREATE TABLE communications (id TEXT PRIMARY KEY, source TEXT, source_id TEXT UNIQUE, subject TEXT, summary TEXT, communication_type TEXT, significance INTEGER, client_domain TEXT, thread_date TEXT);
+CREATE TABLE knowledge (id TEXT PRIMARY KEY, fact TEXT, kind TEXT, client_domain TEXT, contact_email TEXT, thread_date TEXT);
+.mode csv
+.import contacts.csv contacts
+.import knowledge.csv knowledge
+SQL
+```
+
+## Notion
+
+1. Export CSV: `cortex-query.py export contacts --format csv`
+2. Notion > Import > CSV > map columns to properties
+3. Repeat for clients, knowledge, communications
+
+## CRM systems (HubSpot, Pipedrive, etc.)
+
+Export CSV and use the CRM's bulk import. Field mapping:
+- `name` -> Contact Name
+- `email` -> Email
+- `phone` -> Phone
+- `company` -> Company/Organisation
+- `company_domain` -> Website
+
+## Custom API / MCP server
+
+Read files directly from `~/.cortex/` in your scripts:
+
+```python
+import json
+from pathlib import Path
+
+cortex = Path.home() / ".cortex"
+
+# Contacts: dict keyed by email
+contacts = json.loads((cortex / "contacts.json").read_text())
+jane = contacts.get("[email protected]")
+
+# Knowledge: list of facts (JSONL)
+facts = []
+for line in (cortex / "knowledge.jsonl").open():
+ if line.strip():
+ facts.append(json.loads(line))
+
+# Filter by client
+client_facts = [f for f in facts if f.get("client_domain") == "company.com"]
+```
diff --git a/plugins/knowledge-cortex/skills/cortex-mine/references/file-schema.md b/plugins/knowledge-cortex/skills/cortex-mine/references/file-schema.md
new file mode 100644
index 00000000..797b1066
--- /dev/null
+++ b/plugins/knowledge-cortex/skills/cortex-mine/references/file-schema.md
@@ -0,0 +1,108 @@
+# File Schema Reference
+
+Storage root: `~/.cortex/` (or `$CORTEX_DIR`)
+
+---
+
+## contacts.json — keyed by email (lowercase)
+
+```json
+{
+ "name": "Jane Smith",
+ "email": "[email protected]",
+ "phone": null,
+ "role": "Director",
+ "company": "Smith Holdings Pty Ltd",
+ "company_domain": "smithholdings.com.au",
+ "first_seen": "2024-03-15T09:00:00+11:00",
+ "last_seen": "2026-03-10T14:22:00+11:00",
+ "thread_count": 7,
+ "source": "gmail"
+ }
+}
+```
+
+**Upsert rules:** update non-null fields; keep earlier `first_seen`; keep later `last_seen`; increment `thread_count`.
+
+---
+
+## clients.json — keyed by domain (or slugified name if no domain)
+
+```json
+{
+ "smithholdings.com.au": {
+ "name": "Smith Holdings Pty Ltd",
+ "domain": "smithholdings.com.au",
+ "industry": null,
+ "abn": null,
+ "first_seen": "2024-03-15T09:00:00+11:00",
+ "last_seen": "2026-03-10T14:22:00+11:00",
+ "thread_count": 12,
+ "contact_emails": ["[email protected]"],
+ "source": "gmail"
+ }
+}
+```
+
+---
+
+## communications.jsonl — append-only, one JSON per line
+
+```json
+{"id":"comm_1741824000_a3f2","source":"gmail","source_id":"18e2a3b4c5d6e7f8","source_url":"https://mail.google.com/mail/u/0/#all/18e2a3b4c5d6e7f8","channel":"email","subject":"Website redesign quote","participants":["[email protected]","[email protected]"],"summary":"Client enquired about a full website redesign. Agreed to send a quote by end of week.","communication_type":"quote","significance":4,"client_domain":"clientco.com.au","project":null,"thread_date":"2026-03-10T11:30:00+11:00","processed_at":"2026-03-13T06:15:00+11:00"}
+```
+
+`source_id` = Gmail thread ID. **Idempotency key** — always check before processing.
+
+**significance:** 1=junk, 2=routine FYI, 3=normal business, 4=important, 5=critical
+
+---
+
+## knowledge.jsonl — append-only, one JSON per line
+
+```json
+{"id":"know_1741824000_b7c1","fact":"Client prefers phone contact over email","kind":"preference","client_domain":"clientco.com.au","contact_email":"[email protected]","project":null,"source":"gmail","source_id":"18e2a3b4c5d6e7f8","source_url":"https://mail.google.com/mail/u/0/#all/18e2a3b4c5d6e7f8","thread_date":"2026-03-10T11:30:00+11:00","created_at":"2026-03-13T06:15:00+11:00"}
+```
+
+**kind values:** `decision` | `commitment` | `deadline` | `amount` | `preference` | `feedback` | `relationship` | `other`
+
+---
+
+## files.jsonl — append-only, one JSON per line (Phase 2)
+
+```json
+{"id":"file_1741824000_c9d4","filename":"quote-march.pdf","mime_type":"application/pdf","file_type":"pdf","source":"gmail_attachment","source_thread_id":"18e2a3b4c5d6e7f8","client_domain":"clientco.com.au","extracted_text":"Full text...","description":"A website redesign quote totalling $4,200...","extraction_method":"pdftotext","description_method":"claude-api","thread_date":"2026-03-10T11:30:00+11:00","processed_at":"2026-03-13T06:15:00+11:00"}
+```
+
+---
+
+## state.json — cursor and run history
+
+```json
+{
+ "version": "1.0",
+ "cursors": {"gmail": 1741824000, "google_chat": null, "calendar": null},
+ "last_run": "2026-03-13T06:00:00+11:00",
+ "totals": {"contacts": 142, "clients": 67, "communications": 503, "knowledge": 289, "files": 0},
+ "runs": [
+ {
+ "date": "2026-03-13T06:00:00+11:00",
+ "source": "gmail",
+ "fetched": 50,
+ "filtered": 33,
+ "ai_processed": 17,
+ "contacts_added": 2,
+ "contacts_updated": 1,
+ "clients_added": 1,
+ "clients_updated": 2,
+ "comms_logged": 15,
+ "facts_stored": 8,
+ "errors": 0,
+ "duration_seconds": 47
+ }
+ ]
+}
+```
+
+Keep last 30 runs. Trim oldest on write.
diff --git a/plugins/knowledge-cortex/skills/cortex-mine/references/prefilter-patterns.md b/plugins/knowledge-cortex/skills/cortex-mine/references/prefilter-patterns.md
new file mode 100644
index 00000000..6041604a
--- /dev/null
+++ b/plugins/knowledge-cortex/skills/cortex-mine/references/prefilter-patterns.md
@@ -0,0 +1,72 @@
+# Pre-filter Patterns
+
+Applied before any AI call. Goal: skip 60–80% of threads at near-zero cost.
+
+## Step 1 — Duplicate check (always first)
+
+```python
+# Already in communications.jsonl?
+with open(comms_file) as f:
+ if f'"source_id":"{thread_id}"' in f.read():
+ skip # already processed
+```
+
+## Step 2 — Automated sender patterns
+
+Skip if `from` address matches (case-insensitive):
+
+```
+no-reply@, noreply@, do-not-reply@, donotreply@
+notifications@, notification@, alerts@, alert@
+mailer-daemon@, postmaster@, bounce@
+auto-confirm@, automated@, robot@, bot@
+newsletter@, newsletters@, marketing@, offers@, promotions@
+billing@, invoices@, receipts@, system@
+```
+
+Skip if sender domain is a known automated source:
+```
+xero.com, myob.com, quickbooks.com
+stripe.com, paypal.com, square.com
+mailchimp.com, hubspot.com, klaviyo.com, brevo.com, sendinblue.com
+constantcontact.com, campaignmonitor.com
+intercom.io, zendesk.com, freshdesk.com
+shopify.com, squarespace.com, wix.com
+```
+
+## Step 3 — Subject patterns
+
+Skip if subject contains (case-insensitive):
+```
+unsubscribe, newsletter
+your invoice, invoice #, invoice number
+receipt for, your order, order confirmation, order #
+delivery notification, shipping notification, your package
+password reset, reset your password
+verify your email, verification code, confirm your email
+account activation, account created
+trial started, subscription renewed
+payment received, payment failed, payment reminder
+automatic reply, auto-reply, auto reply, out of office
+do not reply, do not respond
+security alert, new sign-in, new device detected
+weekly digest, monthly summary, weekly summary
+```
+
+## Step 4 — Gmail query (apply at fetch time — free filtering)
+
+```
+after:YYYY/MM/DD
+-category:promotions
+-category:updates
+-category:social
+-label:newsletters
+-from:no-reply
+-from:noreply
+```
+
+## Tuning
+
+- Too many false negatives (junk getting through)? Add sender domains to the blocked list.
+- Useful threads being filtered? Check which pattern matched and remove or narrow it.
+- The filter errs aggressive — better to skip a borderline thread than waste an API call.
diff --git a/plugins/knowledge-cortex/skills/cortex-mine/scripts/cortex-mine.py b/plugins/knowledge-cortex/skills/cortex-mine/scripts/cortex-mine.py
new file mode 100644
index 00000000..19f5be4f
--- /dev/null
+++ b/plugins/knowledge-cortex/skills/cortex-mine/scripts/cortex-mine.py
@@ -0,0 +1,777 @@
+#!/usr/bin/env python3
+"""
+cortex-mine.py — Knowledge Cortex Gmail miner
+
+Fetches Gmail threads, filters junk, extracts structured knowledge
+via Claude API, writes to ~/.cortex/ flat files.
+
+Usage:
+ python3 cortex-mine.py
+ python3 cortex-mine.py --from 2024-01-01
+ python3 cortex-mine.py --dry-run
+ python3 cortex-mine.py --batch-size 25
+
+Requirements:
+ pip install anthropic
+ npm install -g @googleworkspace/cli
+ gws auth setup
+ ANTHROPIC_API_KEY env var
+"""
+
+import argparse
+import base64
+import json
+import os
+import random
+import re
+import string
+import subprocess
+import sys
+import time
+from datetime import datetime, timezone, timedelta
+from pathlib import Path
+
+# ─── Config ──────────────────────────────────────────────────────────────────
+
+CORTEX_DIR = Path(os.environ.get("CORTEX_DIR", Path.home() / ".cortex"))
+BATCH_SIZE = int(os.environ.get("CORTEX_BATCH_SIZE", "50"))
+OWNER_EMAIL = os.environ.get("CORTEX_OWNER_EMAIL", "").lower()
+MODEL = "claude-sonnet-4-6"
+
+FILES = {
+ "contacts": CORTEX_DIR / "contacts.json",
+ "clients": CORTEX_DIR / "clients.json",
+ "communications": CORTEX_DIR / "communications.jsonl",
+ "knowledge": CORTEX_DIR / "knowledge.jsonl",
+ "files": CORTEX_DIR / "files.jsonl",
+ "state": CORTEX_DIR / "state.json",
+}
+
+# ─── Automated sender patterns ────────────────────────────────────────────────
+
+JUNK_FROM_PREFIXES = [
+ "no-reply@", "noreply@", "do-not-reply@", "donotreply@",
+ "notifications@", "notification@", "alerts@", "alert@",
+ "mailer-daemon@", "postmaster@", "bounce@", "auto-confirm@",
+ "automated@", "robot@", "newsletter@", "newsletters@",
+ "marketing@", "billing@", "invoices@", "receipts@", "system@",
+]
+
+JUNK_DOMAINS = {
+ "xero.com", "myob.com", "quickbooks.com", "stripe.com", "paypal.com",
+ "square.com", "mailchimp.com", "hubspot.com", "klaviyo.com", "brevo.com",
+ "sendinblue.com", "constantcontact.com", "campaignmonitor.com",
+ "intercom.io", "zendesk.com", "freshdesk.com", "shopify.com",
+ "squarespace.com", "wix.com", "salesforce.com",
+}
+
+JUNK_SUBJECT_PATTERNS = [
+ r"unsubscribe", r"newsletter", r"your invoice", r"invoice #",
+ r"receipt for", r"your order", r"order confirmation",
+ r"delivery notification", r"shipping notification",
+ r"password reset", r"reset your password",
+ r"verify your email", r"verification code", r"confirm your email",
+ r"account activation", r"trial started", r"subscription renewed",
+ r"payment received", r"payment failed", r"payment reminder",
+ r"automatic reply", r"auto.?reply", r"out of office",
+ r"do not reply", r"security alert", r"new sign.?in",
+ r"weekly digest", r"monthly summary",
+]
+JUNK_SUBJECT_RE = re.compile("|".join(JUNK_SUBJECT_PATTERNS), re.IGNORECASE)
+
+# ─── Helpers ─────────────────────────────────────────────────────────────────
+
+def rand_id(prefix: str) -> str:
+ suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=4))
+ return f"{prefix}_{int(time.time())}_{suffix}"
+
+
+def now_iso() -> str:
+ return datetime.now(timezone.utc).astimezone().isoformat()
+
+
+def read_json(path: Path, fallback=None):
+ if fallback is None:
+ fallback = {}
+ if not path.exists():
+ return fallback
+ try:
+ return json.loads(path.read_text())
+ except Exception:
+ return fallback
+
+
+def write_json(path: Path, data):
+ path.write_text(json.dumps(data, indent=2, ensure_ascii=False))
+
+
+def append_jsonl(path: Path, record: dict):
+ with open(path, "a", encoding="utf-8") as f:
+ f.write(json.dumps(record, ensure_ascii=False) + "\n")
+
+
+def load_processed_ids() -> set:
+ """Load all processed thread IDs from communications.jsonl into a set (O(n) once)."""
+ comms = FILES["communications"]
+ ids = set()
+ if not comms.exists():
+ return ids
+ try:
+ for line in comms.open(encoding="utf-8"):
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ record = json.loads(line)
+ sid = record.get("source_id")
+ if sid:
+ ids.add(sid)
+ except Exception:
+ pass
+ except Exception:
+ pass
+ return ids
+
+
+def run_gws(params: dict, resource: str, method: str) -> dict | None:
+ """Run a gws CLI command and return parsed JSON output."""
+ cmd = ["gws", "gmail", resource, method, "--params", json.dumps(params)]
+ try:
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
+ if result.returncode != 0:
+ print(f" gws error: {result.stderr.strip()}", file=sys.stderr)
+ return None
+ return json.loads(result.stdout)
+ except subprocess.TimeoutExpired:
+ print(f" gws timeout on {resource}/{method}", file=sys.stderr)
+ return None
+ except json.JSONDecodeError as e:
+ print(f" gws JSON parse error: {e}", file=sys.stderr)
+ return None
+ except FileNotFoundError:
+ print("ERROR: gws not found. Install: npm install -g @googleworkspace/cli", file=sys.stderr)
+ sys.exit(1)
+
+
+def decode_body(data: str) -> str:
+ """Decode base64url email body."""
+ try:
+ padded = data.replace("-", "+").replace("_", "/")
+ padded += "=" * (4 - len(padded) % 4)
+ return base64.b64decode(padded).decode("utf-8", errors="replace")
+ except Exception:
+ return ""
+
+
+def extract_text_from_message(message: dict) -> str:
+ """Extract plain text from a Gmail message payload."""
+ payload = message.get("payload", {})
+ parts = payload.get("parts", [])
+ body_data = payload.get("body", {}).get("data", "")
+
+ texts = []
+
+ def walk_parts(parts_list):
+ for part in parts_list:
+ mime = part.get("mimeType", "")
+ if mime == "text/plain":
+ data = part.get("body", {}).get("data", "")
+ if data:
+ texts.append(decode_body(data))
+ elif mime.startswith("multipart/"):
+ walk_parts(part.get("parts", []))
+
+ if parts:
+ walk_parts(parts)
+ elif body_data:
+ texts.append(decode_body(body_data))
+
+ text = "\n".join(texts).strip()
+ # Trim to 3000 chars to avoid massive context
+ return text[:3000] if len(text) > 3000 else text
+
+
+def get_header(headers: list, name: str) -> str:
+ for h in headers:
+ if h.get("name", "").lower() == name.lower():
+ return h.get("value", "")
+ return ""
+
+
+def build_thread_summary(thread_data: dict) -> dict:
+ """Extract usable fields from a raw Gmail thread."""
+ messages = thread_data.get("messages", [])
+ if not messages:
+ return {}
+
+ first = messages[0]
+ headers = first.get("payload", {}).get("headers", [])
+
+ subject = get_header(headers, "Subject")
+ from_addr = get_header(headers, "From")
+ date_str = get_header(headers, "Date")
+
+ # Collect all participants
+ all_emails = set()
+ for msg in messages:
+ h = msg.get("payload", {}).get("headers", [])
+ for field in ["From", "To", "Cc"]:
+ val = get_header(h, field)
+ # Extract emails from "Name <email>" format
+ emails = re.findall(r"[\w.+-]+@[\w.-]+\.\w+", val)
+ all_emails.update(e.lower() for e in emails)
+ all_emails.discard(OWNER_EMAIL)
+
+ # Combine text from all messages
+ all_text = []
+ for msg in messages[:5]: # cap at 5 messages to control size
+ text = extract_text_from_message(msg)
+ if text:
+ all_text.append(text)
+ body = "\n\n---\n\n".join(all_text)
+
+ return {
+ "thread_id": thread_data.get("id", ""),
+ "subject": subject,
+ "from": from_addr,
+ "participants": sorted(all_emails),
+ "date": date_str,
+ "body": body,
+ "message_count": len(messages),
+ }
+
+
+# ─── Pre-filter ───────────────────────────────────────────────────────────────
+
+def should_skip(thread_summary: dict) -> tuple[bool, str]:
+ """Returns (skip, reason). Fast, no AI."""
+ from_addr = thread_summary.get("from", "").lower()
+ subject = thread_summary.get("subject", "")
+
+ # Extract email from "Name <email>" format
+ email_match = re.search(r"[\w.+-]+@[\w.-]+\.\w+", from_addr)
+ email = email_match.group(0).lower() if email_match else from_addr
+ domain = email.split("@")[-1] if "@" in email else ""
+
+ for prefix in JUNK_FROM_PREFIXES:
+ if email.startswith(prefix):
+ return True, f"junk sender prefix: {prefix}"
+
+ if domain in JUNK_DOMAINS:
+ return True, f"junk domain: {domain}"
+
+ if JUNK_SUBJECT_RE.search(subject):
+ return True, f"junk subject pattern"
+
+ # Single-message thread from automated-looking sender
+ if thread_summary.get("message_count", 1) == 1:
+ if not thread_summary.get("participants"):
+ return True, "single message, no other participants"
+
+ return False, ""
+
+
+# ─── Claude extraction ────────────────────────────────────────────────────────
+
+EXTRACTION_PROMPT = """You are extracting structured data from an email thread to build a personal business knowledge base.
+
+EMAIL THREAD:
+Subject: {subject}
+From: {from_addr}
+Participants: {participants}
+Date: {date}
+Messages ({message_count} total):
+
+{body}
+
+Extract the following. Respond with ONLY valid JSON, no preamble, no markdown fences:
+
+{{
+ "contacts": [
+ {{"name": "Full Name", "email": "[email protected]", "phone": null, "role": null, "company": null}}
+ ],
+ "client": {{"name": null, "domain": null, "industry": null}},
+ "project": null,
+ "significance": 2,
+ "communication_type": "general",
+ "summary": "1-2 sentence summary of what this thread was about and what happened",
+ "key_facts": [
+ {{"fact": "Specific useful fact, decision, or commitment", "kind": "preference"}}
+ ]
+}}
+
+Significance: 1=junk/automated, 2=routine FYI, 3=normal business, 4=important (commitment/quote/agreement), 5=critical (contract/dispute/major decision)
+communication_type: inquiry | quote | support | meeting | general | complaint | contract | introduction
+fact kind: decision | commitment | deadline | amount | preference | feedback | relationship | other
+
+Rules:
+- Only include real human contacts (no bots, no automated senders)
+- Do NOT include {owner_email} as a contact
+- Only include key_facts worth recalling in 6 months
+- If clearly junk, return significance: 1 and empty arrays
+- client.domain should be the company's primary web domain if evident"""
+
+
+def extract_from_thread(client, thread_summary: dict, owner_email: str) -> dict | None:
+ """Call Claude API to extract structured data from thread."""
+ prompt = EXTRACTION_PROMPT.format(
+ subject=thread_summary.get("subject", ""),
+ from_addr=thread_summary.get("from", ""),
+ participants=", ".join(thread_summary.get("participants", [])),
+ date=thread_summary.get("date", ""),
+ message_count=thread_summary.get("message_count", 1),
+ body=thread_summary.get("body", "")[:2500],
+ owner_email=owner_email or "your own email",
+ )
+
+ try:
+ response = client.messages.create(
+ model=MODEL,
+ max_tokens=1024,
+ messages=[{"role": "user", "content": prompt}],
+ )
+ text = response.content[0].text.strip()
+
+ # Strip any accidental markdown fences
+ text = re.sub(r"^```json\s*", "", text)
+ text = re.sub(r"\s*```$", "", text)
+
+ return json.loads(text)
+
+ except json.JSONDecodeError:
+ # Retry once with explicit instruction
+ try:
+ retry_response = client.messages.create(
+ model=MODEL,
+ max_tokens=1024,
+ messages=[
+ {"role": "user", "content": prompt},
+ {"role": "assistant", "content": text},
+ {"role": "user", "content": "That response contained invalid JSON. Return ONLY the JSON object, nothing else."},
+ ],
+ )
+ return json.loads(retry_response.content[0].text.strip())
+ except Exception:
+ return None
+ except Exception as e:
+ print(f" Claude API error: {e}", file=sys.stderr)
+ return None
+
+
+# ─── Write helpers ────────────────────────────────────────────────────────────
+
+def upsert_contact(contacts: dict, contact: dict, client_domain: str | None, thread_date: str):
+ email = contact.get("email", "").lower().strip()
+ if not email or "@" not in email:
+ return
+ if OWNER_EMAIL and email == OWNER_EMAIL:
+ return
+
+ existing = contacts.get(email, {})
+ now = now_iso()
+
+ updated = {
+ "name": contact.get("name") or existing.get("name"),
+ "email": email,
+ "phone": contact.get("phone") or existing.get("phone"),
+ "role": contact.get("role") or existing.get("role"),
+ "company": contact.get("company") or existing.get("company"),
+ "company_domain": client_domain or existing.get("company_domain"),
+ "first_seen": existing.get("first_seen") or thread_date or now,
+ "last_seen": thread_date or now,
+ "thread_count": existing.get("thread_count", 0) + 1,
+ "source": "gmail",
+ }
+
+ # Keep earlier first_seen
+ if existing.get("first_seen") and thread_date:
+ updated["first_seen"] = min(existing["first_seen"], thread_date)
+
+ contacts[email] = updated
+ return email
+
+
+def upsert_client(clients: dict, client_data: dict, contact_email: str | None, thread_date: str) -> str | None:
+ name = (client_data.get("name") or "").strip()
+ domain = (client_data.get("domain") or "").lower().strip()
+
+ if not name and not domain:
+ return None
+
+ # Determine key
+ key = domain if domain else re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
+
+ existing = clients.get(key, {})
+ now = now_iso()
+
+ contact_emails = set(existing.get("contact_emails") or [])
+ if contact_email:
+ contact_emails.add(contact_email)
+
+ updated = {
+ "name": name or existing.get("name", key),
+ "domain": domain or existing.get("domain"),
+ "industry": client_data.get("industry") or existing.get("industry"),
+ "abn": existing.get("abn"),
+ "first_seen": existing.get("first_seen") or thread_date or now,
+ "last_seen": thread_date or now,
+ "thread_count": existing.get("thread_count", 0) + 1,
+ "contact_emails": sorted(contact_emails),
+ "source": "gmail",
+ }
+
+ if existing.get("first_seen") and thread_date:
+ updated["first_seen"] = min(existing["first_seen"], thread_date)
+
+ clients[key] = updated
+ return key
+
+
+# ─── Main mining loop ─────────────────────────────────────────────────────────
+
+def run_mining(dry_run: bool, from_date: str | None, batch_size: int):
+ start_time = time.time()
+ print(f"\nKnowledge Cortex — {'DRY RUN ' if dry_run else ''}Mining Pass")
+ print(f"Storage: {CORTEX_DIR}")
+ print("─" * 50)
+
+ # Check anthropic
+ try:
+ import anthropic
+ except ImportError:
+ print("ERROR: anthropic not installed. Run: pip install anthropic --break-system-packages")
+ sys.exit(1)
+
+ api_key = os.environ.get("ANTHROPIC_API_KEY")
+ if not api_key:
+ print("ERROR: ANTHROPIC_API_KEY not set")
+ sys.exit(1)
+
+ anthropic_client = anthropic.Anthropic(api_key=api_key)
+
+ # Load state
+ state = read_json(FILES["state"], {
+ "version": "1.0",
+ "cursors": {"gmail": None},
+ "last_run": None,
+ "totals": {"contacts": 0, "clients": 0, "communications": 0, "knowledge": 0},
+ "runs": [],
+ })
+
+ # Determine cursor date
+ if from_date:
+ cursor_str = from_date.replace("-", "/")
+ elif state.get("cursors", {}).get("gmail"):
+ ts = state["cursors"]["gmail"]
+ cursor_dt = datetime.fromtimestamp(ts, tz=timezone.utc)
+ cursor_str = cursor_dt.strftime("%Y/%m/%d")
+ else:
+ default_dt = datetime.now(timezone.utc) - timedelta(days=90)
+ cursor_str = default_dt.strftime("%Y/%m/%d")
+
+ print(f"Fetching threads after: {cursor_str}")
+
+ # Build Gmail query
+ gmail_query = (
+ f"after:{cursor_str} "
+ "-category:promotions -category:updates -category:social "
+ "-from:no-reply -from:noreply"
+ )
+
+ # Fetch thread list
+ list_result = run_gws(
+ {"userId": "me", "q": gmail_query, "maxResults": batch_size},
+ "threads", "list"
+ )
+
+ if not list_result:
+ print("Failed to fetch thread list from Gmail")
+ sys.exit(1)
+
+ threads = list_result.get("threads", [])
+ print(f"Threads fetched: {len(threads)}")
+
+ if not threads:
+ print("No new threads found. Cortex is up to date.")
+ return
+
+ # Load mutable stores
+ contacts = read_json(FILES["contacts"], {})
+ clients = read_json(FILES["clients"], {})
+
+ # Load processed thread IDs for fast dedup (O(n) once, not per-thread)
+ processed_ids = load_processed_ids()
+
+ # Stats
+ stats = {
+ "fetched": len(threads),
+ "skipped_duplicate": 0,
+ "skipped_prefilter": 0,
+ "ai_processed": 0,
+ "sig_1": 0,
+ "contacts_added": 0,
+ "contacts_updated": 0,
+ "clients_added": 0,
+ "clients_updated": 0,
+ "comms_logged": 0,
+ "facts_stored": 0,
+ "errors": 0,
+ }
+
+ latest_ts = state.get("cursors", {}).get("gmail") or 0
+ dry_run_rows = []
+
+ for i, thread_ref in enumerate(threads):
+ thread_id = thread_ref.get("id", "")
+
+ # Duplicate check (O(1) set lookup)
+ if thread_id in processed_ids:
+ stats["skipped_duplicate"] += 1
+ continue
+
+ # Fetch full thread
+ thread_data = run_gws({"userId": "me", "id": thread_id}, "threads", "get")
+ if not thread_data:
+ stats["errors"] += 1
+ continue
+
+ summary = build_thread_summary(thread_data)
+ if not summary:
+ stats["errors"] += 1
+ continue
+
+ # Pre-filter
+ skip, reason = should_skip(summary)
+ if skip:
+ stats["skipped_prefilter"] += 1
+ if dry_run:
+ dry_run_rows.append({
+ "id": thread_id,
+ "from": summary.get("from", "")[:40],
+ "subject": summary.get("subject", "")[:50],
+ "sig": "—",
+ "action": f"skip ({reason})",
+ })
+ continue
+
+ # Extract with Claude
+ print(f" [{i+1}/{len(threads)}] Extracting: {summary.get('subject', '')[:60]}")
+ extracted = extract_from_thread(anthropic_client, summary, OWNER_EMAIL)
+
+ if not extracted:
+ stats["errors"] += 1
+ continue
+
+ stats["ai_processed"] += 1
+ significance = extracted.get("significance", 2)
+
+ if dry_run:
+ n_facts = len(extracted.get("key_facts") or [])
+ n_contacts = len(extracted.get("contacts") or [])
+ actions = []
+ if significance >= 3:
+ if n_contacts:
+ actions.append(f"+{n_contacts} contacts")
+ if extracted.get("client", {}).get("name"):
+ actions.append("+client")
+ actions.append("log comms")
+ if n_facts:
+ actions.append(f"+{n_facts} facts")
+ elif significance == 2:
+ actions.append("log only")
+ else:
+ actions.append("skip (sig 1)")
+ dry_run_rows.append({
+ "id": thread_id,
+ "from": summary.get("from", "")[:40],
+ "subject": summary.get("subject", "")[:50],
+ "sig": significance,
+ "action": ", ".join(actions),
+ })
+ continue
+
+ # Track latest timestamp for cursor
+ messages = thread_data.get("messages", [])
+ if messages:
+ msg_ts = int(messages[-1].get("internalDate", "0")) // 1000
+ latest_ts = max(latest_ts, msg_ts)
+
+ # Parse thread date
+ thread_date = summary.get("date", now_iso())
+
+ # Source URL
+ source_url = f"https://mail.google.com/mail/u/0/#all/{thread_id}"
+
+ # ── significance 1: skip ──
+ if significance <= 1:
+ stats["sig_1"] += 1
+ continue
+
+ # ── significance 2: log comms only ──
+ comm_record = {
+ "id": rand_id("comm"),
+ "source": "gmail",
+ "source_id": thread_id,
+ "source_url": source_url,
+ "channel": "email",
+ "subject": summary.get("subject", ""),
+ "participants": summary.get("participants", []),
+ "summary": extracted.get("summary", ""),
+ "communication_type": extracted.get("communication_type", "general"),
+ "significance": significance,
+ "client_domain": None,
+ "project": extracted.get("project"),
+ "thread_date": thread_date,
+ "processed_at": now_iso(),
+ }
+
+ if significance >= 3:
+ # Upsert contacts
+ client_data = extracted.get("client") or {}
+ client_domain = client_data.get("domain") or None
+
+ contact_email = None
+ for contact in (extracted.get("contacts") or []):
+ prev_exists = contact.get("email", "").lower() in contacts
+ email = upsert_contact(contacts, contact, client_domain, thread_date)
+ if email:
+ contact_email = contact_email or email
+ if prev_exists:
+ stats["contacts_updated"] += 1
+ else:
+ stats["contacts_added"] += 1
+
+ # Upsert client
+ if client_data.get("name") or client_data.get("domain"):
+ prev_exists = bool(
+ client_data.get("domain") and client_data["domain"] in clients
+ )
+ domain_key = upsert_client(clients, client_data, contact_email, thread_date)
+ if domain_key:
+ client_domain = client_domain or domain_key
+ if prev_exists:
+ stats["clients_updated"] += 1
+ else:
+ stats["clients_added"] += 1
+
+ comm_record["client_domain"] = client_domain
+
+ # Store knowledge facts
+ for fact_item in (extracted.get("key_facts") or []):
+ fact_text = fact_item.get("fact", "").strip()
+ if not fact_text:
+ continue
+ know_record = {
+ "id": rand_id("know"),
+ "fact": fact_text,
+ "kind": fact_item.get("kind", "other"),
+ "client_domain": client_domain,
+ "contact_email": contact_email,
+ "project": extracted.get("project"),
+ "source": "gmail",
+ "source_id": thread_id,
+ "source_url": source_url,
+ "thread_date": thread_date,
+ "created_at": now_iso(),
+ }
+ append_jsonl(FILES["knowledge"], know_record)
+ stats["facts_stored"] += 1
+
+ append_jsonl(FILES["communications"], comm_record)
+ processed_ids.add(thread_id) # Prevent within-batch duplicates
+ stats["comms_logged"] += 1
+
+ # Small delay to be kind to the API
+ time.sleep(0.3)
+
+ # ── Write updated stores ───────────────────────────────────────────────────
+
+ if not dry_run:
+ write_json(FILES["contacts"], contacts)
+ write_json(FILES["clients"], clients)
+
+ # Update state
+ if latest_ts:
+ state.setdefault("cursors", {})["gmail"] = latest_ts
+
+ state["last_run"] = now_iso()
+ state.setdefault("totals", {})
+ state["totals"]["contacts"] = len(contacts)
+ state["totals"]["clients"] = len(clients)
+
+ # Count JSONL lines
+ for key in ("communications", "knowledge"):
+ path = FILES[key]
+ count = sum(1 for line in path.open() if line.strip()) if path.exists() else 0
+ state["totals"][key] = count
+
+ run_record = {
+ "date": now_iso(),
+ "source": "gmail",
+ "fetched": stats["fetched"],
+ "skipped_duplicate": stats["skipped_duplicate"],
+ "skipped_prefilter": stats["skipped_prefilter"],
+ "ai_processed": stats["ai_processed"],
+ "contacts_added": stats["contacts_added"],
+ "contacts_updated": stats["contacts_updated"],
+ "clients_added": stats["clients_added"],
+ "clients_updated": stats["clients_updated"],
+ "comms_logged": stats["comms_logged"],
+ "facts_stored": stats["facts_stored"],
+ "errors": stats["errors"],
+ "duration_seconds": round(time.time() - start_time),
+ }
+
+ runs = state.get("runs", [])
+ runs.append(run_record)
+ state["runs"] = runs[-30:] # keep last 30
+ write_json(FILES["state"], state)
+
+ # ── Report ─────────────────────────────────────────────────────────────────
+
+ duration = round(time.time() - start_time)
+ print(f"\nCortex {'dry run' if dry_run else 'run'} complete — {datetime.now().strftime('%-d %b %Y')}")
+ print("─" * 50)
+ print(f"Threads fetched: {stats['fetched']}")
+ print(f"Skipped (duplicate): {stats['skipped_duplicate']}")
+ print(f"Skipped (pre-filter): {stats['skipped_prefilter']}")
+ print(f"Skipped (sig 1): {stats['sig_1']}")
+ print(f"AI processed: {stats['ai_processed']}")
+ print("─" * 50)
+
+ if dry_run:
+ if dry_run_rows:
+ print(f"\n{'Thread ID':<12} {'Sig':>3} {'Action':<30} Subject")
+ print("─" * 80)
+ for row in dry_run_rows:
+ print(f"{row['id'][:12]:<12} {str(row['sig']):>3} {row['action'][:30]:<30} {row['subject'][:40]}")
+ print("\n(Dry run — no files written)")
+ else:
+ print(f"Contacts upserted: {stats['contacts_added'] + stats['contacts_updated']} ({stats['contacts_added']} new, {stats['contacts_updated']} updated)")
+ print(f"Clients upserted: {stats['clients_added'] + stats['clients_updated']} ({stats['clients_added']} new, {stats['clients_updated']} updated)")
+ print(f"Communications logged: {stats['comms_logged']}")
+ print(f"Facts stored: {stats['facts_stored']}")
+ if stats["errors"]:
+ print(f"Errors: {stats['errors']}")
+ print(f"Duration: {duration}s")
+ print(f"Storage: {CORTEX_DIR}")
+ print()
+
+
+# ─── Entry ────────────────────────────────────────────────────────────────────
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="Knowledge Cortex Gmail miner")
+ parser.add_argument("--dry-run", action="store_true", help="Preview without writing")
+ parser.add_argument("--from", dest="from_date", metavar="YYYY-MM-DD", help="Override start date")
+ parser.add_argument("--batch-size", type=int, default=BATCH_SIZE, help="Threads per run")
+ args = parser.parse_args()
+
+ CORTEX_DIR.mkdir(parents=True, exist_ok=True)
+ (CORTEX_DIR / "originals").mkdir(exist_ok=True)
+
+ run_mining(
+ dry_run=args.dry_run,
+ from_date=args.from_date,
+ batch_size=args.batch_size,
+ )
diff --git a/plugins/knowledge-cortex/skills/cortex-query/SKILL.md b/plugins/knowledge-cortex/skills/cortex-query/SKILL.md
new file mode 100644
index 00000000..721f1129
--- /dev/null
+++ b/plugins/knowledge-cortex/skills/cortex-query/SKILL.md
@@ -0,0 +1,53 @@
+---
+name: cortex-query
+description: >
+ Search and query your Knowledge Cortex (~/.cortex/).
+ Use when asked to "cortex stats", "cortex search", "cortex client",
+ "cortex contacts", "cortex export", "cortex prune",
+ "search my knowledge base", or "what do I know about COMPANY".
+ Queries portable JSONL/JSON files for contacts, clients, communications, and facts.
+---
+
+# Knowledge Cortex — Query
+
+Search, browse, and export your Knowledge Cortex flat files.
+
+## When invoked
+
+Read `{skill_path}/references/file-schema.md` for the storage format.
+
+## Commands
+
+| What user says | Action |
+|----------------|--------|
+| "cortex stats" | Show knowledge base stats |
+| "cortex search QUERY" | Search across all records |
+| "cortex client DOMAIN" | Full dossier for a client |
+| "cortex contacts [filter]" | List contacts |
+| "cortex export TYPE" | Export contacts, clients, knowledge, or comms |
+| "cortex prune" | Remove low-value records |
+
+## Usage
+
+```bash
+python3 {skill_path}/scripts/cortex-query.py stats
+python3 {skill_path}/scripts/cortex-query.py search "QUERY"
+python3 {skill_path}/scripts/cortex-query.py client domain.com
+python3 {skill_path}/scripts/cortex-query.py contacts [filter]
+python3 {skill_path}/scripts/cortex-query.py export contacts --format csv
+python3 {skill_path}/scripts/cortex-query.py export knowledge --format json
+python3 {skill_path}/scripts/cortex-query.py prune --dry-run
+python3 {skill_path}/scripts/cortex-query.py prune
+```
+
+Print output directly to the user.
+
+## Environment
+
+| Variable | Default | Purpose |
+|----------|---------|---------|
+| `CORTEX_DIR` | `~/.cortex` | Storage root |
+
+## References
+
+- File schemas: `{skill_path}/references/file-schema.md`
diff --git a/plugins/knowledge-cortex/skills/cortex-query/references/file-schema.md b/plugins/knowledge-cortex/skills/cortex-query/references/file-schema.md
new file mode 100644
index 00000000..797b1066
--- /dev/null
+++ b/plugins/knowledge-cortex/skills/cortex-query/references/file-schema.md
@@ -0,0 +1,108 @@
+# File Schema Reference
+
+Storage root: `~/.cortex/` (or `$CORTEX_DIR`)
+
+---
+
+## contacts.json — keyed by email (lowercase)
+
+```json
+{
+ "name": "Jane Smith",
+ "email": "[email protected]",
+ "phone": null,
+ "role": "Director",
+ "company": "Smith Holdings Pty Ltd",
+ "company_domain": "smithholdings.com.au",
+ "first_seen": "2024-03-15T09:00:00+11:00",
+ "last_seen": "2026-03-10T14:22:00+11:00",
+ "thread_count": 7,
+ "source": "gmail"
+ }
+}
+```
+
+**Upsert rules:** update non-null fields; keep earlier `first_seen`; keep later `last_seen`; increment `thread_count`.
+
+---
+
+## clients.json — keyed by domain (or slugified name if no domain)
+
+```json
+{
+ "smithholdings.com.au": {
+ "name": "Smith Holdings Pty Ltd",
+ "domain": "smithholdings.com.au",
+ "industry": null,
+ "abn": null,
+ "first_seen": "2024-03-15T09:00:00+11:00",
+ "last_seen": "2026-03-10T14:22:00+11:00",
+ "thread_count": 12,
+ "contact_emails": ["[email protected]"],
+ "source": "gmail"
+ }
+}
+```
+
+---
+
+## communications.jsonl — append-only, one JSON per line
+
+```json
+{"id":"comm_1741824000_a3f2","source":"gmail","source_id":"18e2a3b4c5d6e7f8","source_url":"https://mail.google.com/mail/u/0/#all/18e2a3b4c5d6e7f8","channel":"email","subject":"Website redesign quote","participants":["[email protected]","[email protected]"],"summary":"Client enquired about a full website redesign. Agreed to send a quote by end of week.","communication_type":"quote","significance":4,"client_domain":"clientco.com.au","project":null,"thread_date":"2026-03-10T11:30:00+11:00","processed_at":"2026-03-13T06:15:00+11:00"}
+```
+
+`source_id` = Gmail thread ID. **Idempotency key** — always check before processing.
+
+**significance:** 1=junk, 2=routine FYI, 3=normal business, 4=important, 5=critical
+
+---
+
+## knowledge.jsonl — append-only, one JSON per line
+
+```json
+{"id":"know_1741824000_b7c1","fact":"Client prefers phone contact over email","kind":"preference","client_domain":"clientco.com.au","contact_email":"[email protected]","project":null,"source":"gmail","source_id":"18e2a3b4c5d6e7f8","source_url":"https://mail.google.com/mail/u/0/#all/18e2a3b4c5d6e7f8","thread_date":"2026-03-10T11:30:00+11:00","created_at":"2026-03-13T06:15:00+11:00"}
+```
+
+**kind values:** `decision` | `commitment` | `deadline` | `amount` | `preference` | `feedback` | `relationship` | `other`
+
+---
+
+## files.jsonl — append-only, one JSON per line (Phase 2)
+
+```json
+{"id":"file_1741824000_c9d4","filename":"quote-march.pdf","mime_type":"application/pdf","file_type":"pdf","source":"gmail_attachment","source_thread_id":"18e2a3b4c5d6e7f8","client_domain":"clientco.com.au","extracted_text":"Full text...","description":"A website redesign quote totalling $4,200...","extraction_method":"pdftotext","description_method":"claude-api","thread_date":"2026-03-10T11:30:00+11:00","processed_at":"2026-03-13T06:15:00+11:00"}
+```
+
+---
+
+## state.json — cursor and run history
+
+```json
+{
+ "version": "1.0",
+ "cursors": {"gmail": 1741824000, "google_chat": null, "calendar": null},
+ "last_run": "2026-03-13T06:00:00+11:00",
+ "totals": {"contacts": 142, "clients": 67, "communications": 503, "knowledge": 289, "files": 0},
+ "runs": [
+ {
+ "date": "2026-03-13T06:00:00+11:00",
+ "source": "gmail",
+ "fetched": 50,
+ "filtered": 33,
+ "ai_processed": 17,
+ "contacts_added": 2,
+ "contacts_updated": 1,
+ "clients_added": 1,
+ "clients_updated": 2,
+ "comms_logged": 15,
+ "facts_stored": 8,
+ "errors": 0,
+ "duration_seconds": 47
+ }
+ ]
+}
+```
+
+Keep last 30 runs. Trim oldest on write.
diff --git a/plugins/knowledge-cortex/skills/cortex-query/scripts/cortex-query.py b/plugins/knowledge-cortex/skills/cortex-query/scripts/cortex-query.py
new file mode 100644
index 00000000..47ca2879
--- /dev/null
+++ b/plugins/knowledge-cortex/skills/cortex-query/scripts/cortex-query.py
@@ -0,0 +1,382 @@
+#!/usr/bin/env python3
+"""
+cortex-query.py — Query your Knowledge Cortex
+
+Usage:
+ python3 cortex-query.py stats
+ python3 cortex-query.py search "ABC Company"
+ python3 cortex-query.py client domain.com
+ python3 cortex-query.py contacts [filter]
+ python3 cortex-query.py prune [--dry-run]
+ python3 cortex-query.py export contacts|clients|knowledge [--format csv]
+
+Set CORTEX_DIR env var to override default (~/.cortex)
+"""
+
+import csv
+import json
+import os
+import sys
+from datetime import datetime
+from pathlib import Path
+
+# ─── Config ──────────────────────────────────────────────────────────────────
+
+CORTEX_DIR = Path(os.environ.get("CORTEX_DIR", Path.home() / ".cortex"))
+FILES = {
+ "contacts": CORTEX_DIR / "contacts.json",
+ "clients": CORTEX_DIR / "clients.json",
+ "communications": CORTEX_DIR / "communications.jsonl",
+ "knowledge": CORTEX_DIR / "knowledge.jsonl",
+ "files": CORTEX_DIR / "files.jsonl",
+ "state": CORTEX_DIR / "state.json",
+}
+
+# ─── Helpers ─────────────────────────────────────────────────────────────────
+
+def read_json(path, fallback=None):
+ if fallback is None:
+ fallback = {}
+ if not path.exists():
+ return fallback
+ try:
+ return json.loads(path.read_text())
+ except Exception:
+ return fallback
+
+
+def read_jsonl(path):
+ if not path.exists():
+ return []
+ records = []
+ for line in path.read_text(encoding="utf-8").splitlines():
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ records.append(json.loads(line))
+ except Exception:
+ pass
+ return records
+
+
+def write_jsonl(path, records):
+ path.write_text(
+ "\n".join(json.dumps(r, ensure_ascii=False) for r in records) + "\n",
+ encoding="utf-8"
+ )
+
+
+def matches(record, query):
+ return query.lower() in json.dumps(record, ensure_ascii=False).lower()
+
+
+def fmt_date(iso):
+ if not iso:
+ return "unknown"
+ try:
+ dt = datetime.fromisoformat(iso.replace("Z", "+00:00"))
+ return dt.strftime("%-d %b %Y")
+ except Exception:
+ return iso[:10]
+
+
+def trunc(s, n=80):
+ if not s:
+ return ""
+ return s[:n - 1] + "…" if len(s) > n else s
+
+
+def hr(char="─", width=56):
+ return char * width
+
+
+# ─── Commands ─────────────────────────────────────────────────────────────────
+
+def cmd_stats():
+ state = read_json(FILES["state"])
+ contacts = read_json(FILES["contacts"])
+ clients = read_json(FILES["clients"])
+ comms = read_jsonl(FILES["communications"])
+ knowledge = read_jsonl(FILES["knowledge"])
+
+ print(f"\nKnowledge Cortex — Stats")
+ print(hr())
+ print(f"Storage: {CORTEX_DIR}")
+ print(f"Last run: {fmt_date(state.get('last_run')) or 'never'}")
+ print(f"Total runs: {len(state.get('runs', []))}")
+ print(hr())
+ print(f"Contacts: {len(contacts)}")
+ print(f"Clients: {len(clients)}")
+ print(f"Communications: {len(comms)}")
+ print(f"Knowledge facts: {len(knowledge)}")
+ print(hr())
+
+ print("Communications by significance:")
+ for sig in range(1, 6):
+ count = sum(1 for c in comms if c.get("significance") == sig)
+ bar = "█" * min(count, 40)
+ print(f" [{sig}] {bar} {count}")
+
+ print(hr())
+ print("Knowledge by kind:")
+ kind_counts: dict[str, int] = {}
+ for k in knowledge:
+ kind = k.get("kind", "other")
+ kind_counts[kind] = kind_counts.get(kind, 0) + 1
+ for kind, count in sorted(kind_counts.items(), key=lambda x: -x[1]):
+ print(f" {kind:<16} {count}")
+
+ runs = state.get("runs", [])
+ if runs:
+ last = runs[-1]
+ print(hr())
+ print("Last run:")
+ print(f" {fmt_date(last.get('date'))} · {last.get('fetched', 0)} fetched · "
+ f"{last.get('ai_processed', 0)} AI processed · {last.get('facts_stored', 0)} facts · "
+ f"{last.get('duration_seconds', 0)}s")
+ print()
+
+
+def cmd_search(query):
+ if not query:
+ print("Usage: cortex-query.py search \"query\"")
+ sys.exit(1)
+
+ contacts = read_json(FILES["contacts"])
+ clients = read_json(FILES["clients"])
+ comms = read_jsonl(FILES["communications"])
+ knowledge = read_jsonl(FILES["knowledge"])
+
+ m_contacts = [c for c in contacts.values() if matches(c, query)]
+ m_clients = [c for c in clients.values() if matches(c, query)]
+ m_facts = [k for k in knowledge if matches(k, query)]
+ m_comms = [c for c in comms if matches(c, query)]
+
+ print(f"\nSearch: \"{query}\"")
+ print(hr())
+
+ if m_contacts:
+ print(f"\nContacts ({len(m_contacts)})")
+ for c in m_contacts[:10]:
+ print(f" {c.get('name', 'Unknown')} <{c.get('email', '')}>")
+ if c.get("company"):
+ print(f" {c.get('role', 'Contact')} at {c['company']}")
+ print(f" Last: {fmt_date(c.get('last_seen'))} · {c.get('thread_count', 0)} threads")
+
+ if m_clients:
+ print(f"\nClients ({len(m_clients)})")
+ for c in m_clients[:10]:
+ print(f" {c.get('name')} ({c.get('domain', 'no domain')})")
+ print(f" {c.get('industry') or 'Unknown industry'} · {c.get('thread_count', 0)} threads")
+
+ if m_facts:
+ print(f"\nKnowledge ({len(m_facts)} facts)")
+ for f in m_facts[:15]:
+ print(f" [{f.get('kind', '?')}] {trunc(f.get('fact', ''), 90)}")
+ print(f" {f.get('client_domain') or 'no client'} · {fmt_date(f.get('thread_date'))}")
+ if f.get("source_url"):
+ print(f" {f['source_url']}")
+
+ if m_comms:
+ top = sorted(m_comms, key=lambda x: -x.get("significance", 0))[:10]
+ print(f"\nCommunications ({len(m_comms)} matched, top 10)")
+ for c in top:
+ print(f" [sig:{c.get('significance')}] {trunc(c.get('subject', ''), 60)}")
+ print(f" {c.get('client_domain', 'unknown')} · {fmt_date(c.get('thread_date'))}")
+ print(f" {trunc(c.get('summary', ''), 90)}")
+ if c.get("source_url"):
+ print(f" {c['source_url']}")
+
+ total = len(m_contacts) + len(m_clients) + len(m_facts) + len(m_comms)
+ if total == 0:
+ print(f" No results found for \"{query}\"")
+ print()
+
+
+def cmd_client(domain):
+ if not domain:
+ print("Usage: cortex-query.py client domain.com")
+ sys.exit(1)
+
+ clients = read_json(FILES["clients"])
+ contacts = read_json(FILES["contacts"])
+ comms = read_jsonl(FILES["communications"])
+ knowledge = read_jsonl(FILES["knowledge"])
+
+ # Exact match first, then partial
+ client = clients.get(domain)
+ if not client:
+ for c in clients.values():
+ if domain in (c.get("domain") or "") or domain.lower() in (c.get("name") or "").lower():
+ client = c
+ break
+
+ if not client:
+ print(f"\nNo client found matching: {domain}\n")
+ # Suggest similar
+ suggestions = [k for k in clients if domain[:4].lower() in k.lower()][:5]
+ if suggestions:
+ print("Did you mean:")
+ for s in suggestions:
+ print(f" {s} — {clients[s].get('name', '')}")
+ return
+
+ c_domain = client.get("domain")
+ c_contacts = [contacts[e] for e in (client.get("contact_emails") or []) if e in contacts]
+ c_comms = sorted(
+ [c for c in comms if c.get("client_domain") == c_domain],
+ key=lambda x: x.get("thread_date", ""), reverse=True
+ )
+ c_facts = sorted(
+ [k for k in knowledge if k.get("client_domain") == c_domain],
+ key=lambda x: x.get("created_at", ""), reverse=True
+ )
+
+ print(f"\n{client.get('name', domain)}")
+ print(hr())
+ print(f"Domain: {c_domain or '—'}")
+ print(f"Industry: {client.get('industry') or '—'}")
+ print(f"ABN: {client.get('abn') or '—'}")
+ print(f"First seen: {fmt_date(client.get('first_seen'))}")
+ print(f"Last seen: {fmt_date(client.get('last_seen'))}")
+ print(f"Threads: {client.get('thread_count', 0)}")
+
+ if c_contacts:
+ print(f"\nContacts ({len(c_contacts)})")
+ for c in c_contacts:
+ phone = f" · {c['phone']}" if c.get("phone") else ""
+ print(f" {c.get('name') or c.get('email')} — {c.get('role') or 'no role'}")
+ print(f" {c.get('email')}{phone}")
+
+ if c_facts:
+ print(f"\nKnowledge ({len(c_facts)} facts)")
+ for f in c_facts[:20]:
+ print(f" [{f.get('kind', '?')}] {trunc(f.get('fact', ''), 90)}")
+ print(f" {fmt_date(f.get('thread_date'))}")
+
+ if c_comms:
+ print(f"\nCommunications ({len(c_comms)} total, 10 most recent)")
+ for c in c_comms[:10]:
+ print(f" [sig:{c.get('significance')}] {trunc(c.get('subject', ''), 60)}")
+ print(f" {fmt_date(c.get('thread_date'))} · {c.get('communication_type', '')}")
+ print(f" {trunc(c.get('summary', ''), 90)}")
+ if c.get("source_url"):
+ print(f" {c['source_url']}")
+ print()
+
+
+def cmd_contacts(filter_q=None):
+ contacts = read_json(FILES["contacts"])
+ items = list(contacts.values())
+ if filter_q:
+ items = [c for c in items if matches(c, filter_q)]
+ items.sort(key=lambda x: x.get("last_seen", ""), reverse=True)
+
+ label = f' (filter: "{filter_q}")' if filter_q else ""
+ print(f"\nContacts{label} — {len(items)} total")
+ print(hr())
+ for c in items[:50]:
+ name = (c.get("name") or "Unknown").ljust(25)
+ print(f"{name} {c.get('email', '')}")
+ role = (c.get("role") or "—").ljust(20)
+ print(f" {role} {c.get('company') or '—'}")
+ print(f" Last: {fmt_date(c.get('last_seen'))} · {c.get('thread_count', 0)} threads")
+ if len(items) > 50:
+ print(f"\n ... and {len(items) - 50} more")
+ print()
+
+
+def cmd_prune(dry_run=True):
+ comms = read_jsonl(FILES["communications"])
+ knowledge = read_jsonl(FILES["knowledge"])
+
+ low_comms = [c for c in comms if c.get("significance", 3) <= 1]
+
+ seen: set[str] = set()
+ dup_facts = []
+ for k in knowledge:
+ key = f"{(k.get('fact') or '').lower().strip()}::{k.get('client_domain') or ''}"
+ if key in seen:
+ dup_facts.append(id(k))
+ else:
+ seen.add(key)
+
+ print(f"\nPrune Analysis")
+ print(hr())
+ print(f"Communications (sig <= 1): {len(low_comms)} of {len(comms)}")
+ print(f"Duplicate facts: {len(dup_facts)} of {len(knowledge)}")
+ print(f"Total prunable: {len(low_comms) + len(dup_facts)}")
+
+ if dry_run:
+ print(f"\n(Dry run — no changes made)")
+ print(f"Run without --dry-run to apply")
+ else:
+ kept_comms = [c for c in comms if c.get("significance", 3) > 1]
+ kept_facts = [k for k in knowledge if id(k) not in set(dup_facts)]
+ write_jsonl(FILES["communications"], kept_comms)
+ write_jsonl(FILES["knowledge"], kept_facts)
+ print(f"\nPruned {len(low_comms)} communications and {len(dup_facts)} duplicate facts")
+ print()
+
+
+def cmd_export(record_type, fmt="json"):
+ if record_type == "contacts":
+ data = list(read_json(FILES["contacts"]).values())
+ headers = ["name", "email", "phone", "role", "company", "company_domain",
+ "first_seen", "last_seen", "thread_count"]
+ elif record_type == "clients":
+ data = list(read_json(FILES["clients"]).values())
+ headers = ["name", "domain", "industry", "abn", "first_seen", "last_seen", "thread_count"]
+ elif record_type == "knowledge":
+ data = read_jsonl(FILES["knowledge"])
+ headers = ["fact", "kind", "client_domain", "contact_email", "project", "thread_date", "source_url"]
+ elif record_type == "communications":
+ data = read_jsonl(FILES["communications"])
+ headers = ["subject", "summary", "communication_type", "significance",
+ "client_domain", "thread_date", "source_url"]
+ else:
+ print("Usage: cortex-query.py export contacts|clients|knowledge|communications [--format csv]")
+ sys.exit(1)
+
+ if fmt == "csv":
+ writer = csv.writer(sys.stdout)
+ writer.writerow(headers)
+ for row in data:
+ writer.writerow([row.get(h, "") for h in headers])
+ else:
+ print(json.dumps(data, indent=2, ensure_ascii=False))
+
+
+# ─── Entry ────────────────────────────────────────────────────────────────────
+
+def main():
+ args = sys.argv[1:]
+ if not args:
+ print(__doc__)
+ return
+
+ cmd = args[0]
+ rest = args[1:]
+ dry_run = "--dry-run" in rest
+ fmt = rest[rest.index("--format") + 1] if "--format" in rest else "json"
+ positional = [a for a in rest if not a.startswith("--")]
+
+ if cmd == "stats":
+ cmd_stats()
+ elif cmd == "search":
+ cmd_search(" ".join(positional) if positional else None)
+ elif cmd == "client":
+ cmd_client(positional[0] if positional else None)
+ elif cmd == "contacts":
+ cmd_contacts(positional[0] if positional else None)
+ elif cmd == "prune":
+ cmd_prune(dry_run=dry_run)
+ elif cmd == "export":
+ cmd_export(positional[0] if positional else None, fmt=fmt)
+ else:
+ print(__doc__)
+
+
+if __name__ == "__main__":
+ main()