### Nuggets Setup Wizard Example Source: https://github.com/neovertex1/nuggets/blob/main/README.md An example of the interactive setup wizard for the Nuggets project, showing prompts for API keys and chat IDs. ```text Nuggets Setup Wizard ==================== ── AI Provider ────────────────────────────────────── Note: Anthropic Max plan does NOT work (third-party OAuth was blocked Jan 2026). You need an API key from: https://console.anthropic.com/ Paste your sk-ant-... key: Anthropic API key: sk-ant-api03-... ── Telegram ───────────────────────────────────────── Create a bot via @BotFather on Telegram, paste the token: Bot token: 123456789:AAF... Send /start to @userinfobot on Telegram to get your chat ID: Chat ID: 987654321 ── WhatsApp (optional) ────────────────────────────── Your JID (e.g. 1234567890@s.whatsapp.net) — press Enter to skip: WhatsApp JID: ── Pi Model (optional) ────────────────────────────── Model ID (press Enter for Pi's default): Model: ✓ .env written successfully. Ready! Run `npm run dev` to start. ``` -------------------------------- ### Nuggets Project Quick Start Source: https://github.com/neovertex1/nuggets/blob/main/README.md Clone the Nuggets repository, install dependencies, and run the setup and development commands. ```bash npm install -g @mariozechner/pi-coding-agent # install Pi (if not already) git clone https://github.com/NeoVertex1/nuggets.git cd nuggets npm install npm run setup npm run dev ``` -------------------------------- ### Pi Agent Quick Start Commands Source: https://context7.com/neovertex1/nuggets/llms.txt Commands to install the Pi agent, clone the repository, set up the environment, and start the gateway. The `npm run setup` command runs an interactive wizard. ```bash npm install -g @mariozechner/pi-coding-agent # install Pi agent git clone https://github.com/NeoVertex1/nuggets.git cd nuggets npm install npm run setup # interactive wizard: writes .env, validates credentials npm run dev # start gateway (Telegram + WhatsApp) ``` -------------------------------- ### Example: Remembering User Preferences Source: https://github.com/neovertex1/nuggets/blob/main/CLAUDE.md Demonstrates caching personal configuration or style preferences. Keep the stored values brief. ```bash nuggets remember prefs "style" "2-space indent, no semicolons" ``` -------------------------------- ### Install Pi Coding Agent Source: https://github.com/neovertex1/nuggets/blob/main/README.md Install the Pi coding agent globally using npm. This is a prerequisite for the project. ```bash npm install -g @mariozechner/pi-coding-agent ``` -------------------------------- ### Example: Remembering Patterns Source: https://github.com/neovertex1/nuggets/blob/main/CLAUDE.md Illustrates storing a description of a code pattern or concept. Values should be short and descriptive. ```bash nuggets remember project "error handling" "uses Result type, never throws" ``` -------------------------------- ### Example: Remembering Commands Source: https://github.com/neovertex1/nuggets/blob/main/CLAUDE.md Shows how to cache a command for later use. This is useful for frequently executed or complex commands. ```bash nuggets remember project "test cmd" "pytest tests/ -v" ``` -------------------------------- ### Install Nuggets Memory Plugin Source: https://github.com/neovertex1/nuggets/blob/main/README.md Install the Nuggets memory plugin globally for use with coding agents. This is the preferred method for faster startup speeds. ```bash npm install -g nuggets-memory-plugin ``` -------------------------------- ### Create Astro Blog Project Source: https://github.com/neovertex1/nuggets/blob/main/blog/README.md Use this command to create a new Astro project with the blog template. Ensure you have Node.js installed. ```bash npm create astro@latest -- --template blog ``` -------------------------------- ### Example: Remembering Bug Fixes Source: https://github.com/neovertex1/nuggets/blob/main/CLAUDE.md Shows how to store a note about a specific bug fix, including the context and the solution. Values should be concise. ```bash nuggets remember debug "CORS error" "add origin to allowlist in config.ts" ``` -------------------------------- ### Example: Remembering File Locations Source: https://github.com/neovertex1/nuggets/blob/main/CLAUDE.md Demonstrates how to store a specific file location associated with a descriptive key. Ensure the value is concise, ideally a sentence or less. ```bash nuggets remember locations "auth handler" "src/auth/middleware.ts:47" ``` -------------------------------- ### Schedule Extension System Prompt Injection Source: https://context7.com/neovertex1/nuggets/llms.txt This shows how the Schedule extension is automatically injected into the system prompt, providing examples of how to schedule messages and reminders. ```typescript // System prompt injection (automatic): // ## Proactive Capabilities // You can schedule future messages and reminders using the `schedule` tool. // Examples: // - "Remind me to exercise at 7am" → schedule with cron "0 7 * * *", one_shot=false // - "Check on the deployment in 30 minutes" → calculate the cron, one_shot=true ``` -------------------------------- ### Nuggets Project Architecture Overview Source: https://github.com/neovertex1/nuggets/blob/main/README.md Directory structure and main components of the Nuggets project, including memory engine, gateway, and setup. ```text src/ nuggets/ Memory engine (pure TypeScript, zero deps) core.ts HRR math: bind, unbind, orthogonalize, sharpen memory.ts Nugget class: remember, recall, forget (+ token-overlap matching) shelf.ts NuggetShelf: multi-nugget manager with kind-aware routing kinds.ts Memory kind types, auto-classification heuristics promote.ts MEMORY.md promotion (3+ recall threshold) index.ts Public API migrate-memory.ts Migration: legacy single nugget → kind-based layout gateway/ main.ts Entry point — wires everything together config.ts Environment config + helpers router.ts Message routing + proactive event handling pi-rpc.ts Pi subprocess communication (JSONL RPC) pi-pool.ts Per-user process pool with idle eviction telegram.ts Telegram bot (grammY) whatsapp.ts WhatsApp client (Baileys) event-queue.ts Proactive event bus cron.ts 5-field cron scheduler + request file watcher heartbeat.ts Per-user periodic check-ins setup.ts Interactive setup wizard .pi/extensions/ nuggets.ts Memory tool + auto-capture + system prompt injection proactive.ts Schedule tool + cron file bridge ``` -------------------------------- ### Nuggets CLI Commands Source: https://context7.com/neovertex1/nuggets/llms.txt Command-line interface commands for the Nuggets tool, used to remember, recall, and forget facts. Examples show how to store and retrieve specific information. ```bash # Store a fact nuggets remember "" "" # Examples: nuggets remember locations "auth handler" "src/auth/middleware.ts:47" nuggets remember project "test cmd" "pytest tests/ -v" nuggets remember prefs "style" "2-space indent, no semicolons" ``` ```bash # Recall (searches all nuggets by default) nuggets recall "how to run tests" nuggets recall "auth handler" --nugget locations ``` ```bash # Forget nuggets forget locations "auth handler" ``` -------------------------------- ### Nuggets Python API Usage Source: https://github.com/neovertex1/nuggets/blob/main/NUGGETS_INSTRUCTIONS.md Example of using the Nuggets Python API to create a memory, store a fact, and recall it. The recall result includes the answer and a confidence score. ```python from nuggets import Nugget n = Nugget("my_memory") n.remember("wifi_password", "test123") result = n.recall("what is the wifi password") print(result) # {answer: "test123", confidence: 0.85, ...} ``` -------------------------------- ### Migrate Legacy Memory Storage Source: https://github.com/neovertex1/nuggets/blob/main/README.md Run the migration script to split legacy single-file memory into the new kind-based layout for the holographic memory engine. ```bash npm run migrate:memory ``` -------------------------------- ### Astro Project Structure Overview Source: https://github.com/neovertex1/nuggets/blob/main/blog/README.md This is a typical file structure for an Astro project. Key directories include `public/` for static assets, `src/` for source code (components, content, layouts, pages), and configuration files like `astro.config.mjs`. ```text ├── public/ ├── src/ │   ├── components/ │   ├── content/ │   ├── layouts/ │   └── pages/ ├── astro.config.mjs ├── README.md ├── package.json └── tsconfig.json ``` -------------------------------- ### Run Tests Source: https://github.com/neovertex1/nuggets/blob/main/README.md Execute all project tests. This command is used to verify the functionality of HRR math, nugget operations, and shelf management. ```bash npm test ``` -------------------------------- ### Basic HRR Implementation in TypeScript Source: https://github.com/neovertex1/nuggets/blob/main/blog/src/content/blog/how-my-brain-works.md Illustrates the core mathematical operations for HRR, including key generation, binding, superposition, and unbinding, using complex number representations. ```typescript const D = 16384; // Generate a random phase vector (key) function generateKey(): Float64Array { const key = new Float64Array(D); for (let i = 0; i < D; i++) { const phi = Math.random() * 2 * Math.PI; key[i] = phi; } return key; } // Bind two keys (element-wise phase addition) function bind(key1: Float64Array, key2: Float64Array): Float64Array { const trace = new Float64Array(D); for (let i = 0; i < D; i++) { // Geometrically, this is adding angles: exp(iφ₁) * exp(iφ₂) = exp(i(φ₁ + φ₂)) trace[i] = key1[i] + key2[i]; } return trace; } // Superpose multiple traces (element-wise phase addition) function superpose(traces: Float64Array[]): Float64Array { const memory = new Float64Array(D).fill(0); const n = traces.length; for (const trace of traces) { for (let i = 0; i < D; i++) { memory[i] += trace[i]; } } // Scale by 1/√n to keep magnitude bounded for (let i = 0; i < D; i++) { memory[i] /= Math.sqrt(n); } return memory; } // Unbind (recall) a fact using the conjugate of the query key function unbind(memory: Float64Array, queryKey: Float64Array): Float64Array { const recovered = new Float64Array(D); for (let i = 0; i < D; i++) { // Geometrically, this is subtracting angles: exp(iφ) * exp(-iφ_q) = exp(i(φ - φ_q)) recovered[i] = memory[i] - queryKey[i]; } return recovered; } // Example Usage: const duneKey = generateKey(); const genreKey = generateKey(); const sciFiKey = generateKey(); const duneTrace = bind(genreKey, duneKey); const sciFiTrace = bind(genreKey, sciFiKey); const memory = superpose([duneTrace, sciFiTrace]); // Recall 'dune' associated with 'genre' const recalledDunePhases = unbind(memory, genreKey); // To decode 'recalledDunePhases', one would typically compute cosine similarity against known vocabulary phase vectors. // For simplicity, we'll just show the phase values. console.log("Recalled Dune Phases (first 10 dims):", recalledDunePhases.slice(0, 10)); console.log("Original Dune Key (first 10 dims):", duneKey.slice(0, 10)); ``` -------------------------------- ### Promote Hot Facts to MEMORY.md Source: https://context7.com/neovertex1/nuggets/llms.txt Scan all nuggets for facts recalled 3+ times across sessions and promote them to a persistent MEMORY.md file. This bridges ephemeral memory into permanent agent context. ```typescript import { NuggetShelf } from "./src/nuggets/shelf.js"; import { promoteFacts } from "./src/nuggets/promote.js"; const shelf = new NuggetShelf(); shelf.loadAll(); // Simulate recalls across 3 sessions to hit the threshold const n = shelf.getOrCreateKind("project"); n.remember("deploy-cmd", "git push origin main"); n.recall("deploy-cmd", "session-1"); n.recall("deploy-cmd", "session-2"); n.recall("deploy-cmd", "session-3"); // hits = 3 → eligible for promotion // Promote to MEMORY.md (no-op if Claude Code project dir doesn't exist) const promoted = promoteFacts(shelf); console.log(promoted); // 1 // Resulting MEMORY.md: // # Memory // Auto-promoted from nuggets (3+ recalls across sessions). // // ## project // // - **deploy-cmd**: git push origin main ``` -------------------------------- ### Astro Development Commands Source: https://github.com/neovertex1/nuggets/blob/main/blog/README.md These commands are essential for managing your Astro project. Run them from the project's root directory in your terminal. ```bash npm install ``` ```bash npm run dev ``` ```bash npm run build ``` ```bash npm run preview ``` ```bash npm run astro ... ``` ```bash npm run astro -- --help ``` -------------------------------- ### promoteFacts Function Source: https://context7.com/neovertex1/nuggets/llms.txt Scans all nuggets on the shelf and writes facts with `hits >= 3` to a `MEMORY.md` file, bridging ephemeral memory into permanent agent context. ```APIDOC ## promoteFacts Function ### Description Scans all nuggets on the shelf and writes facts with `hits >= 3` (recalled across 3+ distinct sessions) to a `MEMORY.md` file in the Claude Code project memory directory. This bridges ephemeral holographic memory into permanent agent context. The write is atomic (via a `.tmp` rename). ### Parameters - **shelf** (NuggetShelf): An instance of NuggetShelf with loaded nuggets. ### Returns - (number): The number of facts promoted to `MEMORY.md`. ### Example Usage ```typescript import { NuggetShelf } from "./src/nuggets/shelf.js"; import { promoteFacts } from "./src/nuggets/promote.js"; const shelf = new NuggetShelf(); shelf.loadAll(); // Simulate recalls to hit the threshold const n = shelf.getOrCreateKind("project"); n.remember("deploy-cmd", "git push origin main"); n.recall("deploy-cmd", "session-1"); n.recall("deploy-cmd", "session-2"); n.recall("deploy-cmd", "session-3"); const promoted = promoteFacts(shelf); console.log(promoted); // Example output: 1 ``` ``` -------------------------------- ### Environment Variables Configuration Source: https://context7.com/neovertex1/nuggets/llms.txt Configuration options for the Pi agent, including messaging channels, AI provider settings, and proactive system parameters. These are typically set in a .env file. ```bash # Copy .env.example and fill in values, or run: npm run setup # Messaging channels — configure at least one GATEWAY_ALLOWLIST=1234567890@s.whatsapp.net # WhatsApp JID(s), comma-separated TELEGRAM_BOT_TOKEN=123456789:AAF7_NRCOM2nxZt # from @BotFather TELEGRAM_ALLOWLIST=987654321 # your numeric Telegram chat ID # AI provider ANTHROPIC_API_KEY=sk-ant-api03-... PI_PROVIDER=anthropic PI_MODEL= # empty = Pi's default # Process pool PI_IDLE_TIMEOUT_MS=300000 # 5 min — evict idle Pi processes MAX_PI_PROCESSES=5 # max concurrent Pi subprocesses # Proactive system HEARTBEAT_INTERVAL_MS=1800000 # 30 min between heartbeat checks QUIET_HOURS_START=22 # 10 PM — suppress proactive messages QUIET_HOURS_END=8 # 8 AM CRON_EVAL_INTERVAL_MS=60000 # evaluate cron jobs every 1 min ``` -------------------------------- ### List Nuggets Commands Source: https://context7.com/neovertex1/nuggets/llms.txt Use these commands to manage and query nuggets. Add --json for machine-readable output. ```bash nuggets list # all nuggets and their status nuggets facts # all facts in a specific nugget nuggets status # overall memory status nuggets clear # remove all facts from a nugget ``` ```bash nuggets recall "test cmd" --json ``` -------------------------------- ### Manage Multiple Nuggets with NuggetShelf Source: https://context7.com/neovertex1/nuggets/llms.txt Use NuggetShelf to manage multiple Nugget instances, load facts, and perform broadcast recalls. It automatically infers memory kinds or accepts explicit overrides for routing facts. ```typescript import { NuggetShelf } from "./src/nuggets/shelf.js"; import { inferMemoryKind } from "./src/nuggets/kinds.js"; // Load all *.nugget.json files from ~/.nuggets/ const shelf = new NuggetShelf({ saveDir: "/home/user/.nuggets", autoSave: true }); shelf.loadAll(); // Store by kind — auto-inferred from key/value heuristics shelf.rememberKind("project", "test-cmd", "npm test"); // "project" kind shelf.rememberKind("user", "pref:indent", "2 spaces"); // "user" kind // Manual kind inference console.log(inferMemoryKind("file:auth", "src/auth/middleware.ts")); // "project" console.log(inferMemoryKind("pref:theme", "dark")); // "user" console.log(inferMemoryKind("personality", "curious")); // "agent" // Broadcast recall across all nuggets (returns highest-confidence hit) const result = shelf.recall("how to run tests"); console.log(result); // { answer: "npm test", confidence: 0.91, found: true, nugget_name: "project", ... } // Kind-ordered recall: user → project → agent priority const kindResult = shelf.recallByKind("indent preference", ["user", "project", "agent"]); console.log(kindResult); // { answer: "2 spaces", confidence: 0.87, found: true, memory_kind: "user", nugget_name: "user" } // Targeted recall in a single nugget const specific = shelf.recall("test-cmd", "project"); console.log(specific.answer); // "npm test" // Forget across all kinds shelf.forget("project", "test-cmd"); // Or by kind: shelf.forgetKind("user", "pref:indent"); // List status of all loaded nuggets console.log(shelf.list()); // [ // { name: "user", fact_count: 3, dimension: 16384, capacity_used_pct: 0.1, ... }, // { name: "project", fact_count: 12, dimension: 16384, capacity_used_pct: 0.4, ... } // ] // Save everything shelf.saveAll(); ``` -------------------------------- ### Recall Information with Nuggets CLI Source: https://github.com/neovertex1/nuggets/blob/main/CLAUDE.md Use this command to search your stored memory before performing searches with other tools. It helps avoid redundant work by retrieving previously cached information. ```bash nuggets recall "what you're looking for" ``` -------------------------------- ### Nuggets Extension System Prompt Injection Source: https://context7.com/neovertex1/nuggets/llms.txt This shows how the Nuggets extension automatically injects facts and preferences into the system prompt before each agent turn. ```typescript // System prompt injection (automatic, before each agent turn): // ## Nuggets — Persistent Memory // ### Preferences // - always:typescript: TypeScript // ### Learnings // - important-note: always check CI before merging // ### Active Files // - src/gateway/router.ts // ### Facts // - test-command: vitest run --reporter=verbose ``` -------------------------------- ### Store Information with Nuggets CLI Source: https://github.com/neovertex1/nuggets/blob/main/CLAUDE.md Cache useful information discovered during your workflow. This command automatically creates a new 'nugget' if one does not exist for the provided name. ```bash nuggets remember "" "" ``` -------------------------------- ### Create Router for Message Routing and Event Dispatch Source: https://context7.com/neovertex1/nuggets/llms.txt Use `createRouter` to unify message handling, serializing concurrent messages per JID. It handles user-initiated messages and proactive events like heartbeats and cron jobs. ```typescript import { createRouter } from "./src/gateway/router.js"; import { PiPool } from "./src/gateway/pi-pool.js"; import { EventQueue } from "./src/gateway/event-queue.js"; import { HeartbeatManager } from "./src/gateway/heartbeat.js"; const pool = new PiPool(); const eventQueue = new EventQueue(); const heartbeat = new HeartbeatManager(eventQueue); // send is typically the Telegram/WhatsApp send function let sendFn: (jid: string, text: string) => Promise; const getSend = () => sendFn; const router = createRouter(getSend, pool, eventQueue, heartbeat); // Handle an incoming user message await router("987654321@telegram", "What's the weather like?"); // → calls pool.getOrCreate, sends prompt to Pi, delivers chunked reply via sendFn // Heartbeat events are auto-dispatched by HeartbeatManager → EventQueue → router // Router calls Pi with HEARTBEAT_PROMPT; if Pi replies "NOTHING", stays silent // Proactive cron event (fired by CronScheduler) eventQueue.push({ type: "cron", jid: "987654321@telegram", prompt: "Send the user their daily summary", metadata: { cronJobId: "abc12345" }, }); // → router picks it up and dispatches to Pi, delivers reply ``` -------------------------------- ### Infer Memory Kind with Heuristics Source: https://context7.com/neovertex1/nuggets/llms.txt Automatically classify key-value pairs into 'user', 'project', or 'agent' memory kinds using prefix and keyword heuristics. This is used to route facts without explicit kind overrides. ```typescript import { inferMemoryKind, type MemoryKind } from "./src/nuggets/kinds.js"; // "user" kind — personal preferences and corrections inferMemoryKind("pref:style", "2-space indent"); // "user" inferMemoryKind("likes-dark-mode", "yes"); // "user" inferMemoryKind("user-name", "Alice"); // "user" inferMemoryKind("learn:important", "always check test output"); // "user" // "project" kind — repo/file/command context inferMemoryKind("file:router", "src/gateway/router.ts"); // "project" inferMemoryKind("cmd:test", "vitest run"); // "project" inferMemoryKind("edited:config", "src/config.ts"); // "project" inferMemoryKind("repo-url", "github.com/user/app"); // "project" inferMemoryKind("_task", "refactor auth module"); // "project" // "agent" kind — fallback for anything else inferMemoryKind("personality-trait", "curious"); // "agent" inferMemoryKind("conversation-style", "concise"); // "agent" ``` -------------------------------- ### Nuggets CLI Command Reference Source: https://github.com/neovertex1/nuggets/blob/main/CLAUDE.md A reference for the core Nuggets CLI commands. These commands allow for storing, retrieving, and managing information within your persistent memory. ```bash nuggets remember # Store (auto-creates nugget) ``` ```bash nuggets recall # Search all nuggets ``` ```bash nuggets recall --nugget # Search specific nugget ``` ```bash nuggets forget # Remove a fact ``` ```bash nuggets list # Show all nuggets ``` ```bash nuggets facts # Show facts in a nugget ``` -------------------------------- ### Register Nuggets Plugin with Hermes Agent Source: https://github.com/neovertex1/nuggets/blob/main/README.md Register the Nuggets memory plugin with the Hermes agent host using its native MCP command. ```bash hermes mcp add nuggets-memory --command nuggets-memory-plugin ``` -------------------------------- ### Nuggets CLI Commands Source: https://github.com/neovertex1/nuggets/blob/main/NUGGETS_INSTRUCTIONS.md Basic commands for interacting with the Nuggets memory system via the command-line interface. Use `recall` before expensive operations to check the cache. ```bash nuggets remember # Store a fact (auto-creates nugget) ``` ```bash nuggets recall [--nugget ] # Query memory (searches all nuggets by default) ``` ```bash nuggets forget # Remove a fact ``` ```bash nuggets list # List all nuggets ``` ```bash nuggets status # Overall status ``` ```bash nuggets facts # List facts in a nugget ``` ```bash nuggets clear # Clear all facts from a nugget ``` -------------------------------- ### Schedule Extension Actions Source: https://context7.com/neovertex1/nuggets/llms.txt These are the actions for the Schedule extension, allowing the Pi agent to create, delete, and list cron jobs. The LLM calls the 'schedule' tool with these parameters. ```typescript // create a recurring reminder { action: "create", cron: "0 9 * * *", // daily at 9 AM message: "Send morning standup reminder", one_shot: false, // recurring } ``` ```typescript // create a one-shot timer (30 min from now = calculate cron accordingly) { action: "create", cron: "45 14 15 6 *", // June 15 at 14:45 (one-time) message: "Follow up on the deployment", one_shot: true, } ``` ```typescript // list active schedules { action: "list", } ``` ```typescript // delete a schedule { action: "delete", schedule_id: "a1b2c3d4", } ``` -------------------------------- ### NuggetShelf Class Source: https://context7.com/neovertex1/nuggets/llms.txt The NuggetShelf class manages multiple Nugget instances, providing methods for loading, saving, remembering, recalling, and forgetting facts across different memory kinds. ```APIDOC ## NuggetShelf Class ### Description Manages multiple `Nugget` instances under a shared directory and provides broadcast recall across all of them. The three canonical memory kinds are `user` (preferences), `project` (files, commands), and `agent` (self-knowledge). Shelf methods route facts to the correct kind automatically, or accept an explicit override. ### Methods - **`loadAll()`**: Loads all nuggets from the configured directory. - **`rememberKind(kind, key, value)`**: Stores a fact, inferring the kind if not provided. - **`recall(key, kind?)`**: Recalls a fact, optionally targeting a specific kind. - **`recallByKind(key, kinds)`**: Recalls a fact, prioritizing specified kinds. - **`forget(key, kind?)`**: Removes a fact, optionally targeting a specific kind. - **`forgetKind(kind, key)`**: Removes a fact from a specific kind. - **`list()`**: Returns the status of all loaded nuggets. - **`saveAll()`**: Saves all current nugget states. ### Example Usage ```typescript import { NuggetShelf } from "./src/nuggets/shelf.js"; const shelf = new NuggetShelf({ saveDir: "/home/user/.nuggets", autoSave: true }); shelf.loadAll(); shelf.rememberKind("project", "test-cmd", "npm test"); shelf.rememberKind("user", "pref:indent", "2 spaces"); const result = shelf.recall("how to run tests"); console.log(result); const kindResult = shelf.recallByKind("indent preference", ["user", "project", "agent"]); console.log(kindResult); shelf.forget("project", "test-cmd"); shelf.forgetKind("user", "pref:indent"); console.log(shelf.list()); shelf.saveAll(); ``` ``` -------------------------------- ### Nuggets Extension Auto-Capture Source: https://context7.com/neovertex1/nuggets/llms.txt Demonstrates how the Nuggets extension automatically captures facts from tool results and user input without explicit LLM action. ```typescript // Auto-capture (no LLM action needed): // When LLM calls read("src/auth/middleware.ts") // → facts.set("file:middleware", "src/auth/middleware.ts") // When user says "always use TypeScript" // → facts.set("pref:always:typescript", "TypeScript") ``` -------------------------------- ### Nugget Class: Storing and Recalling Facts with HRR Source: https://context7.com/neovertex1/nuggets/llms.txt Demonstrates how to use the Nugget class to store, recall, upsert, and forget key-value facts. Facts are rebuilt from a raw list using a seeded PRNG for efficient storage. Recall uses algebraic unbinding and cosine similarity. ```typescript import { Nugget } from "./src/nuggets/memory.js"; // Create an in-memory nugget (autoSave: false for tests/examples) const n = new Nugget({ name: "project", D: 2048, banks: 4, autoSave: false }); // Store facts n.remember("test-command", "npm test"); n.remember("deploy-process", "git push to main triggers vercel"); n.remember("python-version", "3.11.9"); // Recall by exact key const exact = n.recall("test-command"); console.log(exact); // { answer: "npm test", confidence: 0.94, margin: 0.81, found: true, key: "test-command" } // Recall by natural language (token overlap matching) const nl = n.recall("how to deploy"); console.log(nl); // { answer: "git push to main triggers vercel", confidence: 0.88, found: true, key: "deploy-process" } // Recall with session tracking (per-session dedup for hit counting) const tracked = n.recall("python-version", "session-abc123"); console.log(tracked.answer); // "3.11.9" console.log(n.facts()[2].hits); // 1 — incremented once for this session // Upsert (same key, new value) n.remember("test-command", "vitest run"); console.log(n.facts().length); // still 3, value updated // Forget const removed = n.forget("python-version"); console.log(removed); // true console.log(n.facts().length); // 2 // Status / capacity console.log(n.status()); // { // name: "project", fact_count: 2, dimension: 2048, banks: 4, // capacity_used_pct: 0.7, capacity_warning: "", max_facts: 0 // } // Persist to ~/.nuggets/project.nugget.json const path = n.save(); // atomic write via tmp rename // Reload const loaded = Nugget.load(path, { autoSave: true }); console.log(loaded.recall("test-command").answer); // "vitest run" ``` -------------------------------- ### Nuggets Extension Actions Source: https://context7.com/neovertex1/nuggets/llms.txt These are the actions available for the Nuggets extension, used within Pi agent sessions to manage persistent memory. The LLM calls the 'nuggets' tool with these parameters. ```typescript // remember { action: "remember", key: "test-command", value: "vitest run --reporter=verbose", kind: "project", // optional: "user" | "project" | "agent" } ``` ```typescript // recall { action: "recall", query: "how to run tests", } ``` ```typescript // forget { action: "forget", key: "test-command", } ``` ```typescript // list { action: "list", } ``` -------------------------------- ### Register Nuggets Plugin with Claude Code Agent Source: https://github.com/neovertex1/nuggets/blob/main/README.md Register the Nuggets memory plugin with the Claude Code agent host using its native MCP command. ```bash claude mcp add nuggets-memory -- nuggets-memory-plugin ``` -------------------------------- ### PiRpc: JSONL RPC Subprocess Wrapper Source: https://context7.com/neovertex1/nuggets/llms.txt Wraps a `pi --mode rpc` subprocess, handling communication via newline-delimited JSON. Manages streaming events, ACKs, timeouts, and graceful shutdown. Prompts resolve upon receiving an `agent_end` event. ```typescript import { PiRpc } from "./src/gateway/pi-rpc.js"; const rpc = new PiRpc( "/home/user/.nuggets-gateway/sessions/abc123def456", // sessionDir "/home/user/nuggets", // cwd (project root) "anthropic", // provider "claude-3-5-sonnet-20241022", // model (optional) ); rpc.on("exit", (code: number, signal: string) => { console.log(`Pi exited: code=${code} signal=${signal}`); }); rpc.start(); console.log(rpc.alive); // true // Send a prompt, await the full agent response try { const result = await rpc.promptAndWait("What's the capital of France?"); console.log(result.text); // "Paris" console.log(result.events); // Array of all RpcEvent objects received } catch (err) { console.error("Timeout or process died:", err.message); } // Send with image attachments (base64 paths) const imgResult = await rpc.promptAndWait( "What's in this image?", ["/tmp/screenshot.png"], 30_000, // idle timeout override (ms) ); // Graceful stop (SIGTERM → SIGKILL after 3s) rpc.stop(); ``` -------------------------------- ### PiPool: Per-User Process Pool with Idle Eviction Source: https://context7.com/neovertex1/nuggets/llms.txt Manages a pool of `PiRpc` instances, one per user JID, with automatic eviction after inactivity. Evicts the least-recently-used idle session if `MAX_PI_PROCESSES` is reached. ```typescript import { PiPool } from "./src/gateway/pi-pool.js"; const pool = new PiPool(); // Get or create a Pi process for a user const rpc = pool.getOrCreate("1234567890@s.whatsapp.net"); // rpc is a live PiRpc — same instance returned on subsequent calls // Mark busy (cancels idle timer) before sending a prompt pool.markBusy("1234567890@s.whatsapp.net"); const result = await rpc.promptAndWait("Hello!"); // Mark idle (starts idle eviction timer) after response pool.markIdle("1234567890@s.whatsapp.net"); // Force-kill a process (error recovery — next call spawns fresh) pool.kill("1234567890@s.whatsapp.net"); // Status console.log(pool.size); // number of active sessions // Shutdown all processes (call on SIGTERM) pool.stopAll(); ``` -------------------------------- ### Register Nuggets Plugin with Codex Agent Source: https://github.com/neovertex1/nuggets/blob/main/README.md Register the Nuggets memory plugin with the Codex agent host using its native MCP command. ```bash codex mcp add nuggets-memory -- nuggets-memory-plugin ``` -------------------------------- ### Initialize CronScheduler for Scheduled Tasks Source: https://context7.com/neovertex1/nuggets/llms.txt Instantiate `CronScheduler` with an `EventQueue` to manage persistent cron jobs backed by a JSON file. It evaluates jobs periodically and can bridge with Pi extensions for runtime job management. ```typescript import { CronScheduler } from "./src/gateway/cron.js"; import { EventQueue } from "./src/gateway/event-queue.js"; const queue = new EventQueue(); const cron = new CronScheduler(queue); // Set default JID for requests that don't specify one cron.setDefaultJid("987654321@telegram"); // Add a recurring job (fires daily at 9 AM) const daily = cron.addJob( "987654321@telegram", "0 9 * * *", // minute hour dom month dow "Send the user a morning greeting", false, // oneShot: false = recurring ); console.log(daily.id); // "a1b2c3d4" // Add a one-shot timer (fires once at 14:30 on weekdays) const reminder = cron.addJob( "987654321@telegram", "30 14 * * 1-5", "Remind the user about the team standup", true, // oneShot: true = auto-deletes after firing ); // List jobs for a specific user const jobs = cron.listJobs("987654321@telegram"); console.log(jobs); // [ // { id: "a1b2c3d4", jid: "...", cron: "0 9 * * *", prompt: "...", enabled: true, oneShot: false, ... }, // { id: "e5f6g7h8", jid: "...", cron: "30 14 * * 1-5", prompt: "...", enabled: true, oneShot: true, ... } // ] // Remove by ID cron.removeJob("a1b2c3d4"); // Start/stop the polling loops cron.start(); // ... gateway running ... cron.stop(); // File-bridge: Pi extension writes to .gateway/cron/requests.jsonl // Gateway picks it up within 5s and calls addJob/removeJob automatically // Example line in requests.jsonl: // {"action":"add","cron":"0 8 * * *","prompt":"morning standup reminder","oneShot":false,"timestamp":"2025-01-01T08:00:00.000Z"} ``` -------------------------------- ### Superposition of Multiple Facts Source: https://github.com/neovertex1/nuggets/blob/main/blog/src/content/blog/how-my-brain-works.md Stores multiple facts within a single vector by summing their 'traces'. Scaling by 1/√n keeps the vector magnitude bounded, allowing facts to coexist like superimposed waves. ```plaintext memory = trace₁ + trace₂ + trace₃ + ... ``` -------------------------------- ### Manage Heartbeats for User Check-ins Source: https://context7.com/neovertex1/nuggets/llms.txt Utilize `HeartbeatManager` to schedule recurring check-ins for users who have messaged. It respects quiet hours and defers heartbeats for recently active users. ```typescript import { HeartbeatManager } from "./src/gateway/heartbeat.js"; import { EventQueue } from "./src/gateway/event-queue.js"; const queue = new EventQueue(); // HEARTBEAT_INTERVAL_MS, QUIET_HOURS_START/END read from .env const heartbeat = new HeartbeatManager(queue); // Register a user when they first message (idempotent — also resets timer) heartbeat.register("987654321@telegram"); // Touch on every subsequent message to defer the next heartbeat heartbeat.touch("987654321@telegram"); // Unregister (e.g., user blocked the bot) heartbeat.unregister("987654321@telegram"); // Shutdown all timers on SIGTERM heartbeat.stopAll(); // Quiet hours example (.env): // QUIET_HOURS_START=22 // 10 PM — heartbeats suppressed from 10 PM to 8 AM // QUIET_HOURS_END=8 // 8 AM // When heartbeat fires, queue receives: // { // type: "heartbeat", // jid: "987654321@telegram", // prompt: "It's been a while since you last interacted with the user. Check your memory..." // } // If Pi responds "NOTHING", the router stays silent. Otherwise, the reply is sent. ``` -------------------------------- ### inferMemoryKind Function Source: https://context7.com/neovertex1/nuggets/llms.txt Automatically classifies a key-value pair into one of three memory kinds (`user`, `project`, `agent`) using prefix and keyword heuristics. ```APIDOC ## inferMemoryKind Function ### Description Classifies a key-value pair into one of three memory kinds (`user`, `project`, `agent`) using prefix and keyword heuristics. Used by the nuggets extension to route facts without explicit kind overrides. ### Parameters - **key** (string): The key of the fact to classify. - **value** (any): The value of the fact to classify. ### Returns - **MemoryKind**: The inferred memory kind ('user', 'project', or 'agent'). ### Example Usage ```typescript import { inferMemoryKind } from "./src/nuggets/kinds.js"; console.log(inferMemoryKind("pref:style", "2-space indent")); // "user" console.log(inferMemoryKind("file:router", "src/gateway/router.ts")); // "project" console.log(inferMemoryKind("personality-trait", "curious")); // "agent" ``` ``` -------------------------------- ### Complex Vector Key Generation Source: https://github.com/neovertex1/nuggets/blob/main/blog/src/content/blog/how-my-brain-works.md Represents a concept as a complex-valued vector on the unit circle. Each entry is a phase angle, ensuring keys are purely rotational. ```plaintext key = exp(iφ) where φ ~ Uniform(0, 2π) ``` -------------------------------- ### HRR Core Math: Complex Vector Operations Source: https://context7.com/neovertex1/nuggets/llms.txt Provides low-level building blocks for holographic representations using ComplexVector. Operates on ComplexVector ({ re: Float64Array, im: Float64Array }) with no external dependencies. ```typescript import { mulberry32, seedFromName, makeVocabKeys, makeRoleKeys, bind, unbind, orthogonalize, sharpen, corvacsLite, softmaxTemp, stackAndUnitNorm, type ComplexVector, } from "./src/nuggets/core.js"; const D = 512; // Seeded PRNG — deterministic, same seed = same keys const seed = seedFromName("my-nugget"); // u32 from first 4 bytes of name const rng = mulberry32(seed); // Vocabulary keys: unit-magnitude complex vectors const vocab = makeVocabKeys(3, D, rng); // vocab[i].re, vocab[i].im each have length D, |vocab[i][d]| = 1 // Role/position keys: successive powers of DFT base vector const roles = makeRoleKeys(D, 10); // 10 positional keys // Binding: bind(key, value) = element-wise complex product const binding = bind(vocab[0], vocab[1]); // Unbinding (retrieval): m * conj(key) const recovered = unbind(binding, vocab[0]); // recovered ≈ vocab[1] (cosine sim > 0.99 for D >= 256) // Orthogonalization — reduce cross-talk between keys const orthVocab = orthogonalize(vocab, 1 /* iters */, 0.4 /* step */); // Sharpening — contrast-increase for retrieval (p > 1 amplifies strong signals) const sharpened = sharpen(recovered, 1.5 /* p */); // CORVACS-lite soft saturation (a > 0 prevents magnitude runaway) const saturated = corvacsLite(sharpened, 0.5 /* a */); // Softmax with temperature for vocabulary scoring const sims = new Float64Array([0.3, 0.9, 0.5]); const probs = softmaxTemp(sims, 0.9); // lower T → sharper peaks // probs sums to 1.0, highest value at index 1 // Prepare unit-normed 2D representation for cosine similarity const normed = stackAndUnitNorm(orthVocab); // [V × 2D] real ``` -------------------------------- ### Binding Vectors via Complex Multiplication Source: https://github.com/neovertex1/nuggets/blob/main/blog/src/content/blog/how-my-brain-works.md Associates two concepts by binding their key vectors through element-wise complex multiplication. This operation geometrically corresponds to adding phase angles. ```plaintext trace = bind(role_key, value_key) = role ⊙ value ``` -------------------------------- ### Unbinding and Recalling Facts Source: https://github.com/neovertex1/nuggets/blob/main/blog/src/content/blog/how-my-brain-works.md Recovers a specific fact from memory by multiplying the memory vector with the conjugate of the query key. This isolates the target fact while other information becomes noise. ```plaintext recovered = memory ⊙ conj(query_key) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.