Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions apps/server/src/kin/memory/Memory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,14 +325,21 @@ it.effect(
fixtureItem({
id: "unread",
title: "Never opened fixture",
due: "2026-11-21T19:00:00.000Z",
recorded_at: "2026-11-14T00:00:00.000Z",
}),
);
repository.files.set("deferrals/unreadable.md", "unreadable fixture");
repository.files.set("deferrals/broken.md", "---\nid: [\n---\n");
const program = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
INSERT INTO kin_trigger_settings (org_id, time_zone, morning_brief, evening_summary, dream, full_rebuild_weekday, owner_check_weekday, owner_check, quiet_hours_json)
VALUES (${orgA}, 'Asia/Kolkata', '08:30', '18:30', '02:00', 0, 5, '12:00', '{"from":"22:00","to":"07:00"}')
`;
const memory = yield* Memory.Memory;
yield* memory.rebuildIndex(orgA);
expect(yield* memory.readIndex(orgA)).not.toContain("## Due in 7 days");
expect(yield* memory.readIndex(orgA)).toContain("As of 2026-11-14T00:00:00.000Z");
expect(yield* memory.readIndex(orgA)).toContain("⚠ review");
const counts = repository.counts();
Expand Down Expand Up @@ -441,7 +448,29 @@ it.effect(
);
expect(messages.some((message) => message.includes("batch framing failed"))).toBe(true);
const sql = yield* SqlClient.SqlClient;
yield* sql`UPDATE kin_trigger_settings SET time_zone = 'UTC' WHERE org_id = ${orgA}`;
repository.commit();
yield* memory.prepareWakeup(orgA);
const utcIndex = yield* memory.readIndex(orgA);
yield* sql`UPDATE kin_trigger_settings SET time_zone = 'Invented/Invalid' WHERE org_id = ${orgA}`;
repository.commit();
yield* memory.prepareWakeup(orgA);
expect(yield* memory.readIndex(orgA)).toContain("As of ");
expect(yield* memory.readIndex(orgA)).toBe(utcIndex);
expect(messages.some((message) => message.includes("Invalid memory owner time zone"))).toBe(
true,
);
yield* sql`DROP TABLE kin_trigger_settings`;
yield* sql`DROP TABLE kin_memory_reads`;
repository.commit();
yield* memory.prepareWakeup(orgA);
expect(yield* memory.readIndex(orgA)).toContain("As of ");
expect(
messages.some((message) => message.includes("Could not load memory owner time zone")),
).toBe(true);
expect(
messages.some((message) => message.includes("Could not load memory read history")),
).toBe(true);
expect((yield* memory.readItem(orgA, KinMemoryItemId.make("extra-0"))).head.id).toBe(
"extra-0",
);
Expand Down
30 changes: 15 additions & 15 deletions apps/server/src/kin/memory/Memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import * as Semaphore from "effect/Semaphore";
import { isNonRepositoryGitStderr } from "../../vcs/gitErrors.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import * as MemoryCache from "./MemoryCache.ts";
import { buildIndex } from "./buildIndex.ts";
import { MemoryConfig } from "./MemoryConfig.ts";
import {
MemoryItemError,
Expand Down Expand Up @@ -142,8 +143,6 @@ const memoryGitEnv = Object.freeze({
});

const folders = ["objectives", "commitments", "deferrals", "decisions", "people", "claims"];
const week = 7 * 24 * 60 * 60 * 1000;
const oneLine = (value: string) => value.replace(/[\r\n\u2028\u2029]/g, " ");

const maxBlobBytes = 256 * 1024;

Expand Down Expand Up @@ -668,19 +667,20 @@ const make = Effect.gen(function* () {
),
}),
);
const counts = new Map<string, number>();
for (const { head } of snapshot.items) counts.set(head.id, (counts.get(head.id) ?? 0) + 1);
const entries = snapshot.items
.filter(({ head }) => now - (reads[head.id] ?? dateMillis(head.recorded_at)) < 8 * week)
.map(
({ head }) =>
`- [${head.kind}] ${oneLine(head.title)} (${oneLine(head.path)})${head.invalid_at !== null ? " [invalid]" : ""}${(counts.get(head.id) ?? 0) > 1 ? " [duplicate id]" : ""}${dateMillis(head.review_by) < now ? " ⚠ review" : ""}`,
);
const lines = [`As of ${DateTime.formatIso(DateTime.makeUnsafe(now))}`, "", "# Memory"];
const capacity = 200 - lines.length;
lines.push(...entries.slice(0, entries.length > capacity ? capacity - 1 : capacity));
if (entries.length > capacity) lines.push(`${entries.length - capacity + 1} more`);
snapshot.index = lines.join("\n") + "\n";
const ownerTimeZone = yield* cache.ownerTimeZone(orgId).pipe(
Effect.catchTags({
MemoryHistoryError: () =>
Effect.logWarning("Could not load memory owner time zone; using UTC", { orgId }).pipe(
Effect.as("UTC"),
),
}),
);
snapshot.index = buildIndex(
snapshot.items.map(({ head }) => head),
reads,
now,
ownerTimeZone,
);
const paths = yield* pathsFor(orgId);
yield* io(
orgId,
Expand Down
26 changes: 25 additions & 1 deletion apps/server/src/kin/memory/MemoryCache.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import type { KinMemoryItemId, KinOrgId, MemoryItemHead } from "@t3tools/contracts";
import {
KinTrigger,
type KinMemoryItemId,
type KinOrgId,
type MemoryItemHead,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
Expand All @@ -25,12 +30,15 @@ export class MemoryCache extends Context.Service<
orgId: KinOrgId,
id: KinMemoryItemId,
) => Effect.Effect<void, MemoryHistoryError>;
readonly ownerTimeZone: (orgId: KinOrgId) => Effect.Effect<string, MemoryHistoryError>;
readonly lastReads: (
orgId: KinOrgId,
) => Effect.Effect<Readonly<Record<string, number>>, MemoryHistoryError>;
}
>()("t3/kin/memory/MemoryCache") {}

const decodeTimeZone = Schema.decodeUnknownEffect(KinTrigger.fields.timeZone);

const make = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
return MemoryCache.of({
Expand All @@ -46,6 +54,22 @@ const make = Effect.gen(function* () {
Effect.mapError((cause) => new MemoryHistoryError({ orgId, cause })),
);
}),
ownerTimeZone: Effect.fn("MemoryCache.ownerTimeZone")(function* (orgId) {
const rows = yield* sql<{ time_zone: unknown }>`
SELECT time_zone FROM kin_trigger_settings WHERE org_id = ${orgId} ORDER BY org_id
`.pipe(
Effect.mapError(toPersistenceSqlError("MemoryCache.ownerTimeZone")),
Effect.mapError((cause) => new MemoryHistoryError({ orgId, cause })),
);
if (rows.length === 0) return "UTC";
return yield* decodeTimeZone(rows[0]?.time_zone).pipe(
Effect.catch(() =>
Effect.logWarning("Invalid memory owner time zone; using UTC", { orgId }).pipe(
Effect.as("UTC"),
),
),
);
}),
lastReads: Effect.fn("MemoryCache.lastReads")(function* (orgId) {
const rows = yield* sql<{ item_id: string; last_read_at: number }>`
SELECT item_id, last_read_at FROM kin_memory_reads WHERE org_id = ${orgId} ORDER BY item_id
Expand Down
29 changes: 29 additions & 0 deletions apps/server/src/kin/memory/buildIndex.golden.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
As of 2026-11-08T04:00:00.000Z

## Waiting on owner
- [deferral] Invented waiting (deferrals/waiting.md)

## Due in 7 days
- [deferral] Invented soon (deferrals/soon.md)
- [deferral] Invented future-ask (deferrals/future-ask.md)

## Open objectives
- [objective] Invented objective (objectives/objective.md)

## Open commitments
- [commitment] Invented commitment (commitments/commitment.md) ⚠ review

## Overdue
- [claim] Invented overdue (claims/overdue.md) ⚠ review

## Other memory
- [claim] Invented multiline title safe (claims/constructor.md)
- [claim] Invented duplicate (claims/duplicate.md) [duplicate id]
- [claim] Invented duplicate (claims/moved.md) [invalid] [duplicate id]
- [claim] Invented read (claims/read.md)
- [deferral] Invented undated-ask (deferrals/undated-ask.md)

## Misleading
- [claim] Invented misleading (claims/misleading.md) ⚠ review [misleading]

54 more items not listed; use memory_search
92 changes: 92 additions & 0 deletions apps/server/src/kin/memory/buildIndex.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { expect, it } from "@effect/vitest";
import { KinMemoryItemId, KinOrgId, MemoryItemHead } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import * as DateTime from "effect/DateTime";

import { buildIndex } from "./buildIndex.ts";

const now = Date.parse("2026-11-08T04:00:00.000Z");
const week = 7 * 24 * 60 * 60 * 1000;
const decodeHead = Schema.decodeSync(MemoryItemHead);
const item = (
id: string,
fields: Partial<MemoryItemHead> & { readonly misleading?: boolean } = {},
) => ({
...decodeHead({
id: KinMemoryItemId.make(id),
orgId: KinOrgId.make("fixture-org"),
path: `${fields.kind === "person" ? "people" : `${fields.kind ?? "claim"}s`}/${id}.md`,
kind: "claim",
title: `Invented ${id}`,
status: "open",
due: null,
recorded_at: "2026-11-01T00:00:00.000Z",
valid_from: "2026-11-01T00:00:00.000Z",
invalid_at: null,
superseded_by: null,
review_by: null,
said_by: "fixture-owner",
trust: "owner",
source: "https://example.invalid/fixture",
links: [],
...fields,
}),
...(fields.misleading === undefined ? {} : { misleading: fields.misleading }),
});

