Skip to main content

SDK Reference

npm install @emartai/mindr

The SDK provides a typed TypeScript API for programmatic access to Mindr. It wraps @emartai/mindr-core without depending on the CLI.

import { Mindr } from '@emartai/mindr';

const mindr = await Mindr.open({ project: './my-project' });
// ... use the API ...
mindr.close();

Mindr.open(opts)

Open a Mindr client for a project. Loads .mindr/config.toml from opts.project (walking up the directory tree), connects to the configured backend, and returns a ready client.

const mindr = await Mindr.open({ project: './my-project' });

Options (MindrOpenOptions):

FieldTypeDescription
projectstringAbsolute or relative path to the project root
backend?MemoryBackendInject a pre-built backend (skips config loading — useful for testing)
config?MindrConfigInject a pre-built config (skips .mindr/config.toml discovery)

mindr.close()

Release resources held by the backend (e.g. SQLite file handles). Call this when done.

mindr.close();

mindr.remember(content, opts?)

Store a memory string.

const mem = await mindr.remember('We use tRPC for all internal APIs', {
type: 'decision',
module: 'api',
});
console.log(mem.id); // "mem-abc123..."

Options (RememberOptions):

FieldTypeDescription
type?MemoryTypedecision, convention, bug_pattern, debt, note, context
module?stringModule or area (e.g. 'api', 'auth')
tags?MindrTag[]Additional { key, value } tags
metadata?Record<string, unknown>Arbitrary metadata stored with the memory

Returns a MindrMemory.


mindr.forget(id)

Soft-delete a memory by ID.

await mindr.forget(mem.id);

mindr.query(opts?)

List raw memories matching filters, enriched with quality scores.

const results = await mindr.query({
type: 'decision',
module: 'api',
since: new Date('2026-01-01'),
limit: 10,
});

for (const m of results) {
console.log(m.content, m.qualityScore);
}

Options (QueryOptions):

FieldTypeDescription
type?MemoryTypeFilter by memory type
module?stringFilter by module tag
since?DateOnly return memories created at or after this date
limit?numberMax results (default 50)

Returns ScoredMemory[]MindrMemory extended with qualityScore: number and qualityBreakdown: QualityBreakdown.


mindr.getDecisions(opts?)

Return decision memories as structured Decision objects, newest first.

const decisions = await mindr.getDecisions({ module: 'api' });

for (const d of decisions) {
console.log(`[${d.date}] ${d.summary} (confidence: ${d.confidence})`);
}

Options (DecisionsOptions):

FieldTypeDescription
module?stringFilter by module
from?DateOn or after this date
to?DateOn or before this date
limit?numberMax results (default 50)

Decision fields:

FieldTypeDescription
idstringMemory ID
summarystringDecision text (prefix "Decision: " stripped)
datestringYYYY-MM-DD date string
modulestringModule tag value
trigger?stringPrimary trigger type
triggers?string[]All trigger types that fired
confidence?numberConfidence score in [0, 1]
rationale?stringCommit body text
filesAffected?string[]Files touched in the triggering commit
reversed?booleanTrue if this decision was later reversed
createdAtstringFull ISO 8601 timestamp

mindr.getDebt(opts?)

Return active debt items (TODO / FIXME / HACK) as structured DebtItem objects.

const debt = await mindr.getDebt({ severity: 'high' });

for (const item of debt) {
console.log(`${item.keyword} ${item.location}: ${item.content}`);
}

Options (DebtOptions):

FieldTypeDescription
module?stringFilter by module
severity?'high' | 'medium' | 'low'Filter by severity
minAge?numberOnly return items older than N days
limit?numberMax results

DebtItem fields:

FieldTypeDescription
idstringMemory ID
contentstringRaw debt text
locationstringfile:line string
keywordstringTODO, FIXME, HACK, or XXX
file?stringSource file path
line?numberLine number
modulestringModule tag
severity?stringhigh, medium, or low
createdAtstringFull ISO 8601 timestamp

mindr.addDebt(content, opts)

Manually record a technical debt item.

const item = await mindr.addDebt('Temporary retry loop — replace with queue', {
file: 'src/billing/invoice.ts',
severity: 'high',
});

Options (AddDebtOptions):

FieldTypeDescription
filestringSource file path (required)
severity?'high' | 'medium' | 'low'Default 'medium'
module?stringOverrides the module inferred from file
tags?MindrTag[]Additional tags
metadata?Record<string, unknown>Additional metadata

Returns a DebtItem.


mindr.resolveDebt(id)

Mark a debt item as resolved. Stores a debt_resolved marker; the original item is preserved.

await mindr.resolveDebt('mem-abc123');

