Skip to content
HomenShumPublic

About

Provider-agnostic passive memory for agent systems — notices entities in activity streams, surfaces noteworthy suggestions, learns from dismissals, and deduplicates. Convex is one proof, not the only one.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

NodeMem: Notice passively. Act explicitly.

Quickstart · Code walkthrough · Handoff · All projects

NodeMem

A provider-agnostic passive memory component for agent systems.

It notices entities in activity streams, surfaces noteworthy suggestions, learns from dismissals, and deduplicates — without auto-executing jobs.


Live graph rail: NodeMem notices entities as dim, unmeasured nodes with no edges; a human confirms one suggestion and exactly one faint traversal edge appears

↑ Live graph rail (demo/graph-rail): entities NodeMem notices stay dim with no measured count and draw no edges; confirming one suggestion draws exactly one traversal edge — a recorded hop, not evidence.


NodeMem passive intelligence in NodeRoom: noteworthy suggestions appear in the inbox, user reviews and approves before any research runs

↑ NodeMem running inside NodeRoom — passive suggestions surface in the noteworthy inbox, user reviews and explicitly approves before any research job runs.

New here? Read docs/START_HERE.md — one message followed through the code in the order it runs. The same walkthrough is clickable in .tours/ if you use the CodeTour extension.

Both clips above have committed producers: node scripts/record-graph-rail.mjs records the rail, npm run capture re-asserts and re-shoots the stills.


Table of contents


Documentation

Document What it answers
docs/START_HERE.md One message, followed through the code in runtime order. Start here.
docs/NODEKIT_ADOPTION.md Portable ownership, current commands and incomplete protocol boundaries
docs/codebase/STACK.md What is installed and why; every command
docs/codebase/STRUCTURE.md What each file is for
docs/codebase/ARCHITECTURE.md The boundaries, the gate order, why the browser page is shaped as it is
docs/codebase/CONVENTIONS.md How code here is written
docs/codebase/INTEGRATIONS.md Convex, esm.sh, the vendored renderer, CI
docs/codebase/TESTING.md What each test proves, and what is not covered
docs/codebase/CONCERNS.md Everything known to be wrong, with reproductions
docs/SIMPLIFICATION_REPORT.md Before/after measurements for the Wave 3 cleanup
promotion/PROMOTION_LOG.md The product loop: defect ledger and iterations

Why this exists

Most agent memory systems either:

  • Auto-execute on every detected entity, flooding job queues and starving foreground work.
  • Remember nothing, re-suggesting the same dismissed entities endlessly.
  • Tie you to one provider — Convex, OpenAI, Pinecone — with no escape hatch.

NodeMem fixes all three:

  1. Passive doctrine — detection creates suggestions, not jobs. The caller decides whether to promote.
  2. Dismissal learning — entities dismissed by users are suppressed in future scans.
  3. Provider-agnostic ports — MemoryStore is an interface. Convex, SQLite, Postgres, in-memory — your choice.

Convex is one proof, not the only one. The core is pure TypeScript with zero provider dependencies. Bring your own backend.


How it works

sequenceDiagram
    participant Activity as Activity Stream
    participant Debounce as Debouncer
    participant Scan as Scan Orchestrator
    participant Classify as Classifier
    participant Policy as Policy Resolver
    participant Dedup as Dedup + Quota
    participant Dismiss as Dismissal Learner
    participant Inbox as Noteworthy Inbox

    Activity->>Debounce: Raw event (message, edit, idle)
    Debounce->>Debounce: Sliding-window coalesce
    Debounce->>Scan: Debounced activity row
    Scan->>Classify: classifyNoteworthy(text)
    Classify-->>Scan: Finding { entities, signals, score, action }
    Scan->>Policy: resolveAssistivePolicy(roomId)
    Policy-->>Scan: Resolved policy { mode, disabledSignals, watchlist }
    alt Policy mode = "off"
        Scan-->>Activity: Suppressed (policy_off)
    end
    alt Signal disabled
        Scan-->>Activity: Suppressed (signal_disabled)
    end
    Scan->>Dedup: Check existing noteworthy for entity
    alt Duplicate entity exists
        Dedup-->>Scan: duplicate_entity
        Scan-->>Activity: Suppressed (duplicate_entity)
    end
    Scan->>Dedup: Check per-room quota
    alt Quota exceeded
        Dedup-->>Scan: room_quota_exceeded
        Scan-->>Activity: Suppressed (room_quota_exceeded)
    end
    Scan->>Dismiss: Check dismissed entities
    alt Entity previously dismissed
        Dismiss-->>Scan: previously_dismissed
        Scan-->>Activity: Suppressed (previously_dismissed)
    end
    Scan->>Inbox: Noteworthy suggestion { finding, entities, signals }
    Inbox->>Activity: User sees suggestion (no auto-job)
