Skip to content

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

feat: replace knowledge-cortex with basalt plugin + add deep-research skill

Jeremy Dawes397e8cbcfbd8
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 7091421f..f49dee20 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -62,9 +62,9 @@
"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",
+ "name": "basalt",
+ "description": "Mine knowledge from Gmail, Google Chat, Slack, Drive, local files, MCP servers, and web into an Obsidian-compatible vault. Basalt format: markdown with YAML frontmatter.",
+ "source": "./plugins/basalt",
"category": "productivity"
},
{
diff --git a/CLAUDE.md b/CLAUDE.md
index 4e787db8..e9f4197d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -64,16 +64,16 @@ claude-skills/
│ │ ├── team-update/
│ │ ├── ux-audit/
│ │ ├── responsiveness-check/
-│ │ └── agent-browser/
+│ │ ├── agent-browser/
+│ │ └── deep-research/
│ ├── shopify/ # Shopify store management
│ │ └── skills/
│ │ ├── shopify-setup/
│ │ ├── shopify-products/
│ │ └── shopify-content/
-│ ├── knowledge-cortex/ # Gmail knowledge mining
+│ ├── basalt/ # Multi-source knowledge mining (Obsidian-compatible)
│ │ └── skills/
-│ │ ├── cortex-mine/
-│ │ └── cortex-query/
+│ │ └── basalt-cortex/
│ ├── wordpress/ # WordPress content & Elementor
│ │ └── skills/
│ │ ├── wordpress-setup/
diff --git a/README.md b/README.md
index 7e68f12e..a32cd043 100644
--- a/README.md
+++ b/README.md
@@ -49,9 +49,9 @@ Then just ask Claude what you need — installed skills trigger automatically fr
| Plugin | Skills | What it does |
|--------|--------|-------------|
-| **dev-tools** | project-health, project-docs, app-docs, dev-session, team-update, github-release, brains-trust, git-workflow, ux-audit, responsiveness-check, agent-browser | Project config and permissions, doc generation (ARCHITECTURE/API/DB), app user guides with screenshots, session tracking, team chat updates, GitHub releases, multi-model second opinions, git workflows, UX dogfooding (quick/standard/thorough), responsive layout testing, browser automation |
+| **dev-tools** | project-health, project-docs, app-docs, dev-session, team-update, github-release, brains-trust, git-workflow, ux-audit, responsiveness-check, agent-browser, deep-research | Project config and permissions, doc generation, app user guides with screenshots, session tracking, team chat updates, GitHub releases, multi-model second opinions, git workflows, UX dogfooding (quick/standard/thorough), responsive layout testing, browser automation, deep research and discovery |
| **integrations** | gws-setup, gws-install, google-chat-messages, google-apps-script, elevenlabs-agents, mcp-builder, nemoclaw-setup, parcel-tracking | Google Workspace MCP setup, Google Chat webhooks, Apps Script automation, ElevenLabs voice agents, MCP server building, NVIDIA NemoClaw agent platform setup, Australian parcel tracking via Gmail |
-| **knowledge-cortex** | cortex-mine, cortex-query | Mine Gmail history into portable flat files — contacts, clients, communications, knowledge facts |
+| **basalt** | basalt-cortex | Mine knowledge from Gmail, Chat, Slack, Drive, local files, MCP, web into an Obsidian-compatible vault (~/.cortex/) |
## All 53 Skills
@@ -96,8 +96,8 @@ Then just ask Claude what you need — installed skills trigger automatically fr
| `ux-audit` | "ux audit", "dogfood the app" |
| `responsiveness-check` | "check responsiveness", "test viewports" |
| `agent-browser` | "browser automation", "navigate to" |
-| `cortex-mine` | "mine gmail", "extract contacts from email" |
-| `cortex-query` | "query cortex", "search mined data" |
+| `basalt-cortex` | "run the cortex", "mine emails", "mine slack", "cortex search" |
+| `deep-research` | "research this", "deep research", "explore the space" |
| `shopify-setup` | "shopify setup", "connect shopify" |
| `shopify-products` | "shopify products", "add products" |
| `shopify-content` | "shopify pages", "shopify blog" |
diff --git a/plugins/basalt/.claude-plugin/plugin.json b/plugins/basalt/.claude-plugin/plugin.json
new file mode 100644
index 00000000..896aeb7c
--- /dev/null
+++ b/plugins/basalt/.claude-plugin/plugin.json
@@ -0,0 +1,5 @@
+{
+ "name": "basalt",
+ "description": "Mine knowledge from Gmail, Google Chat, Slack, Drive, local files, MCP servers, and web into an Obsidian-compatible vault. Basalt format: markdown files with YAML frontmatter.",
+ "author": { "name": "Jeremy Dawes / Jezweb", "email": "[email protected]" }
+}
diff --git a/plugins/basalt/commands/basalt-cortex.md b/plugins/basalt/commands/basalt-cortex.md
new file mode 100644
index 00000000..3b995935
--- /dev/null
+++ b/plugins/basalt/commands/basalt-cortex.md
@@ -0,0 +1,15 @@
+---
+description: Mine knowledge from multiple sources into an Obsidian-compatible vault
+argument-hint: "[init|mine|query|stats|sync] [source|search-term|--from DATE]"
+---
+
+Load the `basalt-cortex` skill.
+
+Parse $ARGUMENTS for mode and parameters:
+- `init` — create ~/.cortex/ vault structure
+- `mine [source]` — extract from a source (gmail, chat, slack, drive, local, web). Default: gmail
+- `query [term]` — search across all Basalt files
+- `stats` — show vault statistics
+- `sync` — push to Frond (future)
+
+Examples: `/basalt-cortex mine gmail --from 2026-01-01`, `/basalt-cortex query smith holdings`, `/basalt-cortex init`
diff --git a/plugins/basalt/skills/basalt-cortex/SKILL.md b/plugins/basalt/skills/basalt-cortex/SKILL.md
new file mode 100644
index 00000000..e71fbe95
--- /dev/null
+++ b/plugins/basalt/skills/basalt-cortex/SKILL.md
@@ -0,0 +1,240 @@
+---
+name: basalt-cortex
+description: "Mine knowledge from Gmail, Google Chat, Slack, Drive, local files, MCP servers, and web into an Obsidian-compatible vault (~/.cortex/). Basalt format: markdown files with YAML frontmatter for clients, contacts, communications, and knowledge facts. Opens directly in Obsidian, syncs to Frond. Triggers: 'run the cortex', 'mine emails', 'mine slack', 'mine chat', 'cortex init', 'cortex search', 'cortex stats', 'what do I know about', 'set up cortex', 'mine my inbox'."
+compatibility: claude-code-only
+---
+
+# Basalt Cortex
+
+Mine knowledge from multiple sources into Obsidian-compatible markdown files stored in `~/.cortex/`. Each file has structured YAML frontmatter. Open `~/.cortex/` in Obsidian at any time — it's a valid vault.
+
+**Read [references/basalt-format.md](references/basalt-format.md) before any file operations.**
+
+## Modes
+
+| Mode | Trigger | What it does |
+|------|---------|-------------|
+| **init** | "set up cortex", "cortex init" | Create vault structure, state.json, example notes |
+| **mine** | "run the cortex", "mine emails", "mine slack" | Extract from a source, write Basalt files |
+| **query** | "cortex search", "what do I know about" | Search across Basalt files |
+| **stats** | "cortex stats" | Count files, show vault totals |
+| **sync** | "cortex sync" | Push to Frond API (future — see references/sync-patterns.md) |
+
+---
+
+## Init Mode
+
+Create the vault structure. Run once before first mine.
+
+### Check for existing vault
+
+```bash
+ls ~/.cortex/state.json 2>/dev/null && echo "EXISTS" || echo "FRESH"
+```
+
+If EXISTS: ask user — skip, reset (data loss warning), or continue (add missing folders only).
+
+### Create structure
+
+```bash
+mkdir -p ~/.cortex/{clients,contacts,communications,knowledge,projects,notes,.obsidian}
+```
+
+### Write state.json
+
+```json
+{
+ "version": "1.0",
+ "format": "basalt",
+ "cursors": { "gmail": null, "google_chat": null, "slack": null, "calendar": null },
+ "last_run": null,
+ "totals": { "clients": 0, "contacts": 0, "communications": 0, "knowledge": 0 },
+ "processed_source_ids": [],
+ "runs": []
+}
+```
+
+### Write Obsidian config
+
+```json
+// ~/.cortex/.obsidian/app.json
+{ "newFileLocation": "folder", "newFileFolderPath": "notes" }
+```
+
+### Write 3 example notes
+
+Create one example client, contact, and knowledge note in Basalt format so the user can see the structure. Use templates from [references/basalt-format.md](references/basalt-format.md).
+
+Report the created structure to the user. Tell them to open `~/.cortex/` in Obsidian.
+
+---
+
+## Mine Mode
+
+Extract knowledge from a source and write Basalt-format files.
+
+### Source Selection
+
+Ask or detect which source to mine:
+
+| Source | Prerequisites | Fetch method |
+|--------|-------------|-------------|
+| **gmail** | `gws` CLI + auth | `gws gmail messages list`, `gws gmail messages get` |
+| **google-chat** | `gws` CLI + auth | `gws chat spaces list`, `gws chat messages list` |
+| **slack** | Slack MCP or API token | MCP tools or `curl` with token |
+| **google-drive** | `gws` CLI + auth | `gws drive files list`, `gws drive files get` |
+| **local** | — | `find` + `cat` on local directories |
+| **mcp** | MCP server connected | MCP tool calls (brain_recall, vault recall, etc.) |
+| **web** | Web scraper or fetch | WebFetch, Firecrawl, or browser automation |
+| **calendar** | `gws` CLI + auth | `gws calendar events list` |
+| **obsidian** | Existing vault path | Read `.md` files, normalise frontmatter to Basalt |
+
+Default: `gmail` if no source specified.
+
+### Prerequisites Check
+
+```bash
+# For Gmail/Chat/Drive/Calendar:
+which gws || echo "MISSING: npm install -g @googleworkspace/cli"
+# For AI extraction:
+echo $ANTHROPIC_API_KEY | head -c 5 || echo "MISSING: set ANTHROPIC_API_KEY"
+# Vault exists:
+ls ~/.cortex/state.json 2>/dev/null || echo "NOT INITIALISED: run cortex init first"
+```
+
+### Extraction Workflow
+
+For each source, the pattern is the same:
+
+1. **Fetch** raw data (emails, messages, files, pages)
+2. **Pre-filter** — skip automated content, check source_id against state.json processed list. See [references/prefilter-patterns.md](references/prefilter-patterns.md).
+3. **AI Extract** — send content to an LLM with an extraction prompt (see below)
+4. **Write** Basalt files — one `.md` file per entity with YAML frontmatter
+5. **Update state** — add source_ids to processed list, update cursors and totals
+
+### AI Extraction Prompt Pattern
+
+Generate a script that sends each piece of raw content to an LLM with this prompt structure:
+
+```
+You are extracting structured knowledge from a [source type].
+For each item, identify and output JSON for:
+
+1. CONTACTS: people mentioned (name, email, role, company)
+2. CLIENTS: businesses/organisations (name, domain, industry)
+3. COMMUNICATIONS: the interaction itself (subject, participants, summary, type)
+4. KNOWLEDGE: facts, decisions, preferences, commitments extracted from the content
+
+For each entity, generate a `summary` field: 1-3 sentences, dense with names and context.
+This summary is used for semantic search — make it specific and useful.
+
+Output as JSON array of {type, data} objects.
+```
+
+### Basalt File Writing Pattern
+
+For each extracted entity, write a markdown file with YAML frontmatter:
+
+- **Path**: determined by type (see basalt-format.md)
+- **ID**: deterministic — `client_{domain}`, `contact_{email_slug}`, `comm_{timestamp}_{hash}`
+- **Upsert**: if file exists, merge (keep earlier `first_seen`, update `last_seen`, increment `thread_count`)
+- **Wikilinks**: add `[[related]]` links between connected entities
+
+See [references/basalt-format.md](references/basalt-format.md) for complete field specs per entity type.
+
+### Script Generation
+
+**Do NOT look for a pre-built script.** Generate a Python script in `.jez/scripts/` adapted to:
+- The user's chosen source
+- Their available tools (gws CLI, MCP servers, API keys)
+- Their preferred LLM (Anthropic API, local Ollama, Workers AI)
+- Batch size and date range from arguments
+
+See [references/source-patterns.md](references/source-patterns.md) for per-source fetch + extract patterns.
+
+### Common Arguments
+
+| Argument | Effect |
+|----------|--------|
+| `--dry-run` | Print what would be written, don't touch disk |
+| `--from YYYY-MM-DD` | Only process items from this date onward |
+| `--batch-size N` | Process N items per run (default: 50) |
+| `--source SOURCE` | Which source to mine |
+
+### Environment
+
+| Variable | Default | Purpose |
+|----------|---------|---------|
+| `CORTEX_DIR` | `~/.cortex` | Storage root |
+| `ANTHROPIC_API_KEY` | — | For AI extraction |
+| `CORTEX_BATCH_SIZE` | `50` | Items per run |
+| `CORTEX_OWNER_EMAIL` | — | Your email — excluded from contacts |
+
+---
+
+## Query Mode
+
+Search across Basalt files. Claude can do this natively — no script needed.
+
+### Commands
+
+| What user says | Action |
+|----------------|--------|
+| "cortex search QUERY" | Grep frontmatter + content across all files |
+| "what do I know about COMPANY" | Read `clients/{domain}.md` + find related comms and knowledge |
+| "cortex contacts" | List all files in `contacts/` with name and email from frontmatter |
+| "cortex client DOMAIN" | Full dossier — client file + linked contacts + recent comms + facts |
+| "cortex export TYPE" | Export to CSV or JSON |
+
+### Search Pattern
+
+```bash
+# Keyword search across all Basalt files
+grep -rl "QUERY" ~/.cortex/ --include="*.md"
+
+# Frontmatter field search
+grep -rl "client_domain: example.com" ~/.cortex/ --include="*.md"
+```
+
+For structured queries, read frontmatter with Python `frontmatter` library or parse YAML between `---` markers.
+
+---
+
+## Stats Mode
+
+```bash
+echo "Clients: $(find ~/.cortex/clients -name '*.md' 2>/dev/null | wc -l)"
+echo "Contacts: $(find ~/.cortex/contacts -name '*.md' 2>/dev/null | wc -l)"
+echo "Communications: $(find ~/.cortex/communications -name '*.md' 2>/dev/null | wc -l)"
+echo "Knowledge: $(find ~/.cortex/knowledge -name '*.md' 2>/dev/null | wc -l)"
+echo "Notes: $(find ~/.cortex/notes -name '*.md' 2>/dev/null | wc -l)"
+```
+
+Also read `state.json` for last run date, cursor positions, and run history.
+
+---
+
+## Sync Mode (Future)
+
+Push Basalt files to Frond, D1, or Vectorize. See [references/sync-patterns.md](references/sync-patterns.md).
+
+Not yet built — placeholder for when Frond API token auth is ready.
+
+---
+
+## Scheduling
+
+| Method | How |
+|--------|-----|
+| Claude Code Cowork | Scheduled task: "Run basalt-cortex mine gmail" > Daily |
+| Cron | `0 6 * * * ANTHROPIC_API_KEY=sk-... python3 ~/.jez/scripts/cortex-mine-gmail.py` |
+| `/loop` | `/loop 24h basalt-cortex mine gmail` |
+
+## References
+
+| When | Read |
+|------|------|
+| Before any file operations | [references/basalt-format.md](references/basalt-format.md) |
+| Per-source fetch and extract patterns | [references/source-patterns.md](references/source-patterns.md) |
+| Before processing raw content | [references/prefilter-patterns.md](references/prefilter-patterns.md) |
+| When syncing to Frond/D1/Vectorize | [references/sync-patterns.md](references/sync-patterns.md) |
diff --git a/plugins/basalt/skills/basalt-cortex/references/basalt-format.md b/plugins/basalt/skills/basalt-cortex/references/basalt-format.md
new file mode 100644
index 00000000..11faa18b
--- /dev/null
+++ b/plugins/basalt/skills/basalt-cortex/references/basalt-format.md
@@ -0,0 +1,268 @@
+# Basalt Format
+
+**Basalt** is the file format standard used by Knowledge Cortex.
+
+Name: basalt is the volcanic rock that obsidian forms from. It's the underlying substrate — fully compatible with Obsidian but not dependent on it.
+
+## What It Is
+
+Markdown files with structured YAML frontmatter. Every file is:
+- A valid Obsidian note (open `~/.cortex/` as an Obsidian vault)
+- Readable by Claude Code directly without parsing
+- Syncable to D1 via frontmatter field mapping
+- Embeddable in Vectorize via the `summary` field
+- Importable into Frond via `/api/notes`
+
+Files are the source of truth. D1, Vectorize, and Frond are projections.
+
+---
+
+## Folder Structure
+
+```
+~/.cortex/ # vault root — open in Obsidian directly
+├── .obsidian/ # Obsidian config (can be empty or gitignored)
+├── clients/
+│ └── smithholdings.com.au.md
+├── contacts/
+│ └── jane-smith.md
+├── communications/
+│ └── 2026/03/
+│ └── comm_1741824000_a3f2.md
+├── knowledge/
+│ └── know_1741824000_b7c1.md
+├── projects/ # future
+├── notes/ # manual notes, not mined
+└── state.json # cursor + run history (not a note)
+```
+
+---
+
+## Universal Frontmatter Fields
+
+Every Basalt note has these fields:
+
+```yaml
+---
+# Identity
+id: client_smithholdings.com.au # stable, deterministic, machine-generated
+type: client # client | contact | communication | knowledge | project | note
+created: 2024-03-15T09:00:00+11:00
+updated: 2026-03-13T06:15:00+11:00
+
+# Obsidian-native (Obsidian reads these, ignores everything else)
+tags: [client, active]
+aliases: [Smith Holdings, SH]
+
+# Provenance
+source: gmail # gmail | google_chat | calendar | manual | frond
+source_id: 18e2a3b4c5d6e7f8 # idempotency key — check before processing
+source_url: https://mail.google.com/mail/u/0/#all/18e2a3b4c5d6e7f8
+
+# Semantic layer
+summary: "Web dev client since 2019. Prefers phone. Active WordPress maintenance plan."
+# ^ 1-3 sentences, dense with names/context. This is the Vectorize embedding input.
+
+# Access
+visibility: private # private | team | public
+---
+```
+
+### `id` generation rules
+
+| Type | Pattern | Example |
+|------|---------|---------|
+| client | `client_{domain}` | `client_smithholdings.com.au` |
+| contact | `contact_{email_slug}` | `contact_jane-smith-smithholdings.com.au` |
+| communication | `comm_{unix_ts}_{4char_hash}` | `comm_1741824000_a3f2` |
+| knowledge | `know_{unix_ts}_{4char_hash}` | `know_1741824000_b7c1` |
+| project | `project_{slug}` | `project_smith-redesign-2025` |
+
+---
+
+## Type: `client`
+
+File: `clients/{domain}.md`
+
+```yaml
+---
+id: client_smithholdings.com.au
+type: client
+created: 2024-03-15T09:00:00+11:00
+updated: 2026-03-13T06:15:00+11:00
+tags: [client, active]
+aliases: [Smith Holdings, SH]
+source: gmail
+source_id: ~
+source_url: ~
+summary: "Web dev client since 2019. Prefers phone. Active WordPress maintenance plan."
+visibility: private
+
+name: Smith Holdings Pty Ltd
+domain: smithholdings.com.au
+abn: ~
+industry: ~
+first_seen: 2024-03-15
+last_seen: 2026-03-10
+thread_count: 12
+significance: 3 # 1=minimal 2=light 3=normal 4=important 5=critical
+
+related: ["[[contacts/jane-smith]]"]
+---
+
+# Smith Holdings Pty Ltd
+
+## Contacts
+- [[contacts/jane-smith]] — Director
+
+## Recent Communications
+<!-- cortex-mine appends here -->
+
+## Facts
+<!-- cortex-mine appends here -->
+```
+
+---
+
+## Type: `contact`
+
+File: `contacts/{slug}.md`
+
+```yaml
+---
+id: contact_jane-smith-smithholdings.com.au
+type: contact
+created: 2024-03-15T09:00:00+11:00
+updated: 2026-03-10T14:22:00+11:00
+tags: [contact]
+aliases: [Jane Smith]
+source: gmail
+source_id: ~
+source_url: ~
+summary: "Director at Smith Holdings. Primary contact for all web projects. Prefers brief emails."
+visibility: private
+
+name: Jane Smith
+phone: ~
+role: Director
+company: Smith Holdings Pty Ltd
+company_domain: smithholdings.com.au
+first_seen: 2024-03-15
+last_seen: 2026-03-10
+thread_count: 7
+
+related: ["[[clients/smithholdings.com.au]]"]
+---
+
+# Jane Smith
+```
+
+---
+
+## Type: `communication`
+
+File: `communications/{YYYY}/{MM}/{id}.md`
+
+```yaml
+---
+id: comm_1741824000_a3f2
+type: communication
+created: 2026-03-10T11:30:00+11:00
+updated: 2026-03-10T11:30:00+11:00
+tags: [communication, email, quote]
+source: gmail
+source_id: 18e2a3b4c5d6e7f8
+source_url: https://mail.google.com/mail/u/0/#all/18e2a3b4c5d6e7f8
+summary: "Client requested full website redesign quote. Agreed to send by end of week."
+visibility: private
+
+channel: email # email | google_chat | calendar | phone | note
+subject: Website redesign quote
+communication_type: quote # quote | support | onboarding | billing | general
+significance: 4
+client_domain: smithholdings.com.au
+project: ~
+thread_date: 2026-03-10T11:30:00+11:00
+
+related: ["[[clients/smithholdings.com.au]]"]
+---
+
+# Website redesign quote — 10 Mar 2026
+
+Client asked about full redesign. Discussed timeline and budget. Agreed to send formal quote by Friday.
+```
+
+---
+
+## Type: `knowledge`
+
+File: `knowledge/{id}.md`
+
+```yaml
+---
+id: know_1741824000_b7c1
+type: knowledge
+created: 2026-03-10T11:30:00+11:00
+updated: 2026-03-10T11:30:00+11:00
+tags: [knowledge, preference]
+source: gmail
+source_id: 18e2a3b4c5d6e7f8
+source_url: https://mail.google.com/mail/u/0/#all/18e2a3b4c5d6e7f8
+summary: "Jane Smith at Smith Holdings prefers phone contact over email for project discussions."
+visibility: private
+
+kind: preference # decision | commitment | deadline | amount | preference | feedback | relationship | other
+client_domain: smithholdings.com.au
+contact_email: [email protected]
+project: ~
+thread_date: 2026-03-10T11:30:00+11:00
+
+related: ["[[clients/smithholdings.com.au]]", "[[contacts/jane-smith]]"]
+---
+
+Client prefers phone contact over email for project discussions.
+```
+
+---
+
+## D1 Sync Mapping
+
+When syncing to D1, extract frontmatter fields directly:
+
+| Frontmatter | D1 column | Notes |
+|-------------|-----------|-------|
+| `id` | PRIMARY KEY | Upsert key |
+| `type` | routes to table | `client` → `clients` etc |
+| `created` | `created_at` | ISO 8601 |
+| `updated` | `updated_at` | Drives incremental sync |
+| `summary` | `summary` | Vectorize embedding input |
+| `visibility` | `visibility` | Future team/public access |
+| `tags` | `tags` | JSON array |
+| `source` | `source` | |
+| `source_id` | `source_id` | Idempotency check |
+
+Upsert pattern: `INSERT OR REPLACE` keyed on `id`. Use `updated` to skip unchanged records.
+
+---
+
+## Vectorize Embedding
+
+Embed the `summary` field only. Keep summary:
+- 1–3 sentences max
+- Dense with names, domains, context
+- A factual description, not a heading or label
+
+Vector metadata payload: `id`, `type`, `client_domain`, `visibility`, `updated`
+(lets you filter without a D1 roundtrip)
+
+---
+
+## Obsidian Compatibility Notes
+
+- `tags` and `aliases` — Obsidian reads and renders natively
+- All other fields — Obsidian ignores silently, no errors or warnings
+- `[[wiki links]]` in `related` — Obsidian renders as clickable cross-references
+- Dataview plugin can query any frontmatter field as a table or list, zero config
+- Open `~/.cortex/` as a vault in Obsidian and it works today
diff --git a/plugins/basalt/skills/basalt-cortex/references/prefilter-patterns.md b/plugins/basalt/skills/basalt-cortex/references/prefilter-patterns.md
new file mode 100644
index 00000000..418f8243
--- /dev/null
+++ b/plugins/basalt/skills/basalt-cortex/references/prefilter-patterns.md
@@ -0,0 +1,86 @@
+# Pre-filter Patterns
+
+Applied before any AI call. Goal: skip 60-80% of content at near-zero cost.
+
+## Step 1: Idempotency Check (always first)
+
+Check if this item has already been processed:
+
+```python
+import json
+state = json.load(open(f"{CORTEX_DIR}/state.json"))
+if source_id in state.get("processed_source_ids", []):
+ skip # already processed
+```
+
+For file-based sources, check if a Basalt file already exists with matching `source_id` in frontmatter.
+
+## Step 2: Automated Sender Patterns (Gmail/Chat)
+
+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
+github.com, gitlab.com, bitbucket.org
+atlassian.com, jira.com, trello.com
+slack.com, notion.so, asana.com
+google.com (calendar invites, drive shares)
+cloudflare.com, aws.amazon.com
+linkedin.com, facebook.com, twitter.com
+mailchimp.com, sendinblue.com, constantcontact.com
+```
+
+## Step 3: Content Length Filter
+
+Skip if body is too short to contain useful knowledge:
+- Email body < 50 characters after stripping HTML → skip
+- Chat message < 20 characters → skip
+- Web page < 200 characters → skip (likely JS-rendered blank)
+
+## Step 4: Subject Line Patterns (Gmail)
+
+Skip if subject matches:
+```
+/^(re:\s*)*out of office/i
+/^(re:\s*)*automatic reply/i
+/unsubscribe/i (in body, not subject)
+/^your .* receipt/i
+/^your .* order/i (unless from a real person)
+/^payment .* received/i
+/^invoice .* from/i
+```
+
+## Step 5: Bot Detection (Chat/Slack)
+
+Skip messages from:
+- Users with `[BOT]` or `[APP]` in their display name
+- Slack app messages (check `subtype: bot_message`)
+- Google Chat app messages (check `sender.type: BOT`)
+- Webhook-generated messages
+
+## Step 6: Duplicate Content Detection
+
+For communications that are part of a thread:
+- Only process the thread once (use thread ID, not individual message IDs)
+- For Gmail: the thread ID groups all replies together
+- For Slack: use `thread_ts` to group threaded replies
+- For Chat: use the space + thread key
+
+## Keep Rules (override skips)
+
+Always process if:
+- From/to a known client domain (check existing `clients/` folder)
+- Contains the owner's email in To/CC
+- Has attachments (may contain contracts, quotes, briefs)
+- Subject contains: quote, proposal, contract, agreement, invoice (from real senders)
diff --git a/plugins/basalt/skills/basalt-cortex/references/source-patterns.md b/plugins/basalt/skills/basalt-cortex/references/source-patterns.md
new file mode 100644
index 00000000..43e1fe4e
--- /dev/null
+++ b/plugins/basalt/skills/basalt-cortex/references/source-patterns.md
@@ -0,0 +1,227 @@
+# Source Extraction Patterns
+
+Per-source patterns for fetching, pre-filtering, and extracting knowledge into Basalt format. Claude generates a script from these patterns adapted to the user's environment.
+
+---
+
+## Gmail
+
+**Prerequisites**: `gws` CLI authenticated (`gws auth login -s gmail`)
+
+**Fetch pattern**:
+```bash
+# List threads (newest first, batch of 50)
+gws gmail messages list --query "newer_than:30d" --max-results 50 --format json
+
+# Get full thread content
+gws gmail messages get MESSAGE_ID --format json
+```
+
+**Pre-filter**: See prefilter-patterns.md. Skip automated senders, marketing emails, notifications.
+
+**Extract**: Send thread body to LLM. Extract contacts, client info, communication summary, knowledge facts.
+
+**Basalt mapping**:
+- Each unique sender domain → `clients/{domain}.md`
+- Each unique email address → `contacts/{slug}.md`
+- Each thread → `communications/{YYYY}/{MM}/comm_{ts}_{hash}.md`
+- Each extracted fact → `knowledge/know_{ts}_{hash}.md`
+
+**Idempotency**: Use Gmail thread ID as `source_id`. Check `state.json` processed list before processing.
+
+**Cursor**: Store the newest thread timestamp in `state.json` cursors.gmail. Next run starts from there.
+
+---
+
+## Google Chat
+
+**Prerequisites**: `gws` CLI authenticated with chat scope (`gws auth login -s chat`)
+
+**Fetch pattern**:
+```bash
+# List spaces
+gws chat spaces list --format json
+
+# List messages in a space (newest first)
+gws chat messages list SPACE_NAME --max-results 50 --format json
+```
+
+**Pre-filter**: Skip bot messages, join/leave events, reactions.
+
+**Extract**: Group messages into conversation threads (by time proximity or explicit threads). Extract decisions, action items, knowledge.
+
+**Basalt mapping**:
+- Each conversation thread → `communications/{YYYY}/{MM}/comm_{ts}_{hash}.md` with `channel: google_chat`
+- Decisions and facts → `knowledge/know_{ts}_{hash}.md`
+- New participants → `contacts/{slug}.md`
+
+**Idempotency**: Use message ID as `source_id`.
+
+---
+
+## Slack
+
+**Prerequisites**: Slack MCP connected OR Slack API token
+
+**Fetch pattern (MCP)**:
+```
+Use Slack MCP tools to list channels, read messages
+```
+
+**Fetch pattern (API)**:
+```bash
+curl -s "https://slack.com/api/conversations.list" -H "Authorization: Bearer $SLACK_TOKEN"
+curl -s "https://slack.com/api/conversations.history?channel=CHANNEL_ID&limit=50" -H "Authorization: Bearer $SLACK_TOKEN"
+```
+
+**Pre-filter**: Skip bot messages, app notifications, channel join/leave.
+
+**Extract**: Same as Google Chat — group by thread, extract decisions and knowledge.
+
+**Basalt mapping**: Same as Google Chat with `channel: slack`, `source: slack`.
+
+---
+
+## Google Drive
+
+**Prerequisites**: `gws` CLI authenticated with drive scope
+
+**Fetch pattern**:
+```bash
+# List recent files
+gws drive files list --query "modifiedTime > '2026-01-01'" --format json
+
+# Get file metadata
+gws drive files get FILE_ID --format json
+
+# Download text content (for Google Docs)
+gws drive files export FILE_ID --mime-type text/plain
+```
+
+**Pre-filter**: Skip files smaller than 100 bytes, skip image/video/audio files.
+
+**Extract**: For documents, extract the title, summary, owner, shared-with list. Don't mine the full content unless asked — Drive documents are better linked than copied.
+
+**Basalt mapping**:
+- Each document → `knowledge/know_{ts}_{hash}.md` with document URL in `source_url`
+- Shared-with lists → update `contacts/` with collaboration relationships
+- Folders → `projects/` if they represent a project
+
+---
+
+## Local Folders
+
+**Prerequisites**: None
+
+**Fetch pattern**:
+```bash
+# Find markdown files in a directory
+find /path/to/folder -name "*.md" -type f
+
+# Read each file
+cat /path/to/file.md
+```
+
+**Pre-filter**: Skip files in `node_modules/`, `.git/`, `dist/`, `.wrangler/`.
+
+**Extract**: Read frontmatter if present. If no frontmatter, extract title from first heading. Generate a summary.
+
+**Basalt mapping**:
+- Each file → type depends on content (note, knowledge, project)
+- Preserve existing frontmatter where compatible with Basalt format
+- Add `source: local`, `source_url: file:///path/to/original`
+
+---
+
+## MCP Servers
+
+**Prerequisites**: MCP server connected (Brain, Vault, or any custom server)
+
+**Fetch pattern**:
+```
+# Brain MCP
+brain_recall query="all knowledge" limit=100
+brain_knowledge list limit=100
+
+# Vault MCP
+vault recall query="all items"
+vault knowledge_list
+```
+
+**Pre-filter**: Skip items already in `~/.cortex/` by checking `source_id`.
+
+**Extract**: MCP items often already have structured fields. Map directly to Basalt frontmatter.
+
+**Basalt mapping**:
+- Brain knowledge → `knowledge/know_{ts}_{hash}.md` with `source: brain`
+- Brain clients → `clients/{domain}.md` with `source: brain`
+- Vault items → `knowledge/know_{ts}_{hash}.md` with `source: vault`
+
+---
+
+## Web Pages
+
+**Prerequisites**: WebFetch tool, Firecrawl MCP, or browser automation
+
+**Fetch pattern**:
+```
+# WebFetch
+WebFetch url="https://example.com/article"
+
+# Firecrawl
+firecrawl_scrape url="https://example.com" format=markdown
+
+# Browser
+playwright-cli -s=cortex open https://example.com
+playwright-cli -s=cortex snapshot
+```
+
+**Pre-filter**: Skip pages with less than 200 chars of content (likely JS-rendered blanks).
+
+**Extract**: Extract title, author, date, summary. For reference material, keep the full content.
+
+**Basalt mapping**:
+- Each page → `knowledge/know_{ts}_{hash}.md` or `notes/{slug}.md`
+- `source: web`, `source_url: https://...`
+
+---
+
+## Calendar
+
+**Prerequisites**: `gws` CLI authenticated with calendar scope
+
+**Fetch pattern**:
+```bash
+gws calendar events list --time-min 2026-01-01 --max-results 100 --format json
+```
+
+**Pre-filter**: Skip all-day events without descriptions, skip declined events.
+
+**Extract**: Extract meeting title, attendees, description/agenda, recurring pattern.
+
+**Basalt mapping**:
+- Each meeting → `communications/{YYYY}/{MM}/comm_{ts}_{hash}.md` with `channel: calendar`
+- New attendees → `contacts/{slug}.md`
+- Meeting notes in description → `knowledge/know_{ts}_{hash}.md`
+
+---
+
+## Obsidian Vault Import
+
+**Prerequisites**: Path to existing Obsidian vault
+
+**Fetch pattern**:
+```bash
+find /path/to/vault -name "*.md" -not -path "*/.obsidian/*" -not -path "*/.trash/*"
+```
+
+**Pre-filter**: Skip Obsidian system files (`.obsidian/`, `.trash/`).
+
+**Extract**: Read existing frontmatter. Normalise to Basalt format:
+- Add `id` if missing (generate from filename)
+- Add `type` if missing (infer from folder name or content)
+- Add `source: obsidian`, `source_url: obsidian://open?vault=NAME&file=PATH`
+- Preserve existing `tags` and `aliases` (Obsidian-native fields)
+- Generate `summary` if missing
+
+**Basalt mapping**: Preserve the file as-is with normalised frontmatter. Copy to `~/.cortex/notes/` unless the folder maps to a known type (clients/, contacts/, etc.).
diff --git a/plugins/basalt/skills/basalt-cortex/references/sync-patterns.md b/plugins/basalt/skills/basalt-cortex/references/sync-patterns.md
new file mode 100644
index 00000000..65f50da9
--- /dev/null
+++ b/plugins/basalt/skills/basalt-cortex/references/sync-patterns.md
@@ -0,0 +1,148 @@
+# Sync Patterns
+
+How `~/.cortex/` Basalt files sync to external systems. Files are the source of truth. Everything else is a projection.
+
+**Status**: Not yet built. Reference when implementing cortex-sync mode.
+
+---
+
+## Architecture
+
+```
+~/.cortex/ <- source of truth (Basalt markdown files)
+ |
+ +-> Frond API <- visual web interface, search, browse
+ +-> D1 <- SQL queries, structured lookups
+ +-> Vectorize <- semantic search via embeddings
+```
+
+One-way sync. Files are truth. External systems are read projections.
+
+---
+
+## Frond Sync
+
+Push Basalt files to Frond as notes via its API.
+
+### Prerequisites
+- Frond API token (generate at frond.au settings)
+- Store as `FROND_API_TOKEN` in `~/.cortex/.env`
+
+### Mapping
+
+| Basalt field | Frond field |
+|-------------|-------------|
+| `id` | `external_id` (upsert key) |
+| Full file content | `content` |
+| First `# heading` | `title` (auto-extracted by Frond) |
+| `type` | Determines target folder |
+| `updated` | Compare to skip unchanged |
+
+### Folder mapping
+
+| Cortex path | Frond folder |
+|-------------|-------------|
+| `clients/` | Clients |
+| `contacts/` | Contacts |
+| `communications/` | Communications |
+| `knowledge/` | Knowledge |
+| `notes/` | Notes |
+
+### Sync logic
+
+```python
+for md_file in walk_cortex():
+ basalt = parse_frontmatter(md_file)
+ existing = frond_find_by_external_id(basalt['id'])
+
+ if existing and basalt['updated'] <= existing['synced_at']:
+ continue # unchanged
+
+ if existing:
+ frond_patch(existing['id'], content=md_file.read_text())
+ else:
+ folder_id = get_or_create_folder(basalt['type'])
+ frond_create(folder_id=folder_id, content=md_file.read_text())
+
+ update_sync_state(basalt['id'], synced_at=now())
+```
+
+---
+
+## D1 Sync
+
+Parse frontmatter, map fields to columns, upsert.
+
+### Mapping
+
+| Frontmatter | D1 column | Notes |
+|-------------|-----------|-------|
+| `id` | PRIMARY KEY | Upsert key |
+| `type` | Routes to table | `client` -> `clients` etc |
+| `created` | `created_at` | ISO 8601 |
+| `updated` | `updated_at` | Drives incremental sync |
+| `summary` | `summary` | Vectorize embedding input |
+| `tags` | `tags` | JSON array |
+| `source` | `source` | |
+| `source_id` | `source_id` | Idempotency |
+
+Upsert: `INSERT OR REPLACE` keyed on `id`. Use `updated` to skip unchanged.
+
+---
+
+## Vectorize Sync
+
+Embed the `summary` field. Store vector with metadata for filtering without D1.
+
+### Embedding input
+Use only the `summary` field (1-3 sentences, dense with names/context).
+
+### Metadata payload
+```json
+{
+ "id": "client_smithholdings.com.au",
+ "type": "client",
+ "client_domain": "smithholdings.com.au",
+ "visibility": "private",
+ "updated": "2026-03-13T06:15:00+11:00"
+}
+```
+
+### Pattern
+```python
+embedding = workers_ai_embed(basalt['summary'])
+vectorize.upsert([{
+ "id": basalt['id'],
+ "values": embedding,
+ "metadata": { ... }
+}])
+```
+
+---
+
+## Sync State
+
+Track sync progress in `state.json`:
+
+```json
+{
+ "frond_sync": {
+ "client_smithholdings.com.au": {
+ "frond_note_id": "abc123",
+ "synced_at": "2026-03-13T06:15:00+11:00"
+ }
+ }
+}
+```
+
+---
+
+## Running
+
+```bash
+# Future CLI patterns:
+python3 cortex-sync.py --target frond
+python3 cortex-sync.py --target d1
+python3 cortex-sync.py --target vectorize
+python3 cortex-sync.py # all targets
+```
diff --git a/plugins/dev-tools/commands/deep-research.md b/plugins/dev-tools/commands/deep-research.md
new file mode 100644
index 00000000..a980669e
--- /dev/null
+++ b/plugins/dev-tools/commands/deep-research.md
@@ -0,0 +1,12 @@
+---
+description: Deep research and discovery before building something new
+argument-hint: "[focused|wide|deep] [topic or product idea]"
+---
+
+Load the `deep-research` skill.
+
+Parse $ARGUMENTS for:
+- **Depth**: `focused` (30 min), `wide` (1-2 hours), `deep` (3-6 hours). Default: wide
+- **Topic**: what to research
+
+Examples: `/deep-research deep obsidian replacement on cloudflare`, `/deep-research focused codemirror 6 vs prosemirror`, `/deep-research wide knowledge management tools`
diff --git a/plugins/dev-tools/skills/deep-research/SKILL.md b/plugins/dev-tools/skills/deep-research/SKILL.md
new file mode 100644
index 00000000..a81077b7
--- /dev/null
+++ b/plugins/dev-tools/skills/deep-research/SKILL.md
@@ -0,0 +1,205 @@
+---
+name: deep-research
+description: "Deep research and discovery before building something new. Explores local projects for reusable code, researches competitors, reads forums and reviews, analyses plugin ecosystems, investigates technical options, and produces a comprehensive research brief. Three depths: focused (30 min), wide (1-2 hours), deep (3-6 hours). Triggers: 'research this', 'deep research', 'discovery', 'explore the space', 'what should I build', 'competitive analysis', 'before I start building', 'research before coding'."
+compatibility: claude-code-only
+---
+
+# Deep Research
+
+Comprehensive research and discovery before building something new. Instead of jumping straight into code from training data, this skill goes wide and deep — local exploration, web research, competitor analysis, ecosystem signals, future-casting — and produces a research brief that makes the actual build 10x more productive.
+
+## Depth Levels
+
+| Depth | Duration | What it covers |
+|-------|----------|---------------|
+| **focused** | 15-30 min | Targeted research on one question. 3-5 web searches, local scan, one competitor deep-dive. 1-page brief. |
+| **wide** | 1-2 hours | Broad exploration of a product space. 10-15 searches, scan local machine, 3-5 competitors, architecture options. Multi-section brief. |
+| **deep** | 3-6 hours | Exhaustive research for a major build. Crawl competitors, read docs, explore open-source, scan all local projects, research every technical decision. Complete project brief. |
+
+Default: **wide**
+
+## Workflow
+
+### 1. Understand the Intent
+
+Ask the user:
+- **What** are you building? (one sentence)
+- **Why?** What problem does it solve? Who's it for?
+- **Constraints?** Stack preferences, budget, timeline, must-haves?
+- **Existing work?** Any projects to build on? Repos to look at?
+
+If the user gives a brief prompt ("obsidian replacement on cloudflare"), that's enough — fill in the gaps through research.
+
+### 2. Local Exploration
+
+Scan the user's machine for relevant prior work:
+
+```bash
+# Find related projects by name/keyword
+ls ~/Documents/ | grep -i "KEYWORD"
+
+# Read CLAUDE.md of related projects for architecture context
+find ~/Documents -maxdepth 2 -name "CLAUDE.md" -exec grep -l "KEYWORD" {} \;
+
+# Check for reusable patterns, schemas, components
+find ~/Documents -maxdepth 3 -name "schema.ts" -o -name "ARCHITECTURE.md" | head -20
+```
+
+For each related project found:
+- Read CLAUDE.md (stack, architecture, gotchas)
+- Check for reusable code (schemas, components, utilities, configs)
+- Note what worked well and what didn't (from git history, TODO comments)
+
+Also check:
+- Brain MCP for related client/project knowledge (if available)
+- Vault MCP for technical decisions and gotchas (if available)
+
+### 3. Web Research
+
+Search broadly to understand the space:
+
+- **Product category**: "markdown note app", "knowledge management tool for teams"
+- **Competitors**: find top 5-10 by searching "best X", "X alternatives", "X vs Y"
+- **Open source**: search GitHub for open-source alternatives, check star counts
+- **Architecture**: "how to build X", "X tech stack", "building X with [framework]"
+- **Technology docs**: check llms.txt, official docs for key technologies
+- **Platform examples**: "built with Cloudflare Workers", "D1 full-text search example"
+- **Tutorials and case studies**: "building a Y from scratch", "lessons learned building Z"
+
+### 4. Ecosystem and Community Research (wide + deep)
+
+Go beyond the core product — the ecosystem reveals what users actually need:
+
+**Plugins and add-ons**:
+- What plugins exist for major competitors? The most popular ones reveal what the core product lacks.
+- e.g. Obsidian has 1800+ plugins — the top 20 tell you what Obsidian doesn't do well natively.
+- Search: "top [product] plugins", "[product] plugin directory"
+
+**GitHub issues and feature requests**:
+- Check top competitors' GitHub repos for most-upvoted issues
+- Sort by thumbs-up reactions — this is direct user demand signal
+- Check closed issues for how features were implemented
+
+**Forum discussions**:
+- Reddit: r/[product], r/selfhosted, r/webdev, relevant niche subreddits
+- Hacker News: search for the product category
+- Discord/Discourse: product-specific communities
+- What do users love? What do they complain about? What do they wish existed?
+
+**App store and review sites**:
+- 1-star reviews = unmet needs (the product fails at this)
+- 5-star reviews = what to preserve (users love this, don't break it)
+- 3-star reviews = the interesting middle (it's okay but...)
+- Search: ProductHunt, G2, Capterra, App Store reviews
+
+**Integration requests**:
+- What systems do users want to connect to? (Zapier integrations, API requests)
+- These reveal real workflows — users duct-tape tools together
+
+### 5. Competitor Deep-Dive (wide + deep)
+
+For each major competitor (3-5 for wide, 5-10 for deep):
+
+| Question | How to research |
+|----------|----------------|
+| Features | Landing page, docs, changelog |
+| Pricing | Pricing page, comparison sites |
+| User complaints | Reddit, HN, app store reviews |
+| Tech stack | Wappalyzer, view-source, job postings, blog posts |
+| What they do well | 5-star reviews, product demos |
+| What they do poorly | 1-star reviews, forum complaints, migration guides FROM the product |
+
+### 6. Future-Casting (deep mode)
+
+Think beyond what exists today:
+
+**Platform capabilities**: What's coming to the target platform (Cloudflare, Vercel, etc.) in the next 12 months? New APIs, features, pricing changes that could unlock possibilities?
+
+**AI integration**: Not "add a chatbot" — think deeper. What's possible when the tool can read, reason about, and act on the user's data? What if every note could be searched semantically? What if the app could write its own documentation?
+
+**Device and input evolution**: Mobile-first, voice input, wearables, spatial computing. How might users interact with this in 2-5 years?
+
+**Data sources**: What new inputs could feed in? Sensors, APIs, real-time data, cross-app context?
+
+**Adjacent opportunities**: What problems sit next to this one? e.g. building a note app — adjacent: task management, project tracking, team communication. What are users duct-taping together today?
+
+**Convergence trends**: What separate tools are being unified? (Email + chat + tasks = Slack. Notes + databases + wikis = Notion. What's next?)
+
+### 7. Technical Research (deep mode)
+
+For each major architectural decision:
+
+| Decision area | Questions to answer |
+|--------------|-------------------|
+| Editor / UI framework | Options, tradeoffs, community size, our experience |
+| Database | SQL vs NoSQL vs file, managed vs self-hosted, our stack support |
+| Auth | Better-auth, Clerk, Auth.js, custom — what fits? |
+| Hosting / deployment | Cloudflare, Vercel, Railway — constraints and capabilities |
+| Search | FTS5, Elasticsearch, Meilisearch, Vectorize — what scale? |
+| Real-time | WebSockets, SSE, Durable Objects — do we need it? |
+| File storage | R2, S3, local — access patterns? |
+| API design | REST, tRPC, GraphQL — what does the use case need? |
+
+### 8. Synthesis
+
+Produce a research brief saved to `.jez/artifacts/research-brief-{topic}.md`:
+
+```markdown
+# Research Brief: [Topic]
+**Depth**: [focused|wide|deep]
+**Date**: YYYY-MM-DD
+**Research time**: [duration]
+
+## Executive Summary
+[2-3 sentences: what to build, why, key insight from research]
+
+## Competitive Landscape
+| Product | Strengths | Weaknesses | Pricing | Users |
+
+### Key Insights
+[What winners do well, what gaps exist in the market]
+
+## Ecosystem Signals
+### Most Popular Plugins/Add-ons
+[Top plugins for competitors — reveals unmet needs]
+### Most Requested Features
+[From GitHub issues, forums, reviews — sorted by demand]
+### Integration Patterns
+[What systems users connect to — reveals real workflows]
+
+## User Needs
+[What real users want, from reviews/forums/complaints]
+
+## Technical Landscape
+| Decision | Options | Recommendation | Why |
+
+## Reusable From Existing Projects
+| Project | What to reuse | Location |
+
+## Future Possibilities
+### Platform roadmap
+### AI opportunities
+### Adjacent problems
+### 2-5 year horizon
+
+## Proposed Architecture
+[Stack, data model sketch, key flows]
+
+## Risks and Open Questions
+[Things research couldn't answer]
+
+## Suggested Phases
+[Build order based on research findings]
+
+## Sources
+[Links to everything read]
+```
+
+## Tips
+
+- Start the brief early and add to it as you research — don't try to hold everything in context
+- For deep mode, use sub-agents to parallelise web research and local exploration
+- The "Reusable From Existing Projects" section often saves weeks of work
+- Ecosystem signals (plugins, issues, reviews) are often more valuable than competitor feature lists
+- Save the brief to `.jez/artifacts/` — it's useful for future sessions and for the actual build phase
+- The brief is a living document — update it as you learn more during the build
diff --git a/plugins/knowledge-cortex/.claude-plugin/plugin.json b/plugins/knowledge-cortex/.claude-plugin/plugin.json
deleted file mode 100644
index 2d13e246..00000000
--- a/plugins/knowledge-cortex/.claude-plugin/plugin.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "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/commands/cortex-mine.md b/plugins/knowledge-cortex/commands/cortex-mine.md
deleted file mode 100644
index 299c145f..00000000
--- a/plugins/knowledge-cortex/commands/cortex-mine.md
+++ /dev/null
@@ -1,12 +0,0 @@
----
-description: Mine Gmail history into a local knowledge base
-argument-hint: "[dry-run|from DATE]"
----
-
-Load the `cortex-mine` skill.
-
-Parse $ARGUMENTS:
-- `dry-run` — preview what would be extracted without saving
-- `from YYYY-MM-DD` — only process emails from this date
-
-Default: incremental mine from last run.
diff --git a/plugins/knowledge-cortex/commands/cortex-query.md b/plugins/knowledge-cortex/commands/cortex-query.md
deleted file mode 100644
index 33f9bffa..00000000
--- a/plugins/knowledge-cortex/commands/cortex-query.md
+++ /dev/null
@@ -1,8 +0,0 @@
----
-description: Search your mined knowledge base
-argument-hint: "[search-term]"
----
-
-Load the `cortex-query` skill.
-
-If $ARGUMENTS contains a search term, query for it. Otherwise show stats or ask what to search for.
diff --git a/plugins/knowledge-cortex/skills/cortex-mine/SKILL.md b/plugins/knowledge-cortex/skills/cortex-mine/SKILL.md
deleted file mode 100644
index c23a4416..00000000
--- a/plugins/knowledge-cortex/skills/cortex-mine/SKILL.md
+++ /dev/null
@@ -1,94 +0,0 @@
----
-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.
-compatibility: claude-code-only
----
-
-# 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
deleted file mode 100644
index 28a3218a..00000000
--- a/plugins/knowledge-cortex/skills/cortex-mine/references/export-adapters.md
+++ /dev/null
@@ -1,81 +0,0 @@
-# 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
deleted file mode 100644
index 797b1066..00000000
--- a/plugins/knowledge-cortex/skills/cortex-mine/references/file-schema.md
+++ /dev/null
@@ -1,108 +0,0 @@
-# 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
deleted file mode 100644
index 6041604a..00000000
--- a/plugins/knowledge-cortex/skills/cortex-mine/references/prefilter-patterns.md
+++ /dev/null
@@ -1,72 +0,0 @@
-# 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
deleted file mode 100644
index 19f5be4f..00000000
--- a/plugins/knowledge-cortex/skills/cortex-mine/scripts/cortex-mine.py
+++ /dev/null
@@ -1,777 +0,0 @@
-#!/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
deleted file mode 100644
index 7f4c3ee2..00000000
--- a/plugins/knowledge-cortex/skills/cortex-query/SKILL.md
+++ /dev/null
@@ -1,54 +0,0 @@
----
-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.
-compatibility: claude-code-only
----
-
-# 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
deleted file mode 100644
index 797b1066..00000000
--- a/plugins/knowledge-cortex/skills/cortex-query/references/file-schema.md
+++ /dev/null
@@ -1,108 +0,0 @@
-# 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
deleted file mode 100644
index 47ca2879..00000000
--- a/plugins/knowledge-cortex/skills/cortex-query/scripts/cortex-query.py
+++ /dev/null
@@ -1,382 +0,0 @@
-#!/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()