mindr.getConventions(opts?)

Return detected convention profiles per language.

const profiles = await mindr.getConventions({ language: 'typescript' });

for (const p of profiles) {
for (const c of p.conventions) {
console.log(`${p.language} ${c.category}: ${c.pattern} (${c.score}%)`);
}
}

Options (ConventionsOptions):

FieldTypeDescription
language?stringFilter by language (e.g. 'typescript', 'python')

Returns ConventionProfile[]. Each profile has:

FieldTypeDescription
languagestringLanguage name
analyzedFilesnumberNumber of files scanned
analyzedAtstringISO timestamp of last scan
conventionsConventionEntry[]Detected patterns with scores

Each ConventionEntry has pattern, category, score (0–100), and sampleCount.


mindr.getSessionContext(opts?)

Build a token-aware session context block for injecting into an agent's system prompt.

const ctx = await mindr.getSessionContext({
module: 'auth',
max_tokens: 2000,
});

console.log(ctx.summary); // === MINDR CONTEXT === ...

Options (SessionContextOptions):

FieldTypeDescription
module?stringFocus context on a specific module
files?string[]Changed files for scoped context
max_tokens?numberToken budget; Mindr trims sections to fit

Returns a SessionContext with:

  • summary — the full formatted context string
  • stack — detected languages and frameworks
  • conventions — convention profiles
  • decisions — recent decision memories
  • hotModules — most-touched modules
  • warnings — high-severity debt items
  • tokensUsed — estimated token count
  • droppedSections — sections omitted due to token budget

mindr.getContextHealth(sessionId)

Score how focused the current session is (0–100).

const health = await mindr.getContextHealth('session-abc');
// { score: 72, recommendation: 'ok', breakdown: { ... } }

Recommendations: 'ok' (≥70), 'consider_checkpoint' (40–69), 'recommend_fresh_session' (below 40).


mindr.checkpointSession(sessionId)

Write a session checkpoint memory.

const checkpoint = await mindr.checkpointSession('session-abc');

mindr.getStats(opts?)

Return token metering totals.

const stats = await mindr.getStats({ last: '7d' });
// { sessions: 12, tokensInjected: 48000, estimatedSaved: 96000, range: { low: 48000, high: 96000 } }

Options:

FieldTypeDescription
session?stringFilter to a specific session ID
last?stringTime window: '30m', '2h', '7d', '2w'

mindr.getStatus()

Return a snapshot of the instance — backend type, project path, and per-type memory counts.

const status = await mindr.getStatus();
// { backendType: 'sqlite', projectPath: '/my-project', memoryCounts: { decision: 12, debt: 5, ... } }

mindr.regenerateAgentsMd(opts?)

Generate AGENTS.md and/or CLAUDE.md from observed patterns, writing to disk.

const { agentsMd } = await mindr.regenerateAgentsMd();
// Wrote AGENTS.md to project root

const { agentsMd, claudeMd } = await mindr.regenerateAgentsMd({ target: 'all' });

Options (RegenerateOptions):

FieldTypeDescription
target?'agents-md' | 'claude-md' | 'all'Which file(s) to generate (default 'agents-md')
agentsMdPath?stringCustom output path for AGENTS.md
claudeMdPath?stringCustom output path for CLAUDE.md

Returns a RegenerateResult with agentsMd? and claudeMd? content strings.


mindr.migrateSqliteToRemembr()

Copy all SQLite memories to the Remembr backend.

const { migrated } = await mindr.migrateSqliteToRemembr();
console.log(`Migrated ${migrated} memories`);

Requires the config to already have storage.backend = "remembr" and valid Remembr credentials.


MEMORY_TYPES

Exported constant listing all valid memory type strings.

import { MEMORY_TYPES } from '@emartai/mindr';
// ['decision', 'convention', 'bug_pattern', 'debt', 'debt_resolved', 'session_checkpoint', 'note', 'context']

Full example

import { Mindr } from '@emartai/mindr';

const mindr = await Mindr.open({ project: '.' });

// Store decisions
await mindr.remember('Chose PostgreSQL over MongoDB for ACID guarantees', {
type: 'decision',
module: 'db',
});

// Query context for auth module
const ctx = await mindr.getSessionContext({ module: 'auth', max_tokens: 1500 });

// List high-severity debt
const debt = await mindr.getDebt({ severity: 'high' });
console.log(`${debt.length} high-severity debt items`);

// Check token savings
const stats = await mindr.getStats({ last: '7d' });
console.log(`Saved ~${stats.estimatedSaved} tokens this week`);

// Generate fresh AGENTS.md
await mindr.regenerateAgentsMd();

mindr.close();