Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(memory): date imported mail by its send time and facts by local day

muterCaefcc03cca70
diff --git a/apps/node-services/src/memory/README.md b/apps/node-services/src/memory/README.md
index 47c39661..fe29f14d 100644
--- a/apps/node-services/src/memory/README.md
+++ b/apps/node-services/src/memory/README.md
@@ -175,6 +175,8 @@ Core configuration:
`system_notification` are extracted, and so is every message of a thread with a `self_sent` message; marketing,
subscriptions and drafts are not. Each window's Context line names its origin, so the one prompt knows a
transcript may not label speakers, mail must tell the sender from the user, and a notification may hold no facts.
+ A window's Event Date is its first Room message time, else its source date at local midnight; it is shown in the
+ process time zone, so a message sent just after midnight belongs to the Human's own day rather than the UTC one.
Consecutive Chunks form
windows of at most 3,000 characters, extracted with `apps/node-services/prompts/memory/facts/fact-extraction.md`
(the Hindsight concise prompt) at low reasoning effort. Up to 16 windows form one batch, and each batch runs as one
@@ -359,7 +361,10 @@ head, so a Wiki reference never points at the uploaded original while the Chunk
audio or video without a transcript do not enter the index.
Memory does not normalize Documents: it reads My pages and imported mail as the Markdown TeamHub stored in
`document_texts` (one River job per version), through `memory_source.personal_documents` and, for
-Documents whose indexed hash differs, `personal_document_markdown`. The normalizer TeamHub's job calls is
+Documents whose indexed hash differs, `personal_document_markdown`. A My pages Document is dated by its Version; an
+imported mail message by the send time in its `- Timestamp:` header and named by its `# subject` line, because TeamHub
+stores every message at the time of the import (the Version time and file name are used only when the header has no
+readable time or subject). The normalizer TeamHub's job calls is
`apps/node-services/src/document-normalizer`, served by LLM Wiki in a restricted worker thread of this process. It
converts PDF, DOC/DOCX, PPTX, XLSX, ODT/ODS/ODP, EPUB, EML/MHTML, Office templates and images into canonical Markdown.
Scanned PDFs and raster images use the Chinese and English OCR bundled with the dependencies; conversion needs no
diff --git a/apps/node-services/src/memory/date.ts b/apps/node-services/src/memory/date.ts
index b9f898f2..8298f3d5 100644
--- a/apps/node-services/src/memory/date.ts
+++ b/apps/node-services/src/memory/date.ts
@@ -46,6 +46,20 @@ function pad(value: number): string {
return String(value).padStart(2, "0");
}
+/** The instant as ISO 8601 in the process time zone, with its UTC offset. */
+export function localIsoString(instant: Date): string {
+ const offset = -instant.getTimezoneOffset();
+ const sign = offset < 0 ? "-" : "+";
+ const minutes = Math.abs(offset);
+ return `${localDate(instant)}T${[
+ instant.getHours(),
+ instant.getMinutes(),
+ instant.getSeconds(),
+ ]
+ .map((value) => pad(value))
+ .join(":")}${sign}${pad(Math.floor(minutes / 60))}:${pad(minutes % 60)}`;
+}
+
export function localMeetingTime(start: Date): string {
return [start.getHours(), start.getMinutes(), start.getSeconds()]
.map((value) => pad(value))
diff --git a/apps/node-services/src/memory/my-pages-chunk-sources.ts b/apps/node-services/src/memory/my-pages-chunk-sources.ts
index d00ae2d2..70788d0f 100644
--- a/apps/node-services/src/memory/my-pages-chunk-sources.ts
+++ b/apps/node-services/src/memory/my-pages-chunk-sources.ts
@@ -112,17 +112,25 @@ export async function syncMyPagesChunkSources(options: {
indexedContent.get(document.document_id);
if (content === undefined || !content.trim())
return { indexed: false, skipped: true };
+ // Imported mail is stored when it is imported; its header carries when it
+ // was sent and what it is about.
+ const mail: MailHeader =
+ document.origin_kind === "mail" ? mailHeader(content) : {};
try {
const source = documentRawSource({
identity,
documentId: document.document_id,
textSourceKind: document.text_source_kind,
textSourceId: document.text_source_id,
- title: document.title.trim() || document.filename.trim() || "Untitled",
+ title:
+ mail.title ||
+ document.title.trim() ||
+ document.filename.trim() ||
+ "Untitled",
filename: document.filename.trim() || "untitled",
mediaType: document.media_type,
originKind: document.origin_kind,
- date: localDate(document.created_at),
+ date: localDate(mail.sentAt ?? document.created_at),
markdown: content,
...(document.folder_path ? { folderPath: document.folder_path } : {}),
});
@@ -171,3 +179,24 @@ async function mapSequentially<T, R>(
}
return results;
}
+
+interface MailHeader {
+ sentAt?: Date;
+ title?: string;
+}
+
+/**
+ * The subject and send time TeamHub writes at the top of an imported message
+ * (`# <subject>` and `- Timestamp: <Date header>`). Either is absent when the
+ * message has none or its time cannot be read.
+ */
+export function mailHeader(markdown: string): MailHeader {
+ // The subject is the first line; a body heading never stands in for it.
+ const title = /^# ([^\n]+)/u.exec(markdown)?.[1]?.trim();
+ const stamp = /^- Timestamp: (.+)$/mu.exec(markdown)?.[1]?.trim();
+ const sentAt = stamp ? new Date(stamp) : undefined;
+ return {
+ ...(title ? { title } : {}),
+ ...(sentAt && Number.isFinite(sentAt.getTime()) ? { sentAt } : {}),
+ };
+}
diff --git a/apps/node-services/src/memory/session-fact-extraction.ts b/apps/node-services/src/memory/session-fact-extraction.ts
index d2843e66..9fa1d26a 100644
--- a/apps/node-services/src/memory/session-fact-extraction.ts
+++ b/apps/node-services/src/memory/session-fact-extraction.ts
@@ -15,6 +15,7 @@ import {
type ModelChain,
} from "../runtime-model-call.js";
import { runMemoryModelChain, type MemoryModelChainRunner } from "./llm.js";
+import { localIsoString, localTimeZone } from "./date.js";
import { promptRoot } from "./paths.js";
import type { SourceChunk } from "./search/chunks.js";
@@ -144,8 +145,10 @@ export function factUserMessage(
month: "long",
day: "2-digit",
year: "numeric",
- timeZone: "UTC",
- })} (${eventDate.toISOString()})`
+ // Room messages are stamped in UTC; a message sent just after
+ // midnight belongs to the Human's own day.
+ timeZone: localTimeZone(),
+ })} (${localIsoString(eventDate)})`
: "Unknown";
return `Extract facts from the following chunk.
diff --git a/apps/node-services/src/memory/session-fact-index.ts b/apps/node-services/src/memory/session-fact-index.ts
index dfe4777d..d44f0be4 100644
--- a/apps/node-services/src/memory/session-fact-index.ts
+++ b/apps/node-services/src/memory/session-fact-index.ts
@@ -21,6 +21,7 @@ import {
} from "./session-fact-extraction.js";
import { isComputerOffline } from "../runtime-model-call.js";
import { memoryDatabase } from "./database.js";
+import { localDateWindow } from "./date.js";
import { memoryLogger } from "./run-telemetry.js";
import { sha256Hex } from "@linger/service-kit/node";
@@ -565,6 +566,9 @@ function eventDate(
window: FactWindow,
): Date | undefined {
const at = roomMessageAt(source, window.chunks[0]!.start + 1)?.mentionedAt;
- const value = at ?? (source.date ? `${source.date}T00:00:00Z` : undefined);
- return value ? new Date(value) : undefined;
+ if (at) return new Date(at);
+ // A source dated by its day, such as mail, starts at that day's local midnight.
+ return source.date
+ ? new Date(localDateWindow(source.date).startIso)
+ : undefined;
}
diff --git a/apps/node-services/tests/memory/my-pages-chunk-sources.test.ts b/apps/node-services/tests/memory/my-pages-chunk-sources.test.ts
index d7eece63..45a02e80 100644
--- a/apps/node-services/tests/memory/my-pages-chunk-sources.test.ts
+++ b/apps/node-services/tests/memory/my-pages-chunk-sources.test.ts
@@ -1,7 +1,10 @@
import fs from "node:fs/promises";
import type postgres from "postgres";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { syncMyPagesChunkSources } from "../../src/memory/my-pages-chunk-sources.js";
+import {
+ mailHeader,
+ syncMyPagesChunkSources,
+} from "../../src/memory/my-pages-chunk-sources.js";
import { contentHash } from "../../src/memory/search/source-store.js";
const identity = {
@@ -27,7 +30,7 @@ const scanStartedAt = new Date("2026-09-29T00:00:00Z");
afterEach(() => vi.restoreAllMocks());
-function fixture(cached = false, documents = [document]) {
+function fixture(cached = false, documents = [document], text = markdown) {
const sql = vi.fn(async (parts: TemplateStringsArray) => {
const query = parts.join("?");
if (query.includes("clock_timestamp() AS scan_started_at"))
@@ -36,7 +39,7 @@ function fixture(cached = false, documents = [document]) {
if (query.includes("memory_source.personal_document_markdown("))
return documents.map((entry) => ({
document_id: entry.document_id,
- markdown,
+ markdown: text,
}));
if (query.includes("version.content"))
return cached
@@ -103,6 +106,81 @@ describe("read-only Document chunk ingestion", () => {
expect(source.metadata).not.toHaveProperty("folder_path");
});
+ it("dates and names imported mail by its own header, not the import", async () => {
+ const message = [
+ "# Re: Atlas statement of work",
+ "",
+ "- Provider: gmail",
+ "- Message ID: `m1`",
+ "- Thread ID: `t1`",
+ // 23:30 in UTC is already Jul 3 in the tests' time zone.
+ "- Timestamp: Thu, 2 Jul 2026 15:30:00 -0800",
+ "- Direction: inbound (received by mailbox owner)",
+ "- From: Tom <[email protected]>",
+ "",
+ "# Not the subject",
+ "",
+ "Please send the revised plan next Tuesday.",
+ "",
+ ].join("\n");
+ const test = fixture(
+ false,
+ [
+ {
+ ...document,
+ origin_kind: "mail",
+ folder_path: "",
+ title: "gmail-message-1.md",
+ filename: "gmail-message-1.md",
+ },
+ ],
+ message,
+ );
+ await syncMyPagesChunkSources(test.options);
+ expect(test.ingest).toHaveBeenCalledWith(
+ expect.objectContaining({
+ originKind: "mail",
+ date: "2026-07-03",
+ title: "Re: Atlas statement of work",
+ }),
+ message,
+ );
+ });
+
+ it("keeps the import time and file name when the mail header has neither", async () => {
+ const message = "# \n\n- Timestamp: unknown\n\nBody.\n";
+ const test = fixture(
+ false,
+ [
+ {
+ ...document,
+ origin_kind: "mail",
+ folder_path: "",
+ title: "gmail-message-2.md",
+ },
+ ],
+ message,
+ );
+ await syncMyPagesChunkSources(test.options);
+ expect(test.ingest).toHaveBeenCalledWith(
+ expect.objectContaining({
+ date: "2026-09-30",
+ title: "gmail-message-2.md",
+ }),
+ message,
+ );
+ });
+
+ it("reads the mail header only from imported mail", async () => {
+ const page = "# My notes\n\n- Timestamp: Thu, 2 Jul 2026 15:30:00 +0800\n";
+ const test = fixture(false, [document], page);
+ await syncMyPagesChunkSources(test.options);
+ expect(test.ingest).toHaveBeenCalledWith(
+ expect.objectContaining({ date: "2026-09-30", title: "Document" }),
+ page,
+ );
+ });
+
it("reads no Markdown for a Document whose indexed text is current", async () => {
const test = fixture(true);
await syncMyPagesChunkSources(test.options);
@@ -165,3 +243,21 @@ describe("read-only Document chunk ingestion", () => {
expect(ingest).not.toHaveBeenCalled();
});
});
+
+describe("mail header", () => {
+ it("reads RFC 2822 and RFC 3339 send times and ignores unreadable ones", () => {
+ for (const [stamp, iso] of [
+ ["Sun, 4 Oct 2026 08:11:23 -0700 (MST)", "2026-10-04T15:11:23.000Z"],
+ ["Tue, 20 Oct 2026 03:44:40 -0500", "2026-10-20T08:44:40.000Z"],
+ ["2026-11-09T06:05:12Z", "2026-11-09T06:05:12.000Z"],
+ ] as const)
+ expect(
+ mailHeader(
+ `# Subject\n\n- Timestamp: ${stamp}\n`,
+ ).sentAt?.toISOString(),
+ ).toBe(iso);
+ expect(mailHeader("# Subject\n\n- Timestamp: unknown\n")).toEqual({
+ title: "Subject",
+ });
+ });
+});
diff --git a/apps/node-services/tests/memory/session-fact-extraction.test.ts b/apps/node-services/tests/memory/session-fact-extraction.test.ts
index a800e472..f8d04c42 100644
--- a/apps/node-services/tests/memory/session-fact-extraction.test.ts
+++ b/apps/node-services/tests/memory/session-fact-extraction.test.ts
@@ -70,7 +70,22 @@ describe("Session fact extraction", () => {
"Conversation session on 2024-03-14",
),
).toBe(
- "Extract facts from the following chunk.\n\nChunk: 1/2\nEvent Date: Thursday, March 14, 2024 (2024-03-14T09:00:00.000Z)\nContext: Conversation session on 2024-03-14\n\nContent:\nContent here",
+ "Extract facts from the following chunk.\n\nChunk: 1/2\nEvent Date: Thursday, March 14, 2024 (2024-03-14T17:00:00+08:00)\nContext: Conversation session on 2024-03-14\n\nContent:\nContent here",
+ );
+ });
+
+ it("dates a message by the Human's day, not by UTC", () => {
+ // 01:30 on Thursday in the tests' time zone is still Wednesday in UTC.
+ expect(
+ factUserMessage(
+ { text: "See you tomorrow." },
+ 0,
+ 1,
+ new Date("2024-03-13T17:30:00Z"),
+ "",
+ ),
+ ).toContain(
+ "Event Date: Thursday, March 14, 2024 (2024-03-14T01:30:00+08:00)",
);
});
diff --git a/apps/node-services/tests/memory/session-facts.postgres.test.ts b/apps/node-services/tests/memory/session-facts.postgres.test.ts
index b2124d35..79dcd2b9 100644
--- a/apps/node-services/tests/memory/session-facts.postgres.test.ts
+++ b/apps/node-services/tests/memory/session-facts.postgres.test.ts
@@ -18,7 +18,10 @@ import {
storePocketNoteSource,
} from "../../src/memory/search/source-store.js";
import { SessionFactIndex } from "../../src/memory/session-fact-index.js";
-import type { ExtractedFact } from "../../src/memory/session-fact-extraction.js";
+import {
+ factUserMessage,
+ type ExtractedFact,
+} from "../../src/memory/session-fact-extraction.js";
import { readTimelineEvents } from "../../src/memory/graph-visualization.js";
// Explicit opt-in: never reads TEAMHUB_DATABASE_URL or the application's .env.
@@ -386,4 +389,49 @@ describe.runIf(Boolean(databaseUrl))("Session facts in PostgreSQL", () => {
speaker: null,
});
});
+ it("dates mail facts by the day the mail was sent", async () => {
+ // Sent late on Jul 2 in California, already Jul 3 in the tests' time zone;
+ // syncMyPagesChunkSources dates the source by this header, not the import.
+ const markdown =
+ "# Revised plan\n\n- Provider: gmail\n- Message ID: `m1`\n- Thread ID: `t1`\n- Timestamp: Thu, 2 Jul 2026 15:30:00 -0800\n- Direction: inbound\n- From: [email protected]\n- Class: direct_inbound\n\nPlease send the revised plan next Tuesday.\n";
+ await chunks.indexDatabaseSource(
+ documentRawSource({
+ identity,
+ documentId: "document_mail",
+ textSourceKind: "file_version",
+ textSourceId: "version_mail",
+ title: "Revised plan",
+ filename: "gmail-message-1.md",
+ mediaType: "text/markdown",
+ originKind: "mail",
+ date: "2026-07-03",
+ markdown,
+ }),
+ markdown,
+ );
+ const messages: string[] = [];
+ const dated = new SessionFactIndex({
+ sql: indexSql,
+ extract: async (batch) =>
+ new Map(
+ batch.map((item) => {
+ messages.push(
+ factUserMessage(
+ item.window,
+ item.index,
+ item.total,
+ item.eventDate,
+ item.context,
+ ),
+ );
+ return [item.window.sha256, []];
+ }),
+ ),
+ });
+ expect((await dated.syncAgent(identity.agent_id)).extracted).toBe(1);
+ // "Next Tuesday" is resolved against the send day at local midnight.
+ expect(messages[0]).toContain(
+ "Event Date: Friday, July 03, 2026 (2026-07-03T00:00:00+08:00)",
+ );
+ });
});
diff --git a/apps/teamhub/migrations/00864_index_mail_by_send_time.sql b/apps/teamhub/migrations/00864_index_mail_by_send_time.sql
new file mode 100644
index 00000000..98a9e437
--- /dev/null
+++ b/apps/teamhub/migrations/00864_index_mail_by_send_time.sql
@@ -0,0 +1,11 @@
+-- +goose Up
+-- Memory now dates imported mail by its send time and names it by its
+-- subject instead of the time and file name of the import. An indexed source
+-- is rebuilt only when its text changes, so mail indexed before stays dated by
+-- its import: drop it, with its versions, chunks and Session facts, and the
+-- next sync indexes and extracts it again.
+DELETE FROM memory_index.sources WHERE origin_kind = 'mail';
+
+-- +goose Down
+-- The dropped mail index is rebuilt by the next sync.
+SELECT 1;