Use Narsil to find notes by their text while Sirannon stores the authoritative rows. Select the agent from authenticated application context, filter the search to that agent, and recheck ownership in the database before returning text to a model.
This guide uses Sirannon 0.4 and Narsil 0.3. Install Narsil in the application with pnpm add -E @delali/narsil. The example uses keyword search, so it requires no embedding model or external API key.
Find a note when the question uses different words
A subject lookup matches an exact stored key. A student can ask about funding for an exchange without using the subject under which an adviser filed the note, so an equality query can return nothing while a text search finds a relevant note.
The complete notes.ts example includes advising notes and a separate funding note. It builds the index before accepting later writes, then serialises change processing and waits for the demonstrated update before searching.
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
import { type ChangeEvent, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
interface NoteRow {
id: number
agent_id: string
subject: string
body: string
}
type NoteDocument = {
id: string
agentId: string
subject: string
body: string
}
const asDocument = (row: NoteRow): NoteDocument => ({
id: String(row.id), agentId: row.agent_id, subject: row.subject, body: row.body,
})
const directory = await mkdtemp(join(tmpdir(), 'sirannon-retrieval-'))
const sirannon = new Sirannon({ driver: betterSqlite3() })
const narsil = await createNarsil()
try {
const db = await sirannon.open('student-services', join(directory, 'notes.db'))
await db.execute(`CREATE TABLE note (
id INTEGER PRIMARY KEY, agent_id TEXT NOT NULL, subject TEXT NOT NULL, body TEXT NOT NULL
)`)
await db.executeBatch('INSERT INTO note VALUES (?, ?, ?, ?)', [
[1, 'advising-agent', 'term abroad', 'Ask the bursary office about funding a term abroad.'],
[2, 'advising-agent', 'exchange dates', 'The exchange programme opens in the spring semester.'],
[3, 'funding-agent', 'private application', 'A student requested a hardship bursary for a term abroad.'],
])
await narsil.createIndex('student_notes', {
schema: { agentId: 'string', subject: 'string', body: 'string' }, language: 'english',
})
const rows = await db.query<NoteRow>('SELECT * FROM note ORDER BY id')
const loaded = await narsil.insertBatch('student_notes', rows.map(asDocument), { wait: true })
if (loaded.failed.length > 0) throw new Error('The notes index could not be loaded')
await db.watch('note')
let pending = 0
let isHealthy = true
let updates: Promise<void> = Promise.resolve()
const MAX_PENDING_EVENTS = 1000
const indexed = Promise.withResolvers<void>()
const deadline = setTimeout((): void => indexed.reject(new Error('Index delivery timed out')), 5000)
const handleChange = (event: ChangeEvent<NoteRow>): Promise<void> => {
if (!isHealthy || pending >= MAX_PENDING_EVENTS) {
isHealthy = false
return Promise.reject(new Error('Rebuild the notes index before serving more searches'))
}
pending += 1
const task = updates.then(async (): Promise<void> => {
if (event.type === 'insert') {
await narsil.insert('student_notes', asDocument(event.row), undefined, { wait: true })
} else if (event.type === 'update') {
await narsil.update('student_notes', String(event.row.id), asDocument(event.row), { wait: true })
} else {
if (!event.oldRow) throw new Error('A deleted note has no earlier row')
await narsil.remove('student_notes', String(event.oldRow.id), { wait: true })
}
indexed.resolve()
})
updates = task.catch((error: unknown): never => {
isHealthy = false
throw error
}).finally((): void => { pending -= 1 })
return updates
}
const subscription = db.on('note').subscribe<NoteRow>(handleChange, {
onError: (error): void => {
isHealthy = false
indexed.reject(error)
},
})
try {
const searchNotes = async (agentId: string, text: string): Promise<NoteRow[]> => {
await updates
if (!isHealthy) throw new Error('The notes index needs recovery')
const found = await narsil.query<NoteDocument>('student_notes', {
term: text, filters: { fields: { agentId: { eq: agentId } } }, limit: 3,
})
const ids = found.hits.map((hit): string => hit.id)
if (ids.length === 0) return []
const placeholders = ids.map((): string => '?').join(', ')
const current = await db.query<NoteRow>(
`SELECT * FROM note WHERE agent_id = ? AND id IN (${placeholders})`, [agentId, ...ids])
const byId = new Map(current.map((row: NoteRow): [string, NoteRow] => [String(row.id), row]))
return ids.flatMap((id: string): NoteRow[] => {
const row = byId.get(id)
return row ? [row] : []
})
}
await Promise.all([
db.execute('UPDATE note SET body = ? WHERE id = 1', ['The bursary office can explain funding for a term abroad.']),
indexed.promise,
])
const notes = await searchNotes('advising-agent', 'funding for a term abroad')
console.log(JSON.stringify(notes.map((row: NoteRow): { subject: string; body: string } => ({
subject: row.subject, body: row.body,
})), (key: string, value: unknown): unknown =>
typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
} finally {
clearTimeout(deadline)
subscription.unsubscribe()
await updates.catch((error: unknown): void => console.error('Index update failed', error))
}
} finally {
await narsil.shutdown()
await sirannon.shutdown()
await rm(directory, { recursive: true, force: true })
}Search the notes by what they say
createIndex() declares the fields that Narsil indexes. insertBatch() reports per-document failures, so check its failed array before treating the index as ready. The wait: true option waits for worker copies before a later query uses those writes.
The bootstrap assumes writers remain paused until the first load and subscription are ready. For a service that must index while writes continue, use a consistent snapshot and replayable change cursor or a durable outbox. A table read followed by a subscription can otherwise miss writes between those operations.
Sirannon does not await an asynchronous subscriber callback. The example therefore serialises updates and returns their promises so that onError receives failures. Its 1000-event queue limit is an illustrative bound; exceeding it disables searches until the application rebuilds the index. Choose deployment limits from event size and available memory.
An in-process subscription has no restart cursor. Rebuild the index from the database after restart before accepting searches, or use the remote resumption protocol with a durable cursor and reset handling. Saving an index alone does not prove that it contains every committed database change.
Keep one agent out of another's notes
The search filter narrows candidates to agentId, while the SQL recheck returns current rows only for that same agent. Obtain the identifier from authenticated context when constructing the tool. A model-controlled ownership filter would let the caller choose another agent's notes.
Use the database rows for the returned text, because an index can contain an earlier body or owner while updates are pending. Search rankings and counts can also become stale, so return only the authorised rows through this tool. Broader permission rules require equivalent checks in the database query.
An embedded index is available to trusted application code. When clients access the Narsil HTTP server, enforce index permissions on that server or put an authenticated retrieval service in front of it.
Where to go next
Narsil's full-text guide explains keyword ranking. Hybrid search combines keyword and vector retrieval, while embedding adapters can encode text locally. AI agent tools binds a retrieval tool to its authenticated caller.