From bcc7794121e12e7c8d9fc04f2ddbe5dc98e36741 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:16:19 +0530 Subject: [PATCH 1/3] feat(kin): build memory index and freshness defaults (TRIG-12) --- apps/server/src/kin/memory/Memory.test.ts | 7 ++ apps/server/src/kin/memory/Memory.ts | 25 +++--- apps/server/src/kin/memory/MemoryCache.ts | 10 +++ .../src/kin/memory/buildIndex.golden.txt | 25 ++++++ apps/server/src/kin/memory/buildIndex.test.ts | 89 +++++++++++++++++++ apps/server/src/kin/memory/buildIndex.ts | 84 +++++++++++++++++ apps/server/src/kin/memory/freshness.test.ts | 30 +++++++ apps/server/src/kin/memory/freshness.ts | 24 +++++ docs/kin/specs/lead.md | 4 +- docs/kin/specs/triggers.md | 4 +- packages/contracts/src/kinTriggers.ts | 8 +- 11 files changed, 289 insertions(+), 21 deletions(-) create mode 100644 apps/server/src/kin/memory/buildIndex.golden.txt create mode 100644 apps/server/src/kin/memory/buildIndex.test.ts create mode 100644 apps/server/src/kin/memory/buildIndex.ts create mode 100644 apps/server/src/kin/memory/freshness.test.ts create mode 100644 apps/server/src/kin/memory/freshness.ts diff --git a/apps/server/src/kin/memory/Memory.test.ts b/apps/server/src/kin/memory/Memory.test.ts index cfb90d839e580..0aa3a70faca32 100644 --- a/apps/server/src/kin/memory/Memory.test.ts +++ b/apps/server/src/kin/memory/Memory.test.ts @@ -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(); diff --git a/apps/server/src/kin/memory/Memory.ts b/apps/server/src/kin/memory/Memory.ts index 2a81aa46fe482..6c572feaaf853 100644 --- a/apps/server/src/kin/memory/Memory.ts +++ b/apps/server/src/kin/memory/Memory.ts @@ -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, @@ -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; @@ -668,19 +667,17 @@ const make = Effect.gen(function* () { ), }), ); - const counts = new Map(); - 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 ownerTimeZone = yield* cache + .ownerTimeZone(orgId) + .pipe( + Effect.mapError((cause) => new MemoryError({ orgId, operation: "indexTimeZone", cause })), ); - 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"; + snapshot.index = buildIndex( + snapshot.items.map(({ head }) => head), + reads, + now, + ownerTimeZone, + ); const paths = yield* pathsFor(orgId); yield* io( orgId, diff --git a/apps/server/src/kin/memory/MemoryCache.ts b/apps/server/src/kin/memory/MemoryCache.ts index b88cdbac61c90..b00640c456c3b 100644 --- a/apps/server/src/kin/memory/MemoryCache.ts +++ b/apps/server/src/kin/memory/MemoryCache.ts @@ -25,6 +25,7 @@ export class MemoryCache extends Context.Service< orgId: KinOrgId, id: KinMemoryItemId, ) => Effect.Effect; + readonly ownerTimeZone: (orgId: KinOrgId) => Effect.Effect; readonly lastReads: ( orgId: KinOrgId, ) => Effect.Effect>, MemoryHistoryError>; @@ -46,6 +47,15 @@ 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: string }>` + 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 })), + ); + return rows[0]?.time_zone ?? "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 diff --git a/apps/server/src/kin/memory/buildIndex.golden.txt b/apps/server/src/kin/memory/buildIndex.golden.txt new file mode 100644 index 0000000000000..b171052091bee --- /dev/null +++ b/apps/server/src/kin/memory/buildIndex.golden.txt @@ -0,0 +1,25 @@ +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) + +## 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) + +## Misleading +- [claim] Invented misleading (claims/misleading.md) ⚠ review [misleading] diff --git a/apps/server/src/kin/memory/buildIndex.test.ts b/apps/server/src/kin/memory/buildIndex.test.ts new file mode 100644 index 0000000000000..c8854188e4062 --- /dev/null +++ b/apps/server/src/kin/memory/buildIndex.test.ts @@ -0,0 +1,89 @@ +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 & { 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" }), + 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"); + await expect(actual).toMatchFileSnapshot("./buildIndex.golden.txt"); + 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); + expect(large).toContain("54 more\n"); +}); + +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); +}); diff --git a/apps/server/src/kin/memory/buildIndex.ts b/apps/server/src/kin/memory/buildIndex.ts new file mode 100644 index 0000000000000..3c244b2db972e --- /dev/null +++ b/apps/server/src/kin/memory/buildIndex.ts @@ -0,0 +1,84 @@ +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, + readHistory: Readonly>, + 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(); + for (const item of items) counts.set(item.id, (counts.get(item.id) ?? 0) + 1); + const overdue = (item: IndexItem) => + dateOrder(item.review_by) < now || (item.status === "open" && dateOrder(item.due) < now); + const section = (item: IndexItem) => { + if (item.misleading) return 6; + if (item.status === "open" && item.invalid_at === null) { + if (item.on_due === "ask") return 0; + const due = dateOrder(item.due); + if (due >= now && due < dueThrough) return 1; + if (item.kind === "objective") return 2; + if (item.kind === "commitment") return 3; + } + if (overdue(item)) return 4; + return 5; + }; + const entries = items + .filter( + (item) => + now - + (Object.hasOwn(readHistory, item.id) + ? (readHistory[item.id] ?? memoryDateMillis(item.recorded_at)) + : memoryDateMillis(item.recorded_at)) < + 8 * week, + ) + .map((item) => ({ item, section: section(item) })) + .sort( + (a, b) => + a.section - b.section || + dateOrder(a.item.due) - dateOrder(b.item.due) || + dateOrder(a.item.review_by) - dateOrder(b.item.review_by) || + 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, 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`); + 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(item) ? " ⚠ review" : ""}${item.misleading ? " [misleading]" : ""}`, + ); + previousSection = currentSection; + } + return lines.join("\n") + "\n"; +} diff --git a/apps/server/src/kin/memory/freshness.test.ts b/apps/server/src/kin/memory/freshness.test.ts new file mode 100644 index 0000000000000..bdda2388abc4e --- /dev/null +++ b/apps/server/src/kin/memory/freshness.test.ts @@ -0,0 +1,30 @@ +import { expect, it } from "@effect/vitest"; +import type { MemoryItemKind } from "@t3tools/contracts"; + +import { defaultReviewBy } from "./freshness.ts"; + +const cases: ReadonlyArray<{ + kind: MemoryItemKind; + due: string | null; + milestone?: string | null; + expected: string | null; +}> = [ + { kind: "person", due: null, expected: "2027-02-06T04:00:00.000Z" }, + { kind: "claim", due: null, expected: "2026-12-08T04:00:00.000Z" }, + { kind: "decision", due: "2026-11-09", expected: null }, + { kind: "commitment", due: "2026-11-09", expected: "2026-11-09" }, + { kind: "deferral", due: "2026-11-09T10:00+05:30", expected: "2026-11-09T10:00+05:30" }, + { kind: "deferral", due: null, expected: null }, + { kind: "objective", due: "2026-12-01", milestone: "2026-11-15", expected: "2026-11-15" }, + { kind: "objective", due: "2026-12-01", expected: "2026-12-01" }, + { kind: "objective", due: null, expected: null }, +]; + +it.each(cases)( + "defaults $kind freshness ($due, $milestone)", + ({ kind, due, milestone, expected }) => { + expect(defaultReviewBy({ kind, due }, Date.parse("2026-11-08T04:00:00.000Z"), milestone)).toBe( + expected, + ); + }, +); diff --git a/apps/server/src/kin/memory/freshness.ts b/apps/server/src/kin/memory/freshness.ts new file mode 100644 index 0000000000000..3ef38bb4b7160 --- /dev/null +++ b/apps/server/src/kin/memory/freshness.ts @@ -0,0 +1,24 @@ +import type { MemoryItemFrontMatter } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; + +const day = 24 * 60 * 60 * 1000; + +export function defaultReviewBy( + item: Pick, + now: number, + nextMilestone: string | null = null, +): string | null { + switch (item.kind) { + case "person": + return DateTime.formatIso(DateTime.makeUnsafe(now + 90 * day)); + case "claim": + return DateTime.formatIso(DateTime.makeUnsafe(now + 30 * day)); + case "objective": + return nextMilestone ?? item.due; + case "commitment": + case "deferral": + return item.due; + case "decision": + return null; + } +} diff --git a/docs/kin/specs/lead.md b/docs/kin/specs/lead.md index cd1b7c86552a8..5435176570191 100644 --- a/docs/kin/specs/lead.md +++ b/docs/kin/specs/lead.md @@ -372,7 +372,7 @@ Writer rules, enforced in code on `stage`: - Paths: only `objectives/`, `commitments/`, `deferrals/`, `decisions/`, `people/`, `claims/` and `journal/`. `rules.md` is refused. `INDEX.md` is written only by `rebuildIndex`. `README.md` is never touched. - No deletes. `invalidate` sets `invalid_at`; `supersede` sets the old item's `superseded_by` and `status: superseded` and creates the new one. - Provenance comes from the event, not the model. The writer looks up `sourceEventId` in the current batch and sets `said_by`, `source` and `trust` from the event's `provenance`. Owner → `owner`, member → `member`, webhook or outside text → `external`, worker suggestion → `agent`. The lead may lower trust but never raise it. A member's statement that reads like a rule is stored under `claims/`. -- `review_by` defaults by kind: person 90 days, commitment and deferral at `due`, decision `null`, objective and claim 30 days unless given. +- `review_by` defaults by kind: person 90 days, commitment and deferral at `due`, decision `null`, claim 30 days; objective at the next milestone date (falling back to `due`, then `null`) unless given. - Contradictions: if an open item of the same kind shares a link or id and says something different, and `supersedes` was not passed, `stage` fails with `MemoryConflict { existingId }`. The lead then supersedes (same source, newer) or posts a question to the owner. - Secret scan: before commit, the staged diff goes through `MemorySecretScan.check` (triggers spec). A hit refuses the whole commit, keeps the journal line "Commit refused: possible secret in ", and tells the owner. @@ -394,7 +394,7 @@ The read side pins the server-owned writer repository’s HEAD at wake-up (or fi `readItem` best-effort records integer-millisecond last-read times in Kin’s `kin_memory_reads` table, keyed by organization and item id so moves preserve history. Failed history writes are logged without failing the read. Never-read items use `recorded_at` as the baseline; index generation and queries do not count as reading an item. At eight weeks unread, items leave only the index, not search or git. Rebuilds use original heads, cap the index at 200 physical lines including the `As of ` first line, and flag invalid and overdue items. TRIG-12 extends this builder with sections, ordering and freshness defaults; no writer methods or automatic defaults are part of LEAD-2. -The generated index is derived from HEAD, not read-checkout files; committing it belongs to LEAD-3 or TRIG-12, not LEAD-2. +The generated index is derived from HEAD, not read-checkout files; LEAD-3 commits it; TRIG-12 only builds it, without a git write. ### The journal diff --git a/docs/kin/specs/triggers.md b/docs/kin/specs/triggers.md index 407ece3c76a52..fd9448ae3ece7 100644 --- a/docs/kin/specs/triggers.md +++ b/docs/kin/specs/triggers.md @@ -264,13 +264,15 @@ All are plain code. They write memory only through the LEAD queue as code-only e **`review_by` defaults** are filled at write time by `freshness.ts`: - person: +90 days; -- objective: next milestone date; +- objective: next milestone date supplied by the writer, falling back to `due`, then null; - commitment and deferral: `due`; - decision: null; - claim: +30 days. **`INDEX.md` is built by code**, not by the model (`buildIndex.ts`), from the front-matter cache. It has at most 200 lines and an `As of ` first line. Sections: Waiting on owner, due in 7 days, open objectives, open commitments, overdue (flagged `⚠ review`). Items flagged misleading drop to the end with a mark. Items unread for 8 weeks are left out, using last-read timestamps that LEAD's Memory read path records in Kin's DB (`kin_memory_reads`), not in git. Never-read items use `recorded_at` as the baseline. +The builder takes item heads (optionally marked `misleading` by the caller), last-read integer milliseconds, caller-supplied `now` and the owner's IANA zone. Each item appears once, in the first matching section; open, valid `on_due: ask` items mean Waiting on owner. Due in 7 days includes today through the seventh following owner-calendar date (exclusive midnight of day 8); front-matter date-only values still mean UTC midnight. Other items remain in Other memory; misleading items go last. Within each section, order is due, review date (missing dates last), id, path, then title, using ordinal string order. Overdue due dates on open items and overdue review dates are flagged. The cap includes headings and the omitted-item count. Memory reads the owner's zone from `kin_trigger_settings`, using UTC only before settings exist. Freshness defaults are a pure helper for LEAD-3 to apply only when `review_by` was omitted; explicit null is preserved. + **Contradiction checks** at write time are LEAD's (Memory writer). Dreams list the ones they find. ### Dreaming pipeline (one per org per night) diff --git a/packages/contracts/src/kinTriggers.ts b/packages/contracts/src/kinTriggers.ts index 01deb882f5465..98c6eabc94daa 100644 --- a/packages/contracts/src/kinTriggers.ts +++ b/packages/contracts/src/kinTriggers.ts @@ -2,7 +2,7 @@ import * as Schema from "effect/Schema"; import { NonNegativeInt, ScheduledTaskId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { KinOrgId, KinPersonId } from "./kinChat.ts"; -import { CanonicalUtcTimestamp } from "./kinLead.ts"; +import { CanonicalUtcTimestamp, KinMemoryItemId } from "./kinLead.ts"; import { ScheduledTaskUpsertSchedule, ScheduledTaskWebhookDeliveryId } from "./scheduledTask.ts"; const [interval, fixedTime, once] = ScheduledTaskUpsertSchedule.members; @@ -53,13 +53,13 @@ export type KinTriggerSchedule = typeof KinTriggerSchedule.Type; export const KinTriggerSubject = Schema.Union([ Schema.Struct({ type: Schema.Literal("deferral"), - itemId: TrimmedNonEmptyString, + itemId: KinMemoryItemId, phase: Schema.Literals(["heads_up", "due"]), }), - Schema.Struct({ type: Schema.Literal("reminder"), itemId: TrimmedNonEmptyString }), + Schema.Struct({ type: Schema.Literal("reminder"), itemId: KinMemoryItemId }), Schema.Struct({ type: Schema.Literal("followup"), - itemId: TrimmedNonEmptyString, + itemId: KinMemoryItemId, person: KinPersonId, }), Schema.Struct({ type: Schema.Literal("routine"), routine: KinRoutine }), From c76caa79be60a2d8a8cdbe62ec57c339933271df Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 8 Nov 2026 02:00:00 +0530 Subject: [PATCH 2/3] fix(kin): honor freshness defaults and recover memory index reads --- apps/server/src/kin/memory/Memory.test.ts | 22 ++++++++++++ apps/server/src/kin/memory/Memory.ts | 13 ++++--- apps/server/src/kin/memory/MemoryCache.ts | 20 +++++++++-- .../src/kin/memory/buildIndex.golden.txt | 4 +++ apps/server/src/kin/memory/buildIndex.test.ts | 9 +++-- apps/server/src/kin/memory/buildIndex.ts | 36 +++++++++++-------- apps/server/src/kin/memory/freshness.test.ts | 24 ++++++++++--- apps/server/src/kin/memory/freshness.ts | 14 +++++--- docs/kin/specs/lead.md | 2 +- docs/kin/specs/triggers.md | 4 +-- 10 files changed, 109 insertions(+), 39 deletions(-) diff --git a/apps/server/src/kin/memory/Memory.test.ts b/apps/server/src/kin/memory/Memory.test.ts index 0aa3a70faca32..5c374c729d76f 100644 --- a/apps/server/src/kin/memory/Memory.test.ts +++ b/apps/server/src/kin/memory/Memory.test.ts @@ -448,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", ); diff --git a/apps/server/src/kin/memory/Memory.ts b/apps/server/src/kin/memory/Memory.ts index 6c572feaaf853..3ccdeb7612942 100644 --- a/apps/server/src/kin/memory/Memory.ts +++ b/apps/server/src/kin/memory/Memory.ts @@ -667,11 +667,14 @@ const make = Effect.gen(function* () { ), }), ); - const ownerTimeZone = yield* cache - .ownerTimeZone(orgId) - .pipe( - Effect.mapError((cause) => new MemoryError({ orgId, operation: "indexTimeZone", cause })), - ); + 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, diff --git a/apps/server/src/kin/memory/MemoryCache.ts b/apps/server/src/kin/memory/MemoryCache.ts index b00640c456c3b..0d062391cdcfd 100644 --- a/apps/server/src/kin/memory/MemoryCache.ts +++ b/apps/server/src/kin/memory/MemoryCache.ts @@ -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"; @@ -32,6 +37,8 @@ export class MemoryCache extends Context.Service< } >()("t3/kin/memory/MemoryCache") {} +const decodeTimeZone = Schema.decodeUnknownEffect(KinTrigger.fields.timeZone); + const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; return MemoryCache.of({ @@ -48,13 +55,20 @@ const make = Effect.gen(function* () { ); }), ownerTimeZone: Effect.fn("MemoryCache.ownerTimeZone")(function* (orgId) { - const rows = yield* sql<{ time_zone: string }>` + 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 })), ); - return rows[0]?.time_zone ?? "UTC"; + 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 }>` diff --git a/apps/server/src/kin/memory/buildIndex.golden.txt b/apps/server/src/kin/memory/buildIndex.golden.txt index b171052091bee..1687f277312b8 100644 --- a/apps/server/src/kin/memory/buildIndex.golden.txt +++ b/apps/server/src/kin/memory/buildIndex.golden.txt @@ -5,6 +5,7 @@ As of 2026-11-08T04:00:00.000Z ## 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) @@ -20,6 +21,9 @@ As of 2026-11-08T04:00:00.000Z - [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 diff --git a/apps/server/src/kin/memory/buildIndex.test.ts b/apps/server/src/kin/memory/buildIndex.test.ts index c8854188e4062..3f3b1f3ac6f7d 100644 --- a/apps/server/src/kin/memory/buildIndex.test.ts +++ b/apps/server/src/kin/memory/buildIndex.test.ts @@ -36,7 +36,9 @@ const item = ( 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" }), + 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" }), @@ -50,7 +52,6 @@ it("matches the bounded index golden, independently of input order, and fades on ]; const reads = { read: now - 8 * week + 1 }; const actual = buildIndex(items, reads, now, "Asia/Kolkata"); - await expect(actual).toMatchFileSnapshot("./buildIndex.golden.txt"); expect(buildIndex(items.toReversed(), reads, now, "Asia/Kolkata")).toBe(actual); expect(actual).not.toContain("Invented unread"); const large = buildIndex( @@ -60,7 +61,9 @@ it("matches the bounded index golden, independently of input order, and fades on "Asia/Kolkata", ); expect(large.trimEnd().split("\n")).toHaveLength(200); - expect(large).toContain("54 more\n"); + await expect(actual + "\n" + large.trimEnd().split("\n").at(-1) + "\n").toMatchFileSnapshot( + "./buildIndex.golden.txt", + ); }); it.each([ diff --git a/apps/server/src/kin/memory/buildIndex.ts b/apps/server/src/kin/memory/buildIndex.ts index 3c244b2db972e..c2518402f0b7a 100644 --- a/apps/server/src/kin/memory/buildIndex.ts +++ b/apps/server/src/kin/memory/buildIndex.ts @@ -32,51 +32,57 @@ export function buildIndex( ]; const counts = new Map(); for (const item of items) counts.set(item.id, (counts.get(item.id) ?? 0) + 1); - const overdue = (item: IndexItem) => - dateOrder(item.review_by) < now || (item.status === "open" && dateOrder(item.due) < now); - const section = (item: IndexItem) => { + 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") return 0; - const due = dateOrder(item.due); + 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(item)) return 4; + 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) => + ({ item, recordedAt }) => now - (Object.hasOwn(readHistory, item.id) - ? (readHistory[item.id] ?? memoryDateMillis(item.recorded_at)) - : memoryDateMillis(item.recorded_at)) < + ? (readHistory[item.id] ?? recordedAt) + : recordedAt) < 8 * week, ) - .map((item) => ({ item, section: section(item) })) + .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 || - dateOrder(a.item.due) - dateOrder(b.item.due) || - dateOrder(a.item.review_by) - dateOrder(b.item.review_by) || + 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, section: currentSection }] of entries.entries()) { + 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`); + 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(item) ? " ⚠ review" : ""}${item.misleading ? " [misleading]" : ""}`, + `- [${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; } diff --git a/apps/server/src/kin/memory/freshness.test.ts b/apps/server/src/kin/memory/freshness.test.ts index bdda2388abc4e..44ad21a88993e 100644 --- a/apps/server/src/kin/memory/freshness.test.ts +++ b/apps/server/src/kin/memory/freshness.test.ts @@ -7,6 +7,7 @@ const cases: ReadonlyArray<{ kind: MemoryItemKind; due: string | null; milestone?: string | null; + review_by?: string | null; expected: string | null; }> = [ { kind: "person", due: null, expected: "2027-02-06T04:00:00.000Z" }, @@ -17,14 +18,27 @@ const cases: ReadonlyArray<{ { kind: "deferral", due: null, expected: null }, { kind: "objective", due: "2026-12-01", milestone: "2026-11-15", expected: "2026-11-15" }, { kind: "objective", due: "2026-12-01", expected: "2026-12-01" }, - { kind: "objective", due: null, expected: null }, + { kind: "objective", due: null, expected: "2026-12-08T04:00:00.000Z" }, + { + kind: "objective", + due: "2026-12-01", + milestone: "2026-11-15", + review_by: null, + expected: null, + }, + { kind: "claim", due: null, review_by: "2026-11-20", expected: "2026-11-20" }, + { kind: "claim", due: null, review_by: null, expected: null }, ]; it.each(cases)( "defaults $kind freshness ($due, $milestone)", - ({ kind, due, milestone, expected }) => { - expect(defaultReviewBy({ kind, due }, Date.parse("2026-11-08T04:00:00.000Z"), milestone)).toBe( - expected, - ); + ({ kind, due, milestone, review_by, expected }) => { + expect( + defaultReviewBy( + { kind, due, ...(review_by === undefined ? {} : { review_by }) }, + Date.parse("2026-11-08T04:00:00.000Z"), + milestone, + ), + ).toBe(expected); }, ); diff --git a/apps/server/src/kin/memory/freshness.ts b/apps/server/src/kin/memory/freshness.ts index 3ef38bb4b7160..a36668d7c8552 100644 --- a/apps/server/src/kin/memory/freshness.ts +++ b/apps/server/src/kin/memory/freshness.ts @@ -4,17 +4,21 @@ import * as DateTime from "effect/DateTime"; const day = 24 * 60 * 60 * 1000; export function defaultReviewBy( - item: Pick, - now: number, + item: Pick & + Partial>, + recordedAt: number, nextMilestone: string | null = null, ): string | null { + if (item.review_by !== undefined) return item.review_by; switch (item.kind) { case "person": - return DateTime.formatIso(DateTime.makeUnsafe(now + 90 * day)); + return DateTime.formatIso(DateTime.makeUnsafe(recordedAt + 90 * day)); case "claim": - return DateTime.formatIso(DateTime.makeUnsafe(now + 30 * day)); + return DateTime.formatIso(DateTime.makeUnsafe(recordedAt + 30 * day)); case "objective": - return nextMilestone ?? item.due; + return ( + nextMilestone ?? item.due ?? DateTime.formatIso(DateTime.makeUnsafe(recordedAt + 30 * day)) + ); case "commitment": case "deferral": return item.due; diff --git a/docs/kin/specs/lead.md b/docs/kin/specs/lead.md index 5435176570191..fd8da57a036e0 100644 --- a/docs/kin/specs/lead.md +++ b/docs/kin/specs/lead.md @@ -372,7 +372,7 @@ Writer rules, enforced in code on `stage`: - Paths: only `objectives/`, `commitments/`, `deferrals/`, `decisions/`, `people/`, `claims/` and `journal/`. `rules.md` is refused. `INDEX.md` is written only by `rebuildIndex`. `README.md` is never touched. - No deletes. `invalidate` sets `invalid_at`; `supersede` sets the old item's `superseded_by` and `status: superseded` and creates the new one. - Provenance comes from the event, not the model. The writer looks up `sourceEventId` in the current batch and sets `said_by`, `source` and `trust` from the event's `provenance`. Owner → `owner`, member → `member`, webhook or outside text → `external`, worker suggestion → `agent`. The lead may lower trust but never raise it. A member's statement that reads like a rule is stored under `claims/`. -- `review_by` defaults by kind: person 90 days, commitment and deferral at `due`, decision `null`, claim 30 days; objective at the next milestone date (falling back to `due`, then `null`) unless given. +- `review_by` defaults by kind: person 90 days, commitment and deferral at `due`, decision `null`, claim 30 days; objective at the next milestone date (falling back to `due`, then +30 days from `recorded_at`). Explicit `review_by: null` is preserved. - Contradictions: if an open item of the same kind shares a link or id and says something different, and `supersedes` was not passed, `stage` fails with `MemoryConflict { existingId }`. The lead then supersedes (same source, newer) or posts a question to the owner. - Secret scan: before commit, the staged diff goes through `MemorySecretScan.check` (triggers spec). A hit refuses the whole commit, keeps the journal line "Commit refused: possible secret in ", and tells the owner. diff --git a/docs/kin/specs/triggers.md b/docs/kin/specs/triggers.md index fd9448ae3ece7..aa7c75fd677e2 100644 --- a/docs/kin/specs/triggers.md +++ b/docs/kin/specs/triggers.md @@ -264,14 +264,14 @@ All are plain code. They write memory only through the LEAD queue as code-only e **`review_by` defaults** are filled at write time by `freshness.ts`: - person: +90 days; -- objective: next milestone date supplied by the writer, falling back to `due`, then null; +- objective: next milestone date supplied by the writer, falling back to `due`, then +30 days from `recorded_at`; - commitment and deferral: `due`; - decision: null; - claim: +30 days. **`INDEX.md` is built by code**, not by the model (`buildIndex.ts`), from the front-matter cache. It has at most 200 lines and an `As of ` first line. Sections: Waiting on owner, due in 7 days, open objectives, open commitments, overdue (flagged `⚠ review`). Items flagged misleading drop to the end with a mark. Items unread for 8 weeks are left out, using last-read timestamps that LEAD's Memory read path records in Kin's DB (`kin_memory_reads`), not in git. Never-read items use `recorded_at` as the baseline. -The builder takes item heads (optionally marked `misleading` by the caller), last-read integer milliseconds, caller-supplied `now` and the owner's IANA zone. Each item appears once, in the first matching section; open, valid `on_due: ask` items mean Waiting on owner. Due in 7 days includes today through the seventh following owner-calendar date (exclusive midnight of day 8); front-matter date-only values still mean UTC midnight. Other items remain in Other memory; misleading items go last. Within each section, order is due, review date (missing dates last), id, path, then title, using ordinal string order. Overdue due dates on open items and overdue review dates are flagged. The cap includes headings and the omitted-item count. Memory reads the owner's zone from `kin_trigger_settings`, using UTC only before settings exist. Freshness defaults are a pure helper for LEAD-3 to apply only when `review_by` was omitted; explicit null is preserved. +The builder takes item heads (optionally marked `misleading` by the caller), last-read integer milliseconds, caller-supplied `now` and the owner's IANA zone. Each item appears once, in the first matching section; open, valid `on_due: ask` items with `due <= now` mean Waiting on owner (asked but not yet answered); future-due ask items stay in their normal section. Due in 7 days includes today through the seventh following owner-calendar date (exclusive midnight of day 8); front-matter date-only values still mean UTC midnight. Other items remain in Other memory; misleading items go last. Within each section, order is due, review date (missing dates last), id, path, then title, using ordinal string order. Overdue due dates on open items and overdue review dates are flagged. The cap includes headings and the omitted-item count. Memory reads the owner's zone from `kin_trigger_settings`, using UTC before settings exist or when the zone is invalid or cannot be read. `defaultReviewBy` is the pure helper LEAD-3 calls with parsed front matter and `recordedAt` in integer milliseconds; it applies defaults only when `review_by` was omitted and preserves explicit dates and null. The truncation line is "N more items not listed; use memory_search". **Contradiction checks** at write time are LEAD's (Memory writer). Dreams list the ones they find. From 394f5291340ad630f8407f1e01b0fe9bd5426cce Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Sun, 8 Nov 2026 02:15:01 +0530 Subject: [PATCH 3/3] docs(kin): defaultReviewBy runs on staged input, not parsed files Co-Authored-By: Claude Opus 5.5 --- docs/kin/specs/triggers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/kin/specs/triggers.md b/docs/kin/specs/triggers.md index aa7c75fd677e2..3c1a796e700aa 100644 --- a/docs/kin/specs/triggers.md +++ b/docs/kin/specs/triggers.md @@ -271,7 +271,7 @@ All are plain code. They write memory only through the LEAD queue as code-only e **`INDEX.md` is built by code**, not by the model (`buildIndex.ts`), from the front-matter cache. It has at most 200 lines and an `As of ` first line. Sections: Waiting on owner, due in 7 days, open objectives, open commitments, overdue (flagged `⚠ review`). Items flagged misleading drop to the end with a mark. Items unread for 8 weeks are left out, using last-read timestamps that LEAD's Memory read path records in Kin's DB (`kin_memory_reads`), not in git. Never-read items use `recorded_at` as the baseline. -The builder takes item heads (optionally marked `misleading` by the caller), last-read integer milliseconds, caller-supplied `now` and the owner's IANA zone. Each item appears once, in the first matching section; open, valid `on_due: ask` items with `due <= now` mean Waiting on owner (asked but not yet answered); future-due ask items stay in their normal section. Due in 7 days includes today through the seventh following owner-calendar date (exclusive midnight of day 8); front-matter date-only values still mean UTC midnight. Other items remain in Other memory; misleading items go last. Within each section, order is due, review date (missing dates last), id, path, then title, using ordinal string order. Overdue due dates on open items and overdue review dates are flagged. The cap includes headings and the omitted-item count. Memory reads the owner's zone from `kin_trigger_settings`, using UTC before settings exist or when the zone is invalid or cannot be read. `defaultReviewBy` is the pure helper LEAD-3 calls with parsed front matter and `recordedAt` in integer milliseconds; it applies defaults only when `review_by` was omitted and preserves explicit dates and null. The truncation line is "N more items not listed; use memory_search". +The builder takes item heads (optionally marked `misleading` by the caller), last-read integer milliseconds, caller-supplied `now` and the owner's IANA zone. Each item appears once, in the first matching section; open, valid `on_due: ask` items with `due <= now` mean Waiting on owner (asked but not yet answered); future-due ask items stay in their normal section. Due in 7 days includes today through the seventh following owner-calendar date (exclusive midnight of day 8); front-matter date-only values still mean UTC midnight. Other items remain in Other memory; misleading items go last. Within each section, order is due, review date (missing dates last), id, path, then title, using ordinal string order. Overdue due dates on open items and overdue review dates are flagged. The cap includes headings and the omitted-item count. Memory reads the owner's zone from `kin_trigger_settings`, using UTC before settings exist or when the zone is invalid or cannot be read. `defaultReviewBy` is the pure helper LEAD-3's `stage` calls on the lead's staged input, before it becomes front matter, with `recordedAt` in integer milliseconds; it applies defaults only when the input omitted `review_by` and preserves explicit dates and null. Committed front matter always carries `review_by` (the schema requires it), so the helper never runs on parsed files. The truncation line is "N more items not listed; use memory_search". **Contradiction checks** at write time are LEAD's (Memory writer). Dreams list the ones they find.