# Memory

> The user's shared, phone-local timeline of transcript lines and notes.

Source: https://docs.dev.glassly.ai/app-devs/core-concepts/memory/

`session.memory` is one timeline of what happened around the user: spoken
transcript lines and notes, plus an hourly summary heading each hour. Unlike
[`session.storage`](https://docs.dev.glassly.ai/app-devs/core-concepts/storage.md), it isn't scoped to your
miniapp. The store is host-level and user-scoped, so every miniapp that declares
the `MEMORY` permission reads and writes the same timeline, and the user manages
it in Settings > Memory.

```typescript
await session.memory.addNote("Meeting moved to Thursday");
const hits = await session.memory.query({ terms: ["thursday"], limit: 20 });
```

Memory needs the `MEMORY` permission in your
[manifest](https://docs.dev.glassly.ai/app-devs/core-concepts/miniapp-manifest.md). Without it every call
rejects with `PERMISSION_NOT_DECLARED`. `session.memory.hasPermission` reports
whether you declared it. Nothing here leaves the phone.

This is shared, user-visible data that other miniapps read. Write what a person
would recognize as a note about their day, not your miniapp's internal state.
State belongs in [`session.storage`](https://docs.dev.glassly.ai/app-devs/core-concepts/storage.md).

## Sessions are clock hours

A "session" is one clock hour that has entries. It's derived from entry
timestamps at read time; there is no stored session id, and `hourStart` (epoch
ms of the hour bucket) is what identifies one.

## Entries

| Field | Type | Notes |
|---|---|---|
| `id` | `string` | |
| `kind` | `"line" \| "note"` | A spoken transcript line, or a note. |
| `text` | `string` | |
| `at` | `number` | Epoch ms the entry happened. |
| `speakerId` | `string \| null` | Enrolled-speaker id (`spk_…`) when resolved. |
| `resolvedSpeakerName` | `string \| null?` | Display name from on-device speaker ID, when known. |
| `language` | `string \| null` | |
| `source` | `"voice" \| "ui" \| "auto"?` | How a note originated. Only meaningful for `kind: "note"`. |

## Writing

```typescript
await session.memory.appendLine({
  text: "and then we agreed on Thursday",
  speakerId: null,
  language: "en",
  at: Date.now(),
});

const note = await session.memory.addNote("Meeting moved to Thursday", "ui");
```

| Method | Returns | Notes |
|---|---|---|
| `appendLine({text, speakerId, language, at})` | `Promise<void>` | Append a spoken transcript line. |
| `addNote(text, source?, at?)` | `Promise<MemoryEntry \| null>` | `source` defaults to `"ui"`. `at` targets the hour the note belongs to; omit for now. Notes dedupe on normalized text within the same hour, and a duplicate (or empty) note resolves `null`. |
| `addSummary(summary)` | `Promise<void>` | Upsert the summary heading an hour, keyed by `hourStart`. A `MemorySummary` is `{hourStart, text, createdAt}`. |

## Reading

```typescript
const sessions = await session.memory.sessions();   // newest hour first
const recent = await session.memory.window(Date.now() - 3_600_000);
```

| Method | Returns | Notes |
|---|---|---|
| `sessions()` | `Promise<MemorySession[]>` | Every hour with entries, newest first. Each is `{hourStart, entries, summary, lineCount, noteCount}`. |
| `window(sinceMs, untilMs?)` | `Promise<MemoryEntry[]>` | Entries in `[sinceMs, untilMs)`, newest last. Uncapped, unlike `query`. |
| `summaries()` | `Promise<MemorySummary[]>` | Every hourly summary, newest hour first. |
| `pendingSummaryHour(nowMs?)` | `Promise<number \| null>` | The most recent completed hour that has lines but no summary, or `null`. |
| `exportText(scope, at?)` | `Promise<string>` | Plain-text export of a `"session"`, `"day"`, or `"all"`, for the OS share sheet. |

## Backups

`exportFile()` and `importFile()` move the whole timeline in and out as a JSON
file, the same backup Settings › Memory exports and imports. Both wait on the
user, so neither has a request timeout. They need host 0.3.5 or later.

```typescript
await session.memory.exportFile();                  // OS share sheet
const imported = await session.memory.importFile(); // system file picker
if (imported) console.log(`added ${imported.entries}, skipped ${imported.skipped}`);
```

| Method | Returns | Notes |
|---|---|---|
| `exportFile()` | `Promise<{success, cancelled?}>` | Writes every entry and summary to `glassly-memory-<date>.json` and opens the share sheet. |
| `importFile()` | `Promise<MemoryImportResult \| null>` | Merges the picked backup. Skips stored ids, notes whose text is already in the same hour, and hours that already have a summary. `null` when the user cancels; rejects with `INVALID_ARGUMENT` for a file that isn't a memory backup. |

## Searching

`query(q)` filters the whole timeline by time window and keyword. It's the shape
an LLM history-search tool wants, and results come back newest last, so slicing
keeps the most recent matches when the limit bites.

```typescript
const entries = await session.memory.query({
  sinceMs: Date.now() - 86_400_000,
  terms: ["corwin", "invoice"],
  limit: 40,
});
```

| `MemoryQuery` field | Type | What it does |
|---|---|---|
| `sinceMs` | `number?` | Inclusive lower bound. Omit for "from the beginning". |
| `untilMs` | `number?` | Inclusive upper bound. Omit for "until now". |
| `contains` | `string?` | Case-insensitive **exact** substring filter, for codes, URLs, and exact phrases. |
| `terms` | `string[]?` | Fuzzy any-of terms: an entry matches when any term matches, and a multi-word term needs all of its words. Matching tolerates the small misspellings speech-to-text produces for names ("Korwin" matches "Corwin"). Capped at 8 terms, ANDed with `contains`, and ignored by hosts that predate fuzzy search. |
| `limit` | `number?` | Max entries. Defaults to 60, capped at 200. Newest are kept. |

`search(q)` sends the same request and adds diagnostics:

```typescript
const { entries, windowCount } = await session.memory.search({ terms: ["thursday"] });
```

`windowCount` is how many entries fell inside the time window **before** keyword
filtering, which tells "the keyword matched nothing" apart from "the window was
empty". Prefer `search` from an LLM history-search tool so an empty result can
explain itself instead of triggering a blind retry. It's `undefined` on hosts
that predate fuzzy search.

## Deleting

| Method | Returns | Notes |
|---|---|---|
| `removeEntry(id)` | `Promise<boolean>` | `false` when the id is unknown. |
| `removeScope(scope, at)` | `Promise<void>` | Deletes every entry and summary in an hour (`"session"`) or a whole day (`"day"`) containing `at`. |
| `clear()` | `Promise<void>` | Drops the entire timeline: every entry and every summary, for every miniapp. |

`clear()` and `removeScope()` destroy data other miniapps wrote and the user can
see in Settings > Memory. Only call them in response to an explicit user action.