Loading

Pipeline gates (in order)

Gate Suppress reason Description
Policy policy_off Room policy is off — all detection suppressed
Signal disabled signal_disabled Signal kind is in disabledSignalKinds
Watchlist not_on_watchlist Policy is approved_watchlist_only and entity isn't listed
Dedup duplicate_entity Active noteworthy suggestion for same entity already exists
Quota room_quota_exceeded Room has too many noteworthy suggestions in the last hour
Dismissal previously_dismissed Entity was previously dismissed by a room member

Quick start

Full TypeScript demo

Start here to exercise the library in src/. The existing demo follows classification, policy, duplicate suppression, dismissal and quota behavior through the real source modules.

npm install
npm run demo
Expected output
  Step 1: Classify a chat message
  ✓ Entity detected — CardioNova
  ✓ Score > 0.35 — score=0.90
  ✓ Multiple signals — organization_candidate, finance_signal, person_or_interaction, open_question_or_task
  ✓ Action is start_research_job

  Step 2: Scan activity → noteworthy suggestion
  ✓ Scan result is noteworthy

  Step 3: Duplicate entity → dedup suppresses
  ✓ Duplicate suppressed — duplicate_entity

  Step 4: Dismiss entity → re-scan → suppressed
  ✓ Dismissed entity suppressed — previously_dismissed

  Step 5: Policy 'off' → all suppressed
  ✓ Policy 'off' suppresses all — policy_off

  Step 6: Per-room quota exceeded
  ✓ Quota exceeded suppresses — room_quota_exceeded

  Summary: Pass=13  Fail=0  Total=13
  ✓ DEMO PASSED — all gates green (13/13)

Zero-dependency demo (no install)

This runs the JavaScript classifier and minimal store in demo/nodeMemDemoCore.mjs, shared with the browser demo. It does not exercise the canonical TypeScript library below src/.

node demo/runNodeMemDemo.mjs
Expected output
  NodeMem — Zero-dependency demo
  Doctrine: "Notice passively, act explicitly."

  ✓ Entity detected — CardioNova
  ✓ Score > 0.35 — score=0.90
  ✓ 4+ signals — 4 signals
  ✓ Action: start_research_job
  ✓ Dismissal learning works
  ✓ Classifier is deterministic

  Pass: 6  Fail: 0
  ✓ PASSED

Live graph rail

Read the current developer handoff for the local demo's verified scope and open UI grades. After installing dependencies, node scripts/verify-ui-repair.mjs exercises the actual decision, keyboard, narrow-layout, CDN-retry and reload journey and writes a new evidence directory. It uses the pinned axe-core development dependency for resolved-state contrast checks.

The zero-dependency demo's pipeline (same classifier, same store, same fixtures — imported from demo/nodeMemDemoCore.mjs, not re-implemented) rendered live by NodeGraph Live (vendored in vendor/nodegraph-live/, pending npm publish):

npm install
npm run dev       # serves the repo; prints http://127.0.0.1:5173/demo/graph-rail/index.html
npm run capture   # the same page in headless Chromium: 12 assertions + screenshots
npm run audit:web # lighthouse + axe against the served page; fails on a regression
npm run audit:wig # Web Interface Guidelines review at 320/375/412/768/1440