it("matches the bounded index golden, independently of input order, and fades only unread items", async () => {
const items = [
item("waiting", { kind: "deferral", on_due: "ask", due: "2026-11-08T04:00:00.000Z" }),
item("future-ask", { kind: "deferral", on_due: "ask", due: "2026-11-10" }),
item("undated-ask", { kind: "deferral", on_due: "ask" }),
item("soon", { kind: "deferral", due: "2026-11-09" }),
item("objective", { kind: "objective" }),
item("commitment", { kind: "commitment", due: "2026-11-07" }),
item("overdue", { review_by: "2026-11-07" }),
item("duplicate"),
item("duplicate", { path: "claims/moved.md", invalid_at: "2026-11-07" }),
item("misleading", { misleading: true, review_by: "2026-11-07" }),
item("unread", { recorded_at: DateTime.formatIso(DateTime.makeUnsafe(now - 8 * week)) }),
item("read", { recorded_at: "2026-01-01" }),
item("constructor", { title: "Invented multiline\ntitle\u2028safe" }),
];
const reads = { read: now - 8 * week + 1 };
const actual = buildIndex(items, reads, now, "Asia/Kolkata");
expect(buildIndex(items.toReversed(), reads, now, "Asia/Kolkata")).toBe(actual);
expect(actual).not.toContain("Invented unread");
const large = buildIndex(
Array.from({ length: 250 }, (_, n) => item(`fixture-${n.toString().padStart(3, "0")}`)),
{},
now,
"Asia/Kolkata",
);
expect(large.trimEnd().split("\n")).toHaveLength(200);
await expect(actual + "\n" + large.trimEnd().split("\n").at(-1) + "\n").toMatchFileSnapshot(
"./buildIndex.golden.txt",
);
});

it.each([
{ zone: "UTC", now: "2026-11-08T23:30:00Z", due: "2026-11-16T00:00:00Z", soon: false },
{ zone: "Asia/Kolkata", now: "2026-11-08T23:30:00Z", due: "2026-11-16T00:00:00Z", soon: true },
{
zone: "America/New_York",
now: "2026-03-07T17:00:00Z",
due: "2026-03-15T04:00:00Z",
soon: false,
},
{
zone: "America/New_York",
now: "2026-03-07T17:00:00Z",
due: "2026-03-15T03:59:59Z",
soon: true,
},
])("uses owner calendar days, including DST: $zone $due", ({ zone, now: time, due, soon }) => {
const result = buildIndex(
[item("boundary", { due, recorded_at: time })],
{},
Date.parse(time),
zone,
);
expect(result.includes("## Due in 7 days")).toBe(soon);
});
90 changes: 90 additions & 0 deletions apps/server/src/kin/memory/buildIndex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import type { MemoryItemHead } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";

import { memoryDateMillis } from "./frontMatter.ts";

const week = 7 * 24 * 60 * 60 * 1000;
const oneLine = (value: string) => value.replace(/[\r\n\u2028\u2029]/g, " ");
const compareText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
const dateOrder = (value: string | null) => {
const ms = memoryDateMillis(value);
return Number.isFinite(ms) ? ms : Infinity;
};

type IndexItem = MemoryItemHead & { readonly misleading?: boolean };

export function buildIndex(
items: ReadonlyArray<IndexItem>,
readHistory: Readonly<Record<string, number>>,
now: number,
ownerTimeZone: string,
): string {
const today = DateTime.startOf(DateTime.makeZonedUnsafe(now, { timeZone: ownerTimeZone }), "day");
const dueThrough = DateTime.toEpochMillis(DateTime.add(today, { days: 8 }));
const sections = [
"Waiting on owner",
"Due in 7 days",
"Open objectives",
"Open commitments",
"Overdue",
"Other memory",
"Misleading",
];
const counts = new Map<string, number>();
for (const item of items) counts.set(item.id, (counts.get(item.id) ?? 0) + 1);
const section = (item: IndexItem, due: number, overdue: boolean) => {
if (item.misleading) return 6;
if (item.status === "open" && item.invalid_at === null) {
if (item.on_due === "ask" && due <= now) return 0;
if (due >= now && due < dueThrough) return 1;
if (item.kind === "objective") return 2;
if (item.kind === "commitment") return 3;
}
if (overdue) return 4;
return 5;
};
const entries = items
.map((item) => ({
item,
due: dateOrder(item.due),
reviewBy: dateOrder(item.review_by),
recordedAt: memoryDateMillis(item.recorded_at),
}))
.filter(
({ item, recordedAt }) =>
now -
(Object.hasOwn(readHistory, item.id)
? (readHistory[item.id] ?? recordedAt)
: recordedAt) <
8 * week,
)
.map(({ item, due, reviewBy }) => {
const overdue = reviewBy < now || (item.status === "open" && due < now);
return { item, due, reviewBy, overdue, section: section(item, due, overdue) };
})
.sort(
(a, b) =>
a.section - b.section ||
a.due - b.due ||
a.reviewBy - b.reviewBy ||
compareText(a.item.id, b.item.id) ||
compareText(a.item.path, b.item.path) ||
compareText(a.item.title, b.item.title),
);
const lines = [`As of ${DateTime.formatIso(DateTime.makeUnsafe(now))}`];
let previousSection = -1;
for (const [index, { item, overdue, section: currentSection }] of entries.entries()) {
const header = currentSection === previousSection ? [] : ["", `## ${sections[currentSection]}`];
const reserved = index < entries.length - 1 ? 1 : 0;
if (lines.length + header.length + 1 + reserved > 200) {
lines.push(`${entries.length - index} more items not listed; use memory_search`);
break;
}
lines.push(
...header,
`- [${item.kind}] ${oneLine(item.title)} (${oneLine(item.path)})${item.invalid_at !== null ? " [invalid]" : ""}${(counts.get(item.id) ?? 0) > 1 ? " [duplicate id]" : ""}${overdue ? " ⚠ review" : ""}${item.misleading ? " [misleading]" : ""}`,
);
previousSection = currentSection;
}
return lines.join("\n") + "\n";
}
Loading
Loading