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
8 changes: 8 additions & 0 deletions apps/server/src/kin/chat/KinChatRepository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,14 @@ describe("KinChatRepository", () => {
assert.strictEqual(Option.getOrThrow(yield* repo.getMember(scope)).leftAt, later);
const rejoined = yield* repo.addMember({ ...owner, joinedAt: later });
assert.deepStrictEqual(rejoined, { ...owner, joinedAt: later });
for (const body of ["a\u0000b", "\u0000ab", "ab\u0000"]) {
const failure = yield* Effect.flip(repo.insertMessage(message("nul", { body })));
assert.strictEqual(failure._tag, "PersistenceDecodeError");
assert.strictEqual(
Option.isNone(yield* repo.getMessage({ orgId, messageId: decodeMessageId("nul") })),
true,
);
}
const first = yield* repo.insertMessage(message("first"));
assert.deepStrictEqual(first, decodeMessage({ ...message("first"), seq: 1 }));
const repeated = yield* Effect.all(
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/kin/chat/KinChatRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ const isSqlError = Schema.is(PersistenceSqlError);
const encodeMentions = Schema.encodeEffect(Schema.fromJsonString(KinMessage.fields.mentions));
const encodeWidgetState = Schema.encodeEffect(Schema.fromJsonString(KinWidget.fields.state));
const encodeAwaiting = Schema.encodeEffect(Schema.fromJsonString(KinWidget.fields.awaiting));
const decodeBody = Schema.decodeEffect(KinMessage.fields.body);
const decodeHistory = Schema.decodeEffect(KinChatHistoryInput);
const decodeSeq = Schema.decodeEffect(NonNegativeInt);
const decodeResume = Schema.decodeEffect(
Expand Down Expand Up @@ -820,6 +821,7 @@ const make = Effect.gen(function* () {
),
insertMessage: Effect.fn("KinChatRepository.insertMessage")(
function* (input) {
yield* decodeBody(input.body);
return yield* sql.withTransaction(
Effect.gen(function* () {
const author = input.author;
Expand Down
23 changes: 8 additions & 15 deletions apps/server/src/kin/lead/LeadPrompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,18 +140,7 @@ it.effect.each([
{ role: "member", tag: "human", label: "member human message (untrusted)" },
{ role: "guest", tag: "human", label: "guest human message (untrusted)" },
{ role: "owner", tag: "human", label: "owner message" },
...[
"\u0000",
"\u001b",
"\u007f",
"\u0085",
"\u200b",
"\ufeff",
"\u202e",
"\u2066",
"\u2028",
"\u2029",
].map(
...["\u001b", "\u007f", "\u0085", "\u200b", "\ufeff", "\u202e", "\u2066", "\u2028", "\u2029"].map(
(character) =>
({
role: "member",
Expand Down Expand Up @@ -228,8 +217,8 @@ it.effect.each([
editedAt: null,
clientMessageId: null,
});
// Non-human owner roles and NUL text are defensive repository-boundary cases.
const defensiveRecord = (tag !== "human" && role === "owner") || body.includes("\u0000");
// Non-human owner roles are defensive repository-boundary cases.
const defensiveRecord = tag !== "human" && role === "owner";
const source = defensiveRecord
? Chat.KinChatRepository.of({
...repo,
Expand Down Expand Up @@ -405,6 +394,9 @@ it.effect("bounds the encoded events section and drops oldest events visibly", (
it.effect.each([
{ zone: "Asia/Kolkata", expected: "1970-01-01T05:30:00.000+05:30" },
{ zone: "America/New_York", expected: "1969-12-31T19:00:00.000-05:00[America/New_York]" },
{ zone: "+05:30", expected: "UTC (invalid owner timezone; using UTC)" },
{ zone: " Asia/Kolkata", expected: "1970-01-01T05:30:00.000+05:30" },
{ zone: "db-failure", expected: "UTC (owner timezone unavailable; using UTC)" },
{ zone: "invalid-zone", expected: "UTC (invalid owner timezone; using UTC)" },
{ zone: null, expected: "UTC (owner timezone unavailable; using UTC)" },
])("shows owner timezone $zone only below the divider", ({ zone, expected }) =>
Expand All @@ -413,7 +405,8 @@ it.effect.each([
const sql = yield* SqlClient.SqlClient;
const prompt = yield* KinLeadPrompt;
const before = yield* prompt.build(input);
if (zone !== null)
if (zone === "db-failure") yield* sql`DROP TABLE kin_trigger_settings`;
else if (zone !== null)
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)
Expand Down
26 changes: 8 additions & 18 deletions apps/server/src/kin/lead/LeadPrompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/sql/SqlClient";
import { toPersistenceSqlError } from "../../persistence/Errors.ts";

import * as Memory from "../memory/Memory.ts";
import * as MemoryCache from "../memory/MemoryCache.ts";
import * as Chat from "../chat/KinChatRepository.ts";

import { instructions } from "./instructions.ts";
Expand Down Expand Up @@ -44,7 +43,7 @@ export class KinLeadPrompt extends Context.Service<
Effect.gen(function* () {
const memory = yield* Memory.Memory;
const chat = yield* Chat.KinChatRepository;
const sql = yield* SqlClient.SqlClient;
const cache = yield* MemoryCache.MemoryCache;
const build = Effect.fn("KinLeadPrompt.build")(function* (input: KinLeadPromptInput) {
const { orgId, agentId, memoryHead } = input;
if (input.events.some((event) => event.orgId !== orgId || event.agentId !== agentId))
Expand Down Expand Up @@ -112,20 +111,11 @@ export class KinLeadPrompt extends Context.Service<
);
}
const now = yield* Clock.currentTimeMillis;
const settings = yield* sql<{ time_zone: string }>`
SELECT time_zone FROM kin_trigger_settings WHERE org_id = ${orgId}
`.pipe(
Effect.mapError(toPersistenceSqlError("KinLeadPrompt.ownerTimeZone")),
Effect.mapError(
(cause) =>
new KinLeadPromptError({ orgId, reason: "Could not read owner timezone", cause }),
),
);
const zone = settings[0]?.time_zone;
const local = zone ? DateTime.makeZoned(now, { timeZone: zone }) : Option.none();
const ownerTime = Option.isSome(local)
? `${encoded(zone)}; local time: ${DateTime.formatIsoZoned(local.value)}`
: `UTC (${zone ? "invalid owner timezone" : "owner timezone unavailable"}; using UTC); local time: ${DateTime.formatIso(DateTime.makeUnsafe(now))}`;
const zone = yield* cache.readOwnerTimeZone(orgId);
const ownerTime =
zone._tag === "zone"
? `${encoded(zone.zone)}; local time: ${DateTime.formatIsoZoned(DateTime.makeZonedUnsafe(now, { timeZone: zone.zone }))}`
: `UTC (${zone._tag === "invalid" ? "invalid owner timezone" : "owner timezone unavailable"}; using UTC); local time: ${DateTime.formatIso(DateTime.makeUnsafe(now))}`;

return [
instructions,
Expand All @@ -147,7 +137,7 @@ export class KinLeadPrompt extends Context.Service<
});
return KinLeadPrompt.of({ build });
}),
);
).pipe(Layer.provide(MemoryCache.layer));
}

const messageBodyLimit = 8_000;
Expand Down
35 changes: 26 additions & 9 deletions apps/server/src/kin/memory/Memory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import * as Sqlite from "../../persistence/Sqlite.ts";
import * as Memory from "./Memory.ts";
import * as Chat from "../chat/KinChatRepository.ts";
import { KinLeadPrompt } from "../lead/LeadPrompt.ts";
import * as MemoryCache from "./MemoryCache.ts";
import * as MemoryConfig from "./MemoryConfig.ts";
import * as ServerConfig from "../../config.ts";
import { fixtureItem } from "./__fixtures__/items.ts";
Expand Down Expand Up @@ -507,15 +508,31 @@ it.effect(
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* Effect.gen(function* () {
const cache = yield* MemoryCache.MemoryCache;
for (const row of [
{ zone: "+05:30", expected: { _tag: "invalid" } },
{ zone: " Asia/Kolkata", expected: { _tag: "zone", zone: "Asia/Kolkata" } },
{ zone: "Asia/Kolkata", expected: { _tag: "zone", zone: "Asia/Kolkata" } },
{ zone: "Invented/Invalid", expected: { _tag: "invalid" } },
{ zone: null, expected: { _tag: "missing" } },
]) {
if (row.zone === null)
yield* sql`DELETE FROM kin_trigger_settings WHERE org_id = ${orgA}`;
else
yield* sql`UPDATE kin_trigger_settings SET time_zone = ${row.zone} WHERE org_id = ${orgA}`;
expect(yield* cache.readOwnerTimeZone(orgA)).toEqual(row.expected);
expect(yield* cache.readOwnerTimeZone(orgB)).toEqual({ _tag: "missing" });
repository.commit();
yield* memory.prepareWakeup(orgA);
if (row.expected._tag !== "zone") 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`;
expect(yield* cache.readOwnerTimeZone(orgA)).toEqual({ _tag: "unavailable" });
}).pipe(Effect.provide(MemoryCache.layer));
yield* sql`DROP TABLE kin_memory_reads`;
repository.commit();
yield* memory.prepareWakeup(orgA);
Expand Down
9 changes: 1 addition & 8 deletions apps/server/src/kin/memory/Memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -671,14 +671,7 @@ const make = Effect.gen(function* () {
),
}),
);
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"),
),
}),
);
const ownerTimeZone = yield* cache.ownerTimeZone(orgId);
snapshot.index = buildIndex(
snapshot.items.map(({ head }) => head),
reads,
Expand Down
44 changes: 29 additions & 15 deletions apps/server/src/kin/memory/MemoryCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,21 @@ export class MemoryHistoryError extends Schema.TaggedError<MemoryHistoryError>()
{ orgId: Schema.String, cause: Schema.Defect() },
) {}

export type OwnerTimeZone =
| { readonly _tag: "zone"; readonly zone: string }
| { readonly _tag: "missing" }
| { readonly _tag: "invalid" }
| { readonly _tag: "unavailable" };

export class MemoryCache extends Context.Service<
MemoryCache,
{
readonly read: (
orgId: KinOrgId,
id: KinMemoryItemId,
) => Effect.Effect<void, MemoryHistoryError>;
readonly ownerTimeZone: (orgId: KinOrgId) => Effect.Effect<string, MemoryHistoryError>;
readonly readOwnerTimeZone: (orgId: KinOrgId) => Effect.Effect<OwnerTimeZone>;
readonly ownerTimeZone: (orgId: KinOrgId) => Effect.Effect<string>;
readonly lastReads: (
orgId: KinOrgId,
) => Effect.Effect<Readonly<Record<string, number>>, MemoryHistoryError>;
Expand All @@ -41,7 +48,21 @@ const decodeTimeZone = Schema.decodeUnknownEffect(KinTrigger.fields.timeZone);

const make = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const readOwnerTimeZone = Effect.fn("MemoryCache.readOwnerTimeZone")(function* (
orgId: KinOrgId,
): Effect.fn.Return<OwnerTimeZone> {
const result = 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.readOwnerTimeZone")), Effect.result);
if (result._tag === "Failure") return { _tag: "unavailable" };
if (result.success.length === 0) return { _tag: "missing" };
const decoded = yield* decodeTimeZone(result.success[0]?.time_zone).pipe(Effect.result);
return decoded._tag === "Success"
? { _tag: "zone", zone: decoded.success }
: { _tag: "invalid" };
});
return MemoryCache.of({
readOwnerTimeZone,
read: Effect.fn("MemoryCache.read")(function* (orgId, id) {
const now = yield* Clock.currentTimeMillis;
// Memory.readItem validates the item against this organization's committed snapshot.
Expand All @@ -55,20 +76,13 @@ const make = Effect.gen(function* () {
);
}),
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"),
),
),
);
const result = yield* readOwnerTimeZone(orgId);
if (result._tag === "zone") return result.zone;
if (result._tag === "invalid")
yield* Effect.logWarning("Invalid memory owner time zone; using UTC", { orgId });
if (result._tag === "unavailable")
yield* Effect.logWarning("Could not load memory owner time zone; using UTC", { orgId });
return "UTC";
}),
lastReads: Effect.fn("MemoryCache.lastReads")(function* (orgId) {
const rows = yield* sql<{ item_id: string; last_read_at: number }>`
Expand Down
2 changes: 1 addition & 1 deletion docs/kin/specs/lead.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ The CLIs own their system prompt and tool list, and Kin cannot set cache breakpo
1. The lead instructions (`instructions.ts`, below), with its version line.
2. `rules.md` through `Memory`, verbatim and pinned to the wake-up head.
3. `INDEX.md` through the same atomic, head-checked `Memory.readPromptSnapshot` read. Its content is JSON-encoded inside a labelled data quote because titles can originate in member or external text. Use the rebuilt snapshot index when present, otherwise the committed bytes, under the same lock and head check. If neither exists, quote an empty index and add a one-line "index unavailable" note. Missing committed rules fails the build. Repeated builds at the same head reuse the snapshot index; an explicit index rebuild may change the prefix without a new commit.
4. A divider, then the variable part: time and timezone, wake-up id, level per chat, budget state ("62% of today left"), running workers, and the events. Each event is a short line. Message bodies are loaded by organization and message id from the chat repository. Owner labels require both stored `author._tag: human` and `authorRole: owner`, never event provenance or body text. Only posted messages reach the prompt; suggested guest messages remain hidden until the owner sends them. Quoted message JSON includes kind, status and widgetId. Human non-owner text uses role-labelled quotes; agent and system labels never start with a role word ("agent message (untrusted)" and "system message"), with stored roles inside the JSON. GitHub summaries and other event data are quoted. JSON encoding escapes angle brackets, ampersands and every Unicode Cc, Cf, Zl and Zp character as `\uXXXX` (surrogate pairs where needed), so source text cannot close a block or forge a label. Each quoted event/message text field is capped at 2,000 UTF-16 characters, except message bodies at 8,000; a visible `…[truncated N chars]` marker inside the JSON string reports removed characters. The complete encoded events section is capped at 60,000 characters, including framing and an `N earlier events omitted` line; drop oldest events and their message quotes together. Raw webhook bodies remain references for tool reads. LEAD-6 supplies UTC time, the owner timezone and local time read from organization trigger settings (UTC with a note for a missing or invalid zone), and event context; LEAD-5/LEAD-10 supply level and budget context when available, without changing the stable prefix.
4. A divider, then the variable part: time and timezone, wake-up id, level per chat, budget state ("62% of today left"), running workers, and the events. Each event is a short line. Message bodies are loaded by organization and message id from the chat repository. Owner labels require both stored `author._tag: human` and `authorRole: owner`, never event provenance or body text. Only posted messages reach the prompt; suggested guest messages remain hidden until the owner sends them. Quoted message JSON includes kind, status and widgetId. Human non-owner text uses role-labelled quotes; agent and system labels never start with a role word ("agent message (untrusted)" and "system message"), with stored roles inside the JSON. GitHub summaries and other event data are quoted. JSON encoding escapes angle brackets, ampersands and every Unicode Cc, Cf, Zl and Zp character as `\uXXXX` (surrogate pairs where needed), so source text cannot close a block or forge a label. Each quoted event/message text field is capped at 2,000 UTF-16 characters, except message bodies at 8,000; a visible `…[truncated N chars]` marker inside the JSON string reports removed characters. The complete encoded events section is capped at 60,000 characters, including framing and an `N earlier events omitted` line; drop oldest events and their message quotes together. Raw webhook bodies remain references for tool reads. LEAD-6 supplies UTC time, the owner timezone and local time read from organization trigger settings (validated with the trigger TimeZone contract; UTC with a note for missing, invalid or unavailable settings), and event context; LEAD-5/LEAD-10 supply level and budget context when available, without changing the stable prefix.

No wake-up timestamps or ids go above the divider (dates and item ids already in memory remain there). A test asserts that two prompts built for the same organization and memory commit share everything above it while the snapshot index is unchanged. Cache hits are measured with `cachedInputTokens` on the turn's `tokenUsage` and shown in the evening summary.

Expand Down
2 changes: 1 addition & 1 deletion packages/contracts/src/kinChat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ describe("Kin chat contracts", () => {
expect(decodeSend(payload)).toEqual(send);
});

it.each(["", " \n ", "x".repeat(16_001)])("rejects send body %j", (body) => {
it.each(["", " \n ", "x".repeat(16_001), "a\u0000b"])("rejects send body %j", (body) => {
expect(() => decodeSend({ ...send, body })).toThrow();
});

Expand Down
11 changes: 9 additions & 2 deletions packages/contracts/src/kinChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ const isNonBlankBody = Schema.makeFilter((value: string) => value.trim().length
expected: "a non-blank message body",
});

// node:sqlite truncates TEXT results at NUL, even when the full value was stored.
const MessageBody = Schema.String.check(
Schema.makeFilter((value) => !value.includes("\u0000"), {
expected: "a message body without NUL characters",
}),
);

export const KinChatKind = Schema.Literals(["direct", "team_group", "project_group", "router"]);
export type KinChatKind = typeof KinChatKind.Type;
export const KinRole = Schema.Literals(["owner", "member", "guest"]);
Expand Down Expand Up @@ -142,7 +149,7 @@ export const KinMessage = Schema.Struct({
author: KinAuthor,
authorRole: KinRole,
kind: KinMessageKind,
body: Schema.String,
body: MessageBody,
intent: Schema.NullOr(KinAgentIntent),
mentions: Schema.Array(KinMemberId),
replyTo: Schema.NullOr(KinMessageId),
Expand Down Expand Up @@ -293,7 +300,7 @@ export type KinChatHistoryResult = typeof KinChatHistoryResult.Type;
export const KinMessagesSendInput = Schema.Struct({
chatId: KinChatId,
clientMessageId: TrimmedNonEmptyString,
body: Schema.String.check(isNonBlankBody, Schema.isMaxLength(16_000)),
body: MessageBody.check(isNonBlankBody, Schema.isMaxLength(16_000)),
mentions: Schema.optional(Schema.Array(KinMemberId)),
replyTo: Schema.optional(KinMessageId),
});
Expand Down
Loading