Metadata-Version: 2.4
Name: gnosion
Version: 0.9.0
Summary: Gnosion — a portable, self-improving cognitive engine: pluggable cognition heads (vision/text/design/tabular/memory) that learn from every input, exportable as a single .gnosion file and importable into any project.
Author: Crave Asia / IPG
License: MIT
Project-URL: Homepage, https://github.com/craveasia/gnosion
Keywords: machine-learning,embeddings,self-learning,memory,portable-model,brain
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: embed
Requires-Dist: fastembed>=0.4; extra == "embed"
Provides-Extra: ml
Requires-Dist: numpy>=1.23; extra == "ml"
Requires-Dist: scikit-learn>=1.2; extra == "ml"
Provides-Extra: data
Requires-Dist: pandas>=1.5; extra == "data"
Requires-Dist: matplotlib>=3.6; extra == "data"
Requires-Dist: openpyxl>=3.1; extra == "data"
Provides-Extra: media
Requires-Dist: pillow>=9; extra == "media"
Requires-Dist: imageio>=2.28; extra == "media"
Requires-Dist: imageio-ffmpeg>=0.4; extra == "media"
Provides-Extra: audio
Requires-Dist: faster-whisper>=1.0; extra == "audio"
Provides-Extra: report
Requires-Dist: fpdf2>=2.7; extra == "report"
Provides-Extra: all
Requires-Dist: fastembed>=0.4; extra == "all"
Requires-Dist: numpy>=1.23; extra == "all"
Requires-Dist: scikit-learn>=1.2; extra == "all"
Requires-Dist: pandas>=1.5; extra == "all"
Requires-Dist: matplotlib>=3.6; extra == "all"
Requires-Dist: openpyxl>=3.1; extra == "all"
Requires-Dist: pillow>=9; extra == "all"
Requires-Dist: imageio>=2.28; extra == "all"
Requires-Dist: imageio-ffmpeg>=0.4; extra == "all"
Requires-Dist: faster-whisper>=1.0; extra == "all"
Requires-Dist: fpdf2>=2.7; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Dynamic: license-file

<div align="center">

# 🧠 Gnosion

**A portable, self-improving cognitive engine — and a universal memory for any coding agent.**

*Learns from every input · exports to one file · imports anywhere · zero required dependencies.*

`pip install gnosion` &nbsp;·&nbsp; `npm i -g gnosion` &nbsp;·&nbsp; MIT

</div>

---

Gnosion is a small, honest brain you can drop into anything: a product, a data
pipeline, or your coding workflow. It holds several **cognition domains** (vision,
text, design, tabular, memory) that each learn their own way, guards them so they
never regress or memorise junk, and packs the whole thing into a single portable
`.gnosion` file you can move between projects and machines.

It also doubles as a **shared project memory for coding agents** — Claude Code,
Cursor, Windsurf, Cline, Aider, Zed, or your own scripts — via a CLI and an MCP
server, so agents stop re-deriving your decisions, drifting from your structure, or
repeating fixed bugs.

- 🪶 **Zero required dependencies.** Pure-Python core — installs and runs anywhere,
  no PyTorch, no build step.
- 📈 **Gets smarter on every input.** Each `learn()` improves the right domain;
  memory recalls from a *single* example.
- 📦 **Portable.** `export()` → one `.gnosion`. `load()` it anywhere. Ship it in git.
- 🔌 **Fully flexible.** Add your own domains and swap in your own embedder in a line.
- 🤝 **Universal agent memory.** One CLI + one MCP server, shared across every agent.
- 🫱 **Honest.** Lightweight ML (nearest-centroid + k-NN over embeddings) — no magic,
  no black box. Optional extras add real semantic quality.
- 🕸️ **Visual & interactive.** `gns ui` opens a drag/zoom/spin **neuro-graph** of
  everything the brain knows, with views for knowledge, projects, and chat — feed it,
  map a project, and export a handoff right from the browser. See [the dashboard](#the-interactive-dashboard-gns-ui).
- 🍽️ **Feeds on anything.** `gns feed` learns from `.md` files, folders, or web pages
  (with optional crawl) into named knowledge domains (marketing, SEO, DevOps…).
- 🧩 **Reasons without an LLM.** `gns reason` blends A + B → emergent C, does analogies,
  spreading activation, and link prediction — explainable, offline. See [Reasoning](#reasoning--no-llm-required-gns-reason).

## How it works (one glance)

Every input is embedded to a vector, routed to the domain's head, and folded into one
portable file. Nothing else to run.

```mermaid
flowchart LR
  IN["input<br/>text · image · numbers"] --> EMB["embedder<br/>hashing (0-dep) or fastembed (semantic)"]
  EMB --> H{"domain head"}
  H -->|classifier| C["nearest-centroid + optional logreg<br/>champion / challenger — never regresses"]
  H -->|memory| M["k-NN cosine recall<br/>learns from ONE example · reinforces on hit"]
  C --> F[("one .gnosion file<br/>portable · git-committable")]
  M --> F
  F -.load anywhere.-> IN
```

## Install

```bash
pip install gnosion                 # Python, zero deps
pip install "gnosion[embed]"        # + fastembed (ONNX MiniLM/CLIP) → semantic quality
pip install "gnosion[ml]"           # + numpy / scikit-learn acceleration

npm i -g gnosion                    # Node wrapper (bundles the Python core; needs Python 3.9+)
```

**Automatic quality upgrades — zero code changes.** Install an extra and Gnosion just
gets better on its own:
- `gnosion[ml]` → classifiers automatically use a **calibrated logistic regression**
  (falls back to nearest-centroid otherwise). The `.gnosion` stays plain JSON — the
  model is re-fit from the stored samples, never pickled.
- `gnosion[embed]` → embeddings become **semantic** (fastembed ONNX MiniLM/CLIP, no
  torch) so paraphrases and visually-similar images match. Opt out with
  `GNOSION_NO_FASTEMBED=1`. A brain records which embedder it used, so it reloads
  consistently.

## Quickstart (Python)

```python
from gnosion import Gnosion

bx = Gnosion()                                    # 5 default cognition domains

# classify — teach with labels, then predict
bx.learn("text", "how do I reset my password", label="account")
bx.learn("text", "what are your opening hours", label="hours")
bx.train("text")
bx.predict("text", "i forgot my password")       # {'label': 'account', 'confidence': 0.83}

# remember facts / conventions — memory learns from ONE example
bx.remember("design", "auth pattern",
            "Use a JWT in an httpOnly cookie; the refresh token rotates.")
bx.recall("design", "auth pattern")               # {'value': '...', 'similarity': 1.0}

# vision (image bytes) and tabular (feature vectors) work the same way
bx.learn("vision", open("leak.jpg", "rb").read(), label="plumbing")
bx.learn("tabular", [500000, 0.1, 4.0, 30], label="affordable")

# one portable file → import anywhere
bx.export("company.gnosion")
same_brain = Gnosion.load("company.gnosion")
```

## The 5 default cognition domains ("neurons")

| Domain    | Head        | Input           | What it does |
|-----------|-------------|-----------------|--------------|
| `vision`  | classifier  | image bytes     | what kind of thing is in the picture |
| `text`    | classifier  | text            | intent / category of a message |
| `design`  | memory      | text            | system-design & structure conventions (recall) |
| `tabular` | classifier  | list of numbers | outcome from numeric features |
| `memory`  | memory      | text            | general knowledge recall (from 1 example) |

```mermaid
flowchart TB
  G(("🧠 Gnosion")) --> V["vision<br/><i>classifier · image</i>"]
  G --> T["text<br/><i>classifier · text</i>"]
  G --> D["design<br/><i>memory · text</i>"]
  G --> B["tabular<br/><i>classifier · numbers</i>"]
  G --> M["memory<br/><i>memory · text</i>"]
```

Add your own: `bx.add_domain("sentiment", head="classifier", modality="text")`.

## Universal coding-agent memory 🤝

A full **agent-memory model** any agent can read and write — persisted to
`./.gnosion/project.gnosion` in the repo. It covers the standard agent-memory types:

| Type | Holds |
|---|---|
| `fact` | world / semantic facts |
| `entity` | facts **about** the user / project / environment / team / domain |
| `experience` | **episodic** — "did X → got Y" events (experience tracking) |
| `observation` | raw things noticed in the environment |
| `skill` | **procedural**, user-addable how-to procedures the agent recalls & follows |
| `decision · convention · structure · bug · preference` | how / why you work |

**CLI** (any agent can shell out to this):
```bash
gns note "The user prefers concise plain-text replies" --kind entity --subject user
gns note "We use JWT in an httpOnly cookie; refresh rotates" --kind decision
gns experience "used dedup reuse for repeat photos" --outcome "served stale label; now re-runs"
gns observe "the vision model classifies category only, not sub-category"
gns skill "deploy" --when "shipping a change" --how "git pull; docker compose up -d --build"
gns ask    "how do we do auth"        # recall relevant memories (any type)
gns skills                            # list learned skills
gns brief                             # session-start briefing (facts, decisions, skills)
gns mem                               # counts by type
```

**MCP** — one config, works across MCP-capable agents (Claude Code, Cursor, Windsurf,
Cline, Zed, …). They all share the same repo `.gnosion`, so memory carries across
agents *and* sessions:
```jsonc
{ "mcpServers": { "gnosion": { "command": "gns", "args": ["mcp"] } } }
```
Tools exposed: **remember · recall · record_experience · observe · add_skill ·
recall_skill · briefing · stats**. (Pure stdlib JSON-RPC over stdio — no SDK needed.)

**Python:**
```python
from gnosion.agent import AgentMemory
mem = AgentMemory(root=".")
mem.about("user", "prefers concise plain-text answers")        # entity fact
mem.experience("tried X", outcome="failed because Y")           # episodic
mem.observe("CI is flaky on the payments module")               # observation
mem.add_skill("deploy", when_to_use="shipping a change",
              how="git pull; docker compose up -d --build")     # user-added skill
mem.recall_skill("how do I ship this")                           # -> the deploy skill
mem.recall("how do we do auth")                                  # across all types
print(mem.briefing())
```

> Recall matches shared **words** out of the box (zero-dep). For **semantic**
> paraphrase recall, `pip install "gnosion[embed]"` and set `GNOSION_SEMANTIC=1`
> (or `AgentMemory(semantic=True)`) — then it uses fastembed (ONNX MiniLM, no torch).

## The walking brain 🚶

Gnosion is *portable*, so it goes with you. Every time an `AgentMemory` saves, it
records the project into a global registry at `~/.gnosion/registry.json` — so one brain
remembers **every project it has entered** and what it learned in each. `gns ui` reads
that registry to show the whole picture.

```mermaid
flowchart LR
  PA["project A<br/>.gnosion"] --> R
  PB["project B<br/>.gnosion"] --> R
  PC["project C<br/>.gnosion"] --> R
  R["~/.gnosion registry<br/><i>what learned where</i>"] --> UI["gns ui<br/>🕸️ neuro-graph"]
```

## The interactive dashboard (`gns ui`)

```bash
gns ui                    # dashboard for THIS repo's ./.gnosion/project.gnosion
gns ui company.gnosion    # dashboard for any explicit .gnosion file
gns ui --port 9000        # pick a port (auto-finds a free one otherwise)
```

Opens a **local, self-contained, interactive dashboard** (pure stdlib server — no deps,
no CDN, no internet). The main canvas is a **live force-directed neuro-graph** you can
**drag, zoom (scroll), pan (drag background), and spin** (orbit toggle); double-click any
neuron for details. The left rail switches **views**:

| View | Shows |
|---|---|
| **Neuro** | *every* neuron the brain has learned — the whole mind, clustered by similarity (dot = neuron, edge = similarity, size = how often recalled) |
| **Coding Agent** | the project **knowledge graph** — files, functions, classes & concepts as typed nodes; imports/calls/references as edges; detected stack — with one-click **handoff.md** export |
| **Chat / Training** | the conversational brain (`text` · `design` · `memory`) + its clusters |
| ***\<domain>*** | one nav **per fed knowledge domain** (marketing, seo, devops…) — **appears automatically** as the brain learns |

Long lists are collapsed to the first 5 with a **"see all N →"** modal (searchable), so a
big brain stays readable. The sidebar also lists every **project** the walking brain has
entered (click to switch), and live stats. You can **feed knowledge** (paste text / a URL,
optional crawl) and **re-scan / export a handoff** right from the toolbar.

```mermaid
flowchart LR
  subgraph UI["gns ui  ·  one canvas, many views"]
    N["🧠 Neuro<br/>all knowledge"]
    C["💻 Coding Agent<br/>files + imports + stack"]
    T["💬 Chat / Training<br/>text · design · memory"]
    K["📈 marketing / seo / devops…<br/>auto-appear per fed domain"]
  end
  BRAIN[(".gnosion")] --> UI
  UI -->|"+ Feed"| BRAIN
  C -->|"⬇ handoff.md"| AGENT["Claude · Codex · Cursor"]
```

> Run `gns ui` locally to see it — the graph animates and is fully interactive. (The repo
> ships no PNGs; the diagram above is the layout.)

## Feed it knowledge (`gns feed`)

Gnosion learns anything you point it at, into a **named knowledge domain** (which then
becomes its own nav + cluster in the UI, and is searchable via `gns ask`). Pure stdlib.

```bash
gns feed notes.md --domain marketing              # a markdown/text file → chunked
gns feed ./kb --domain seo                         # a whole folder (.md/.txt/.rst)
gns feed https://site.com/post --domain dev        # one web page (HTML → text)
gns feed https://docs.x.io --crawl --depth 1 --max 20 --domain dev   # a small doc site
gns feed --text "SEO: titles drive CTR" --domain seo                  # a raw paste
```

**Which source should I use?**

| Source | Best for | Notes |
|---|---|---|
| **`.md` / `.txt` files** ✅ | curated knowledge you control | highest signal — chunked by heading/paragraph. Feed a whole folder at once. |
| **A single URL** | one research page / article | static HTML only (no JS rendering); tags stripped to text. |
| **`--crawl`** | a small doc site | follows **same-host** links up to `--depth`/`--max`, one request at a time. |
| **`--text`** | a quick paste | no file needed. |

> Chunks are matched by shared **words** by default. Install `gnosion[embed]` +
> `GNOSION_SEMANTIC=1` for **semantic** recall (paraphrases match). This is how a domain
> like *marketing*, *SEO*, *DevOps*, or *PyTorch recipes* becomes a first-class part of
> the brain.

## Map anything into a knowledge graph (`gns mapping`)

`gns mapping` turns a directory — a codebase, a docs folder, *any* tree of files — into a
real **knowledge graph the brain stores and traverses**, so you can ask *"what connects X
to Y?"* instead of grepping. (Inspired by [Graphify](https://github.com/Graphify-Labs/graphify),
kept pure-Python, zero-dep, and general.)

```bash
gns mapping .                       # build / refresh the map for a directory
gns mapping query "auth database"   # a scoped subgraph around matching nodes
gns mapping path "login" "DatabasePool"   # shortest path between two things
gns mapping explain "UserService"   # a node + everything it connects to
```

**The model — a graph you traverse, not embeddings:**

| | Kinds |
|---|---|
| **Nodes** | `dir` · `file` · `function` · `class` · `module` · `route` · `concept` (doc headings) |
| **Edges** | `contains` · `defines` · `imports` · `inherits` · `calls` · `references` |

Each edge is tagged `EXTRACTED` (explicit in source) or `INFERRED` (resolved by analysis).
Python is parsed with `ast` (functions, classes, methods, imports, calls, inheritance,
routes); JS/TS via light regex; Markdown headings become `concept` nodes and `[[wikilinks]]`
become `references`. The graph persists to `.gnosion/graph.json` (reusable, no re-parsing),
and file/symbol notes also land in the brain's `structure` memory so `gns ask` still works.

```text
$ gns mapping path "login" "DatabasePool"
{ "from": "login_route", "to": "DatabasePool",
  "path": ["login_route", "UserService.login", "DatabasePool"], "hops": 2 }
```

Because it's general, the *same* command maps a docs vault or a mixed folder — you get a
graph of concepts and references, not just code.

## Hand a project to a coding agent (`gns handoff`)

```bash
gns handoff -o PROJECT.md # ONE markdown: stack + file tree + per-file defs/routes/imports + memory briefing
gns handoff --as-claude   # write it as ./CLAUDE.md
gns handoff --as-agents   # write it as ./AGENTS.md
```

`handoff` turns the map — plus what the brain has learned about the project — into **one
file a coding agent reads instead of crawling every source file**, saving tokens.

Two ways to plug it into an agent:

```mermaid
flowchart LR
  P["your project"] -->|gns mapping| B[(".gnosion<br/>graph.json")]
  B -->|gns handoff| MD["PROJECT.md / CLAUDE.md<br/><i>one-shot cheap context</i>"]
  B -->|gns mcp| MCP["MCP server<br/><i>live recall + traversal</i>"]
  MD --> A["Claude · Codex · Cursor"]
  MCP --> A
```

- **Static** — `gns handoff` → a single `.md` the agent loads once (cheap, offline).
- **Live** — the MCP server *is* the pluggable install: `claude mcp add gnosion -- gns mcp`;
  the agent then calls `recall` / `briefing` on demand across every session.

## Reasoning — no LLM required (`gns reason`)

gnosion doesn't just *recall* — it **reasons**, using classic pre-LLM cognitive methods
over its own embeddings + knowledge graph. Give it A and B and it can produce **C** — an
emergent concept, analogy, or association that is *not* A or B — and **every answer is
explainable** (traceable to the vectors / graph, not a black box).

```bash
gns reason "how do titles and conversion relate"   # blend + spread + recall → insight (written back)
gns reason analogy click rate conversion           # B − A + C → D (word2vec-style)
gns reason relate auth database                     # why they connect: similarity + graph path
gns reason spread seo conversion                    # spreading activation from seeds
gns reason links                                    # predict connections that should exist
gns reason --status                                 # engine info (no LLM)
```

| Method | Origin | Produces |
|---|---|---|
| **blend** | word2vec | compose vectors of A + B → nearest neuron that isn't an input = **emergent C** |
| **analogy** | word2vec | `B − A + C → D` |
| **relate** | graph traversal | *why* A relates to B (path + shared neighbours + similarity) |
| **spread** | Collins & Loftus, 1975 | what all seeds light up (associative insight) |
| **infer_links** | Adamic-Adar | connections that *should* exist but don't yet |

Each `gns reason "…"` writes its conclusion back as an `insight` memory — so the brain
**compounds**: next time, the new insight is part of what it blends. Text works zero-dep;
image / cross-modal reasoning uses CLIP embeddings (`pip install "gnosion[embed]"`), same
calls. This is the **"walking brain"** — associative, self-expanding, and glass-box.

> Not an LLM: it returns *structured, explainable insight* (ranked concepts, analogies,
> predicted links) — not fluent prose. That's the trade for offline, zero-dep, and
> traceable. An LLM reasoning head can be added later as an optional extra; it isn't
> required for reasoning.

## Plugins — extend it to do anything (`gns plugins`)

Capabilities are **plugins**. One class declares its actions + a `run()`; it then appears
everywhere automatically — `gns plugins`, `gns run`, and a **UI nav + panel** (upload /
buttons / table / chart) with *no per-plugin UI code*. Adding a new power = one file.

| Plugin | Does | Deps |
|---|---|---|
| **data** | CSV/Excel/TXT: profile · sort · pivot · correlation · chart | stdlib; `gnosion[data]` for pivot/chart/excel |
| **media** | images: learn · classify · similar · describe; video scenes | stdlib; `gnosion[embed]`/`[media]` |
| **web** | fetch / crawl (robots-legal) → learn → reason | stdlib |
| **finance** | loan · compound · roi/cagr · npv · irr · break-even | stdlib |
| **tabular** | regress · forecast (linear/ma/holt/seasonal) · trend | stdlib |
| **audio** | WAV info; transcribe → learn | stdlib; `gnosion[audio]` |
| **report** | whole-brain snapshot → Markdown / PDF | stdlib; `gnosion[report]` |
| **lang** | detect language of text | stdlib |
| **calendar** | parse `.ics` → events → learn | stdlib |
| **geo** | great-circle distance + bearing | stdlib |
| **code** | run a trusted Python snippet (subprocess, timed) | stdlib |
| **email** | parse `.eml`; send via SMTP (env creds) | stdlib |

> **`code` is not a security sandbox** — it isolates and times out, but doesn't block fs/net.
> Run only code you trust. **`email send`** goes out under *your* account and reads creds from
> `GNOSION_SMTP_*` env only (use an app-password; never commit it).

### Data analysis (first plugin) — `gns data` / the "Data Analysis" tool

Upload a CSV / Excel / TXT and analyse it, storing insights back into the brain:

```bash
gns data profile sales.csv                 # rows/cols, dtypes, missing, numeric summary
gns data preview sales.csv --n 20
gns data sort sales.csv --by sales --desc
gns data pivot sales.csv --index region --columns month --values sales --agg sum
gns data correlation sales.csv
gns data chart sales.csv --x month --y sales --kind line   # saves data-chart.png
```

- **profile · preview · sort** work in **pure stdlib** (zero deps).
- **pivot · correlation · chart · Excel** need `pip install "gnosion[data]"` (pandas +
  matplotlib + openpyxl). The CLI/UI tells you when an action needs it.
- In `gns ui` → **Tools → Data Analysis**: drop in a file, click Profile / Pivot / Chart —
  tables and charts render right there. Every profile writes an `observation` insight, so
  the brain remembers your datasets.

Flow: **CSV/Excel/TXT → data plugin → table · pivot · correlation · chart → insight saved to brain.**

### Media (image / video) — `gns media` / the "Media" tool

```bash
gns media learn photo.jpg --label "leak"      # teach an image
gns media classify unknown.jpg                 # nearest learned label
gns media similar query.jpg --k 5              # most similar learned images
gns media describe photo.jpg                   # size/format/colour (Pillow) + closest match
gns media video clip.mp4 --every 15            # scene changes (needs gnosion[media])
```

Learn / classify / similar work **zero-dep** (byte-level image similarity). Install
`gnosion[embed]` for **CLIP** → real visual/semantic similarity and text↔image reasoning;
`gnosion[media]` (Pillow + imageio) adds image details and video scene detection.

### Consolidate — the brain's "sleep" (`gns consolidate`)

```bash
gns consolidate            # merge near-duplicate memories, fold recall counts together
gns consolidate --sim 0.95 # merge more aggressively
```

Keeps the brain lean as it grows so recall and reasoning stay sharp. Also a one-click
**Consolidate** button in `gns ui`.

### More plugins — web · finance · tabular ML

```bash
gns run web research --text "https://docs.example.com" --set domain=dev   # fetch (robots-legal) → learn → reason
gns run web crawl    --text "https://docs.example.com" --set depth=1 --set max=10

gns run finance loan --set principal=100000 --set rate=5 --set years=30   # → 536.82/mo
gns run finance roi  --set initial=100 --set final=150 --set years=2      # ROI + CAGR
gns run finance npv  --set rate=8 --set cashflows=-1000,300,300,300,300   # also: irr, compound, breakeven

gns run tabular regress  sales.csv --set x=month_num --set y=sales --set predict=13
gns run tabular forecast sales.csv --set y=sales --set periods=6
```

- **web** — checks `robots.txt` and stays on-host, depth/count-capped (legal by default).
- **finance** — pure-math calculators; results saved as insights.
- **tabular** — pure least-squares regression / forecast / trend.

All three also appear in `gns ui` → **Tools**, with the right inputs auto-rendered (a URL
box for web, parameter fields for finance, file upload for tabular).

### Forecasting · audio · report · scheduler

```bash
gns run tabular forecast sales.csv --set y=sales --set periods=6 --set method=holt   # linear|ma|holt|seasonal
gns run audio transcribe talk.mp3 --set domain=meetings   # speech → learned (gnosion[audio])
gns run report markdown                                    # whole-brain snapshot → brain-report.md
gns run report pdf                                         # → brain-report.pdf (gnosion[report])
gns schedule consolidate --every 3600                     # routine upkeep loop (or --once)
gns schedule both --every 86400                           # consolidate + re-map daily
```

- **forecast** methods: `linear`, `ma` (moving average), `holt` (level+trend), `seasonal`.
- **audio**: `info` (WAV, zero-dep) + `transcribe` (`gnosion[audio]`, offline whisper).
- **report**: Markdown (zero-dep) or PDF (`gnosion[report]`).
- **scheduler**: foreground interval loop; for unattended use OS cron / Task Scheduler.

### Language detection · geo · calendar · chaining

```bash
gns lang "saya nak makan nasi lemak"          # → {"lang":"ms","name":"Malay",...}
gns run geo distance --set lat1=3.139 --set lon1=101.687 --set lat2=1.352 --set lon2=103.82
gns run calendar events schedule.ics          # parse .ics → events table
gns chain "web:research+report:markdown" --text https://docs.example.com   # pipe plugins
```

**Chatbot tip:** `reason("…")` returns a `language` field, so you detect the user's language
and reply accordingly — e.g. English in, English out; Malay in, Malay out. (gnosion serves
recall + detection; fluent prose in that language still comes from your reply layer / an LLM.)
Detects en/es/fr/de/it/pt/nl/ms/id and zh/ja/ko/ru/ar/th/hi/he/el.

## Use cases

One brain, many jobs — it is deliberately **universal**:

- **Give a product its own brain** — classify images/text on-device ($0, offline),
  learning from user confirmations; ship the trained brain as one file.
- **A domain-expert brain** — `gns feed` marketing, SEO, DevOps, legal, or product docs
  into named domains; the brain becomes a queryable expert you can commit and share.
- **Coding-agent context** — `mapping` + `handoff` hand any agent a whole project in one
  file (or a traversable graph); MCP gives it live recall. Less token burn, less drift.
- **Agent memory across sessions & tools** — capture decisions/conventions/bug-fixes
  once; every future agent session recalls them.
- **An ML side-brain / pipeline component** — use it inside a PyTorch or vision pipeline
  as a fast nearest-centroid classifier or a k-NN memory cache: log good predictions,
  recall them next time, or bootstrap labels before a heavy model is trained. Swap in
  your own embedder (`.embed(x) -> vector`) and it rides on your existing features.
- **A learning layer over LLMs** — remember the good answers an LLM gave; serve them
  locally next time (faster, cheaper, consistent).
- **Edge / CPU classification** — vision/text/tabular classifiers, no GPU, no framework.

## Flexibility

- **Custom domains:** `bx.add_domain(name, head="classifier"|"memory", modality="text"|"image"|"vector")`.
- **Custom embedder:** any object with `.embed(x) -> list[float]` and a stable `.dim`
  — plug in your own model, or `pip install "gnosion[embed]"` for fastembed.
- **Custom heads:** `ClassifierHead` / `MemoryHead` are plain classes with
  `to_dict()`/`from_dict()`; extend them and register in `HEAD_TYPES`.
- **Portable format:** the `.gnosion` is a zip (`manifest.json` + gzipped brain) — you
  can inspect, diff, or generate it yourself.

## How it learns (and won't get worse)

- **Classifier heads** keep every labelled example and fit a per-label centroid over
  embeddings. `train()` carves a **stable golden holdout**, scores a challenger, and
  **only promotes it if it doesn't regress** — champion/challenger.
- **Memory heads** store `(embedding → value)` and answer by nearest-neighbour cosine
  above a confidence threshold — so paraphrases recall the right value and unrelated
  queries recall *nothing* (no confident-but-wrong answers).

## API at a glance

```python
Gnosion(dim=256, prefer_fastembed=False, domains=None)
  .learn(domain, x, label=None, value=None)   .remember(domain, cue, value)   .absorb(domain, q, a)
  .train(domain=None)   .predict(domain, x)   .recall(domain, q, min_sim=None)   .search(domain, q, k=5)
  .add_domain(name, head, modality)   .stats()   .export(path)   Gnosion.load(path)
```

## CLI reference

```bash
gns note|ask|brief|mem                 # universal repo memory (./.gnosion/project.gnosion)
gns observe|experience|skill|skills    # episodic / procedural memory
gns reason "question"                  # PURE reasoning (no LLM): blend/analogy/relate/spread/links
gns plugins                            # list capability plugins (data analysis, …)
gns data profile|sort|pivot|chart <file>   # data analysis (stdlib + gnosion[data])
gns feed <file|dir|url> --domain X     # teach new knowledge (--text, --crawl, --depth, --max)
gns mapping [path]                     # build a knowledge graph of a directory
gns mapping query|path|explain ...     # traverse it instead of grepping
gns handoff [--as-claude|--as-agents|-o F.md]   # export a single project map for coding agents
gns ui [file.gnosion] [--port N]       # 🕸️ interactive dashboard (local, 0-dep)
gns mcp                                # run the MCP server (stdio) for agents
gns learn|train|predict|recall <file.gnosion> <domain> <text> [--label/--value]
gns inspect|stats <file.gnosion>        # peek / full stats
```

## Expand & scale it bigger

Gnosion is small on purpose, so growth is just composition:

- **More brainpower per domain** — install `gnosion[embed]` for semantic embeddings and
  `gnosion[ml]` for calibrated logistic-regression classifiers. Zero code changes; the
  `.gnosion` stays plain JSON (models are re-fit from stored samples, never pickled).
- **More domains** — `bx.add_domain(name, head, modality)` or just `gns feed --domain new`.
  Every domain is independent, so the brain scales sideways without retraining others.
- **Bigger embedder** — point a domain at any model exposing `.embed(x) -> list[float]`
  and a stable `.dim` (OpenAI embeddings, your own CLIP, a fine-tuned encoder). The graph,
  recall, and champion/challenger guard all keep working.
- **Many brains, one mind** — keep a per-repo `.gnosion` (committed) and let the
  `~/.gnosion` registry aggregate them; `gns ui` shows all projects and lets you switch.
- **Custom heads** — subclass `ClassifierHead` / `MemoryHead` (they're plain
  `to_dict()`/`from_dict()` classes) and register in `HEAD_TYPES` for new learning rules.
- **Sharding** — split by domain into separate `.gnosion` files and load the one you need;
  each file is a self-contained zip you can diff, cache, or generate.

## What Gnosion is — and isn't

It **is** a practical, portable, always-improving memory + classifier you can embed
anywhere. It **is not** a replacement for a large language model, and importing a
`.gnosion` will not magically make an LLM bug-free — it *augments* by remembering what
worked and classifying what it has seen, so systems drift less and repeat fewer
mistakes.

## Learn more

- **[`RESEARCH.md`](RESEARCH.md)** — how the brain works: structure + every reasoning method
  explained simply *and* with the math + Mermaid diagrams. Learn along the way.
- **[`USAGE.md`](USAGE.md)** — a full how-to: install → app brain → project memory →
  coding agents (MCP) → AI agents → embedding in a system → Node/JS → sharing a brain.
- **[`PUBLISHING.md`](PUBLISHING.md)** — the exact GitHub / PyPI / npm steps.

MIT © Crave Asia / IPG