npm run capture needs Chromium once: npx playwright install chromium. The two audits write their raw output to promotion/evidence/audit/; what the review concluded from it is promotion/WIG_REVIEW.md. audit:web pulls [email protected] and @axe-core/[email protected] through npx at pinned versions, so it needs a network and a local Chrome.

Before any confirmation — every noticed entity present, dim, "unknown — not measured", and zero edges (the capture script exits nonzero if one exists):

Noticed entities only, zero edges

After a human clicks Confirm on one suggestion — exactly one faint traversal edge, a confirmed hop, still not a measured count:

One traversal edge after one confirmation

Noticing draws a dim node, a suggestion draws nothing, only a human confirmation draws an edge — and assertEdge is never called, because NodeMem has no versioned curated source to back an assertion.

Run tests

npm install
npm test

Everything, before you push

npm run check     # secret-scan + typecheck + tests + the 13-check pipeline proof
npm run proof     # the pipeline story plus a receipt at docs/eval/nodemem-smoke.json

Code examples

These snippets illustrate the source API exported by src/index.ts. The bare nodemem imports are API sketches: this checkout does not declare a built package entrypoint or build script for npm consumers. For runnable source usage, follow demo/demo-runner.ts with npm run demo; do not treat the sketches as a verified package-installation recipe.

Classify text for noteworthy entities

import { classifyNoteworthy } from "nodemem";

const finding = classifyNoteworthy(
  "Met with CardioNova last week. They just raised Series A and are piloting at three hospitals."
);

console.log(finding.score);           // 0.90
console.log(finding.action);          // "start_research_job"
console.log(finding.entities[0]);     // { displayName: "CardioNova", entityKey: "cardionova", ... }
console.log(finding.signals);         // ["organization_candidate", "finance_signal", "person_or_interaction", ...]

Scan an activity row through the full pipeline

import { scanActivity, InMemoryAdapter } from "nodemem";

const store = new InMemoryAdapter();

// Insert activity from your stream
const rowId = store.insertActivity({
  roomId: "room-1",
  sourceKind: "message",
  sourceId: "msg-1",
  sourceHash: "abc123",
  text: "Met with CardioNova about their Series A funding raise.",
  visibility: "room",
});

// Run the full scan pipeline
const result = await scanActivity(store, {
  id: rowId,
  roomId: "room-1",
  sourceKind: "message",
  sourceId: "msg-1",
  sourceHash: "abc123",
  text: "Met with CardioNova about their Series A funding raise.",
  visibility: "room",
});

if (result.status === "noteworthy") {
  // Show suggestion to user. Do NOT auto-create a job.
  console.log(`Noteworthy: ${result.finding?.entities[0]?.displayName}`);
  console.log(`Signals: ${result.finding?.signals.join(", ")}`);
  console.log(`Score: ${result.finding?.score}`);
}

Learn from dismissals

// User dismisses "CardioNova" from the noteworthy inbox
await store.recordDismissal("room-1", ["CardioNova"], "user-alice");

// Future scans for CardioNova in this room are suppressed
const dismissed = await store.isEntityDismissed("room-1", ["CardioNova"]);
console.log(dismissed); // true

Set per-room assistive policy

// Room owner sets policy to "ask before research"
await store.setRoomPolicy("room-1", {
  mode: "ask_before_research",
  allowExternalCalls: true,
  maxSuggestionsPerHour: 20,
  maxApprovedBackgroundJobsPerDay: 5,
  disabledSignalKinds: [],
  approvedEntityWatchlist: [],
});

// System default (suggestions_only) is overridden by room policy
// Most restrictive setting always wins

The scanner uses the lower of the resolved room/system maxSuggestionsPerHour and the host's maxPerRoomPerHour (default 10). Setting either ceiling to zero withholds new suggestions. Each supplied limit must be a non-negative safe integer. For an otherwise eligible scan, invalid limits reject with RangeError before a quota read or verdict write. Ignored messages skip validation; room/system limits validate during policy resolution, and the host limit validates at the quota gate. An omitted or undefined optional host/system override keeps its default.

The storage port separates counting from writing. Hosts must supply serialization or a transaction for a hard cap during concurrent scans in the same room. The reference adapter counts currently noteworthy rows by updatedAt, not a durable history of every suggestion produced. Same-row retries also remain unsafe; see the recorded storage limits.

Debounce rapid activity

import { computeDebounce } from "nodemem";

const now = Date.now();

// First event — fresh debounce window
const d1 = computeDebounce(now, null, 12_000);
console.log(d1.effectiveDelay); // 12000 (ms)

// Second event 3s later — window slides but caps at maxWait
const d2 = computeDebounce(now + 3_000, d1.state, 12_000);
console.log(d2.effectiveDelay); // capped by maxWaitAt - now

Architecture

src/
  index.ts                    # Public API barrel — 28 names, nothing else is public
  core/
    classifier.ts             # Pure: entity + signal detection from text
    scanOrchestrator.ts       # The pipeline: seven gates, one verdict per row
    policyResolver.ts         # Pure: how much noticing a room allows (quieter wins)
    ports.ts                  # The entire storage contract, in one file
    dedupeKey.ts              # Pure: deterministic activity dedupe keys
    debouncer.ts              # Pure: sliding-window debounce logic
  adapters/
    inMemoryAdapter.ts        # Zero-dependency reference MemoryStore implementation
    convexSchema.ts           # Convex table definitions (drop into your convex/ dir)

Port contract

interface MemoryStore extends DismissalStore, DedupStore, PolicyStore {
  patchRow(id: string, patch: {
    status: ActivityStatus;
    finding?: NoteworthyFinding;
    updatedAt: number;
  }): Promise<void>;
}

Implement this single interface with any backend. The in-memory adapter is the reference. patchRow must reject if the activity row does not exist. A fulfilled write lets scanActivity return its verdict, so silently ignoring a missing row would report an outcome that was never saved. Re-enqueue through the host's normal activity creation path before scanning again; the scanner does not create missing rows.


Using with Convex

  1. Copy src/adapters/convexSchema.ts into your convex/ directory.
  2. Merge the table definitions into your schema.ts:
import {
  roomActivityOutbox,
  roomDismissedEntities,
  roomAssistivePolicies,
} from "./nodemem/schema.js";

export default defineSchema({
  // ... your existing tables
  roomActivityOutbox,
  roomDismissedEntities,
  roomAssistivePolicies,
});
  1. Implement MemoryStore against Convex's MutationCtx / QueryCtx.

Using with any backend

import { scanActivity, type MemoryStore } from "nodemem";

// Implement the port with your backend
class MyStore implements MemoryStore {
  async listNoteworthy(roomId: string, limit?: number) {
    // your query — e.g. SQL, Firestore, Supabase
  }
  async countNoteworthyLastHour(roomId: string) {
    // your query
  }
  async isEntityDismissed(roomId: string, entityNames: string[]) {
    // your query
  }
  async recordDismissal(roomId: string, entityNames: string[], by: string) {
    // your mutation
  }
  async getRoomPolicy(roomId: string) {
    // your query
  }
  async setRoomPolicy(roomId: string, policy: AssistivePolicy) {
    // your mutation
  }
  async patchRow(id: string, patch: { status: ActivityStatus; finding?: NoteworthyFinding; updatedAt: number }) {
    // your mutation
  }
}

const store = new MyStore();
const result = await scanActivity(store, {
  id: "row-1",
  roomId: "room-1",
  sourceKind: "message",
  sourceId: "msg-1",
  sourceHash: "abc123",
  text: "Met with CardioNova about their Series A funding raise.",
  visibility: "room",
});

if (result.status === "noteworthy") {
  // Show suggestion to user. Do NOT auto-create a job.
  console.log(`Noteworthy: ${result.finding?.entities[0]?.displayName}`);
}

Signals

Signal Enum Trigger Example
Organization candidate organization_candidate Capitalized multi-word name or suffix match (Inc, Labs, Bio, etc.) "CardioNova Inc", "Stripe Labs"
Finance signal finance_signal Series A/B, seed, funding, raise, runway, burn, ARR, revenue, EBITDA, margin, cash "raised Series A", "runway is 18 months"
Person interaction person_or_interaction Met, spoke, talked, call, founder, CEO, CFO, contact, intro, emailed "Met with the founder"
Research signal research_signal Product, launch, announced, customer, pilot, hospital, pricing, competitor, market, news "announced a pilot at three hospitals"
Open question / task open_question_or_task Verify, source, follow up, ask, research, find, confirm, todo, next step, reference "Need to verify their runway"
Source URL source_url https:// URL "See https://example.com"

Scoring

  • Base: 0.18 per detected signal (max 6 signals → 1.08, clamped to 1.0)
  • Thresholds:
    • ≥ 0.70 → start_research_job (4+ signals)
    • ≥ 0.50 → create_coach_cue (2+ signals)
    • ≥ 0.35 → index_only (1+ signal)
    • < 0.35 → ignore

Assistive modes

Mode Behavior Use case
off All passive detection suppressed. Quiet mode, focus work
suggestions_only Default. Suggestions surface in inbox, no auto-jobs. Most rooms
ask_before_research Suggestions surface, user must approve before any research. Sensitive rooms
approved_watchlist_only Only entities on the approved watchlist get suggestions. Curated deal rooms

Most restrictive setting wins across system default → room policy.


Doctrine

Notice passively, act explicitly. Passive should create options, not jobs.

NodeMem detects what's noteworthy and surfaces it as a suggestion. The user — or an explicit approval workflow — decides whether to act. This prevents:

  • Job queue saturation from passive auto-execution
  • Infinite retry loops on budget-limited free routes
  • Duplicate suggestions for the same entity
  • Re-suggesting entities the user already dismissed

Project structure

NodeMem/
├── src/                          # the library — 9 files, this is what you import
│   ├── index.ts                  # Public API barrel
│   ├── core/
│   │   ├── classifier.ts         # Entity + signal detection
│   │   ├── scanOrchestrator.ts   # The pipeline: seven gates
│   │   ├── policyResolver.ts     # Assistive policy resolution
│   │   ├── ports.ts              # The whole storage contract
│   │   ├── dedupeKey.ts          # Deterministic dedupe keys
│   │   └── debouncer.ts          # Sliding-window debounce
│   └── adapters/
│       ├── inMemoryAdapter.ts    # Zero-dependency reference
│       └── convexSchema.ts       # Convex table definitions
├── tests/                        # 8 test files — see docs/codebase/TESTING.md
├── demo/
│   ├── demo-runner.ts            # the 13-check pipeline story
│   ├── runNodeMemDemo.ts         # npm run demo / npm run proof
│   ├── runNodeMemDemo.mjs        # npm run demo:node — no install, no build
│   ├── nodeMemDemoCore.mjs       # plain-JS classifier copy for the no-build surfaces
│   └── graph-rail/               # the one page a human can open
├── scripts/
│   ├── serve.mjs                 # npm run dev, and both capture scripts
│   ├── capture-graph-rail.mjs    # the browser gate — 12 assertions
│   ├── record-graph-rail.mjs     # records the README clip (needs ffmpeg)
│   └── secret-scan.mjs           # Secret scanner
├── docs/                         # START_HERE, codebase/, SIMPLIFICATION_REPORT
├── .tours/                       # the same walkthrough, clickable in VS Code
├── promotion/                    # product loop: goal, journeys, defect ledger
├── vendor/nodegraph-live/        # vendored graph renderer (browser only)
├── assets/                       # clips and screenshots, each with a producer
├── package.json
├── tsconfig.json
├── vitest.config.ts
└── README.md

License

MIT © Homen Shum

About

Provider-agnostic passive memory for agent systems — notices entities in activity streams, surfaces noteworthy suggestions, learns from dismissals, and deduplicates. Convex is one proof, not the only one.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages