diff --git a/apps/server/src/kin/chat/KinChatHub.test.ts b/apps/server/src/kin/chat/KinChatHub.test.ts new file mode 100644 index 0000000000000..3fadabe0166e1 --- /dev/null +++ b/apps/server/src/kin/chat/KinChatHub.test.ts @@ -0,0 +1,79 @@ +import { assert, describe, it } from "@effect/vitest"; +import { KinChatId, KinMemberId, KinOrgId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as PubSub from "effect/PubSub"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as Sqlite from "../../persistence/Sqlite.ts"; +import * as KinPersistence from "../persistence/KinPersistence.ts"; +import * as Repository from "./KinChatRepository.ts"; +import * as Hub from "./KinChatHub.ts"; + +const layer = Layer.provideMerge( + Hub.layer, + Layer.provideMerge( + Repository.layer, + Layer.provideMerge(KinPersistence.layer, Sqlite.layerMemory), + ), +); +const orgId = Schema.decodeSync(KinOrgId)("org-a"); +const otherOrg = Schema.decodeSync(KinOrgId)("org-b"); +const event: Hub.KinChatHubEvent = { + type: "read.updated", + orgId, + chatId: Schema.decodeSync(KinChatId)("chat"), + memberId: Schema.decodeSync(KinMemberId)("member"), + seq: 1, +}; + +describe("KinChatHub", () => { + it.effect( + "isolates org subscriptions and delivers only after the outer commit, discarding rollbacks", + () => + Effect.gen(function* () { + const hub = yield* Hub.KinChatHub; + const sql = yield* SqlClient.SqlClient; + const first = yield* hub.subscribe(orgId); + const second = yield* hub.subscribe(orgId); + const other = yield* hub.subscribe(otherOrg); + yield* sql`CREATE TABLE chat_hub_test (seq INTEGER)`; + yield* sql.withTransaction( + Effect.gen(function* () { + yield* sql`INSERT INTO chat_hub_test VALUES (1)`; + yield* sql.withTransaction(hub.publish(event)); + assert.deepStrictEqual(yield* PubSub.takeUpTo(first, 10), []); + yield* sql + .withTransaction( + hub + .publish({ ...event, seq: 2 }) + .pipe(Effect.andThen(Effect.fail("nested rollback"))), + ) + .pipe(Effect.flip); + }), + ); + assert.deepStrictEqual(yield* PubSub.take(first), event); + assert.deepStrictEqual(yield* PubSub.take(second), event); + assert.deepStrictEqual(yield* sql`SELECT seq FROM chat_hub_test ORDER BY seq`, [ + { seq: 1 }, + ]); + yield* sql + .withTransaction( + Effect.gen(function* () { + yield* sql`INSERT INTO chat_hub_test VALUES (3)`; + yield* hub.publish({ ...event, seq: 3 }); + return yield* Effect.fail("outer rollback"); + }), + ) + .pipe(Effect.flip); + assert.deepStrictEqual(yield* PubSub.takeUpTo(first, 10), []); + assert.deepStrictEqual(yield* PubSub.takeUpTo(second, 10), []); + assert.deepStrictEqual(yield* PubSub.takeUpTo(other, 10), []); + yield* hub.publish({ ...event, orgId: otherOrg }); + assert.deepStrictEqual(yield* PubSub.take(other), { ...event, orgId: otherOrg }); + assert.deepStrictEqual(yield* sql`SELECT seq FROM chat_hub_test ORDER BY seq`, [ + { seq: 1 }, + ]); + }).pipe(Effect.provide(layer)), + ); +}); diff --git a/apps/server/src/kin/chat/KinChatHub.ts b/apps/server/src/kin/chat/KinChatHub.ts new file mode 100644 index 0000000000000..c5c8fde915709 --- /dev/null +++ b/apps/server/src/kin/chat/KinChatHub.ts @@ -0,0 +1,127 @@ +import type { + KinChat, + KinChatId, + KinMemberId, + KinMessage, + KinOrgId, + KinWaitingItem, + KinWidget, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; +import * as Repository from "./KinChatRepository.ts"; +import type { AgentIdentity, PersonIdentity } from "./KinIdentity.ts"; +import * as PubSub from "effect/PubSub"; +import type * as Scope from "effect/Scope"; +import * as SqlClient from "effect/sql/SqlClient"; + +type ChatEvent = + | { readonly type: "chat.created"; readonly chat: KinChat } + | { readonly type: "message.posted"; readonly message: KinMessage } + | { readonly type: "widget.updated"; readonly widget: KinWidget } + | { readonly type: "waiting.updated"; readonly item: KinWaitingItem } + | { + readonly type: "read.updated"; + readonly chatId: KinChatId; + readonly memberId: KinMemberId; + readonly seq: number; + }; +export type KinChatHubEvent = ChatEvent & { readonly orgId: KinOrgId }; + +export class KinChatHub extends Context.Service< + KinChatHub, + { + readonly publish: (event: KinChatHubEvent) => Effect.Effect; + readonly subscribeForViewer: ( + identity: PersonIdentity | AgentIdentity, + ) => Effect.Effect< + Stream.Stream, + never, + Scope.Scope + >; + readonly subscribe: ( + orgId: KinOrgId, + ) => Effect.Effect, never, Scope.Scope>; + } +>()("t3/kin/chat/KinChatHub") {} + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const repo = yield* Repository.KinChatRepository; + const hubs = new Map>(); + yield* Effect.addFinalizer(() => + Effect.forEach(hubs.values(), PubSub.shutdown, { discard: true }), + ); + const subscribe = Effect.fn("KinChatHub.subscribe")(function* (orgId: KinOrgId) { + let hub = hubs.get(orgId); + if (hub === undefined) { + const created = yield* PubSub.unbounded(); + hub = hubs.get(orgId) ?? created; + hubs.set(orgId, hub); + } + return yield* PubSub.subscribe(hub); + }); + return KinChatHub.of({ + publish: Effect.fn("KinChatHub.publish")(function (event) { + return sql.afterCommit( + Effect.gen(function* () { + const hub = hubs.get(event.orgId); + if (hub !== undefined) yield* PubSub.publish(hub, event); + }), + ); + }), + subscribe, + subscribeForViewer: Effect.fn("KinChatHub.subscribeForViewer")(function* (identity) { + const subscription = yield* subscribe(identity.orgId); + return Stream.fromEffectRepeat(PubSub.take(subscription)).pipe( + Stream.filterEffect( + Effect.fn("KinChatHub.canDeliver")(function* (event) { + const chatId = + event.type === "chat.created" + ? event.chat.chatId + : event.type === "message.posted" + ? event.message.chatId + : event.type === "widget.updated" + ? event.widget.chatId + : event.type === "waiting.updated" + ? event.item.chatId + : event.chatId; + const member = (yield* repo.listMembers({ orgId: identity.orgId, chatId })).find( + (row) => + row.leftAt === null && + (identity._tag === "person" + ? row.principal._tag === "person" && row.principal.personId === identity.personId + : row.principal._tag === "agent" && row.principal.agentId === identity.agentId), + ); + if (member === undefined) return false; + const messageId = + event.type === "widget.updated" + ? event.widget.messageId + : event.type === "waiting.updated" + ? event.item.messageId + : null; + const message = + event.type === "message.posted" + ? Option.some(event.message) + : messageId === null + ? Option.none() + : yield* repo.getMessage({ orgId: identity.orgId, messageId }); + if (messageId !== null && Option.isNone(message)) return false; + return ( + Option.isNone(message) || + !["suggested", "dismissed"].includes(message.value.status) || + member.role === "owner" || + (message.value.author._tag !== "system" && + message.value.author.memberId === member.memberId) + ); + }), + ), + ); + }), + }); +}); + +export const layer = Layer.effect(KinChatHub, make); diff --git a/apps/server/src/kin/chat/KinChatRepository.test.ts b/apps/server/src/kin/chat/KinChatRepository.test.ts index f6b81bae6a600..2dbc36e374017 100644 --- a/apps/server/src/kin/chat/KinChatRepository.test.ts +++ b/apps/server/src/kin/chat/KinChatRepository.test.ts @@ -307,7 +307,7 @@ describe("KinChatRepository", () => { repo.insertMessage({ ...message("first"), messageId: decodeMessageId(`retry-${i}`), - body: "changed", + body: first.body, createdAt: later, }), ), @@ -327,7 +327,7 @@ describe("KinChatRepository", () => { assert.strictEqual(action.messageId, decodeMessageId("action")); assert.deepStrictEqual( yield* repo.insertMessage({ - ...message("repeated-action", { kind: "widget_action" }), + ...message("repeated-action", { kind: "system", body: "action" }), clientMessageId: { kind: "act", id: "first" }, }), action, @@ -337,6 +337,18 @@ describe("KinChatRepository", () => { Option.getOrThrow(yield* repo.getWidget({ orgId, widgetId })), widget, ); + const suppliedRevision = { + ...widget, + widgetId: decodeWidgetId("server-revision"), + revision: 99, + }; + yield* repo.insertWidget(suppliedRevision); + assert.strictEqual( + Option.getOrThrow( + yield* repo.getWidget({ orgId, widgetId: decodeWidgetId("server-revision") }), + ).revision, + 1, + ); yield* repo.markRead({ ...scope, seq: 1, updatedAt: timestamp }); assert.deepStrictEqual(Option.getOrThrow(yield* repo.getReadState(scope)), { ...scope, @@ -355,6 +367,9 @@ describe("KinChatRepository", () => { resolvedAt: null, resolution: null, } as const; + assert.include(yield* Effect.flip(repo.addWaiting({ ...waiting, resolvedAt: later })), { + reason: "invalid_state", + }); assert.strictEqual(yield* repo.addWaiting(waiting), true); assert.strictEqual( yield* repo.addWaiting({ ...waiting, waitingId: decodeWaitingId("duplicate-waiting") }), @@ -439,12 +454,44 @@ describe("KinChatRepository", () => { ); assert.deepStrictEqual( yield* sql`SELECT typeof(revision) AS type FROM kin_widgets WHERE org_id = ${orgId}`, - [{ type: "integer" }], + [{ type: "integer" }, { type: "integer" }], ); assert.deepStrictEqual(yield* sql`PRAGMA foreign_key_check`, []); }).pipe(Effect.provide(layer)), ); + it.effect("rejects left mentions and retired authors inside the post transaction", () => + Effect.gen(function* () { + const repo = yield* seed; + yield* repo.leaveChat({ ...scope, memberId: agentMemberId, leftAt: later }); + assert.include(yield* Effect.flip(repo.insertMessage(message("left-mention"))), { + reason: "not_found", + }); + yield* repo.addMember(agentMember); + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE kin_agents SET retired_at = ${later} WHERE org_id = ${orgId} AND agent_id = ${agentId}`; + assert.deepStrictEqual(yield* repo.listActiveAgentThreads(), []); + assert.include( + yield* Effect.flip( + repo.insertMessage( + message("retired", { + author: { + _tag: "agent", + agentId, + memberId: agentMemberId, + ownerPersonId: personId, + threadId, + }, + intent: "answer", + }), + ), + ), + { reason: "not_found" }, + ); + assert.strictEqual(Option.getOrThrow(yield* repo.getChat(scope)).lastSeq, 0); + }).pipe(Effect.provide(layer)), + ); + it.effect("allocates gapless seqs under 20 concurrent sends", () => Effect.gen(function* () { const repo = yield* seed; @@ -463,7 +510,7 @@ describe("KinChatRepository", () => { clientMessageId: { kind: "send", id: "new-id" }, }), ); - assert.strictEqual(failed._tag, "PersistenceSqlError"); + assert.include(failed, { reason: "not_found" }); assert.strictEqual(Option.getOrThrow(yield* repo.getChat(scope)).lastSeq, 20); assert.strictEqual((yield* repo.insertMessage(message("next"))).seq, 21); }).pipe(Effect.provide(layer)), @@ -523,6 +570,20 @@ describe("KinChatRepository", () => { [...expected], ); } + for (const status of ["suggested", "dismissed"] as const) + yield* repo.insertMessage(message(status, { status })); + yield* repo.insertMessage(message("visible")); + for (const [viewerMemberId, seqs] of [ + [agentMemberId, [5, 8]], + [memberId, [7, 8]], + ] as const) { + const page = yield* repo.history({ orgId, chatId, beforeSeq: 9, limit: 2, viewerMemberId }); + assert.deepStrictEqual( + page.messages.map((row) => row.seq), + [...seqs], + ); + assert.strictEqual(page.hasMore, true); + } }).pipe(Effect.provide(layer)), ); @@ -605,7 +666,10 @@ describe("KinChatRepository", () => { repo.insertMessage(message("invalid-reference", fields)), ); assert.strictEqual(failure._tag, "KinChatError"); - if (failure._tag === "KinChatError") assert.strictEqual(failure.reason, "not_found"); + if (failure._tag === "KinChatError") { + assert.strictEqual(failure.reason, "not_found"); + assert.strictEqual(failure.message, "Kin record not found."); + } } const hidden = { ...scope, orgId: orgA }; const sql = yield* SqlClient.SqlClient; @@ -707,6 +771,7 @@ describe("KinChatRepository", () => { endedAt: null, }); for (const refs of [ + { source: { threadId: decodeThreadId("other-thread"), itemId: decodeTurnItemId("item") } }, { awaiting: [otherPerson] }, { awaiting: [decodePersonId("unknown-person")] }, { @@ -725,6 +790,36 @@ describe("KinChatRepository", () => { if (failure._tag === "KinChatError") assert.strictEqual(failure.reason, "not_found"); } } + const foreignAnchor = yield* repo.insertMessage({ + ...message("foreign-anchor"), + orgId: orgA, + chatId: otherChat, + author: { _tag: "system" }, + mentions: [], + clientMessageId: null, + }); + for (const collision of [ + repo + .insertMessage({ + ...message("first"), + orgId: orgA, + chatId: otherChat, + author: { _tag: "system" }, + mentions: [], + clientMessageId: null, + }) + .pipe(Effect.asVoid), + repo.insertWidget({ + ...widget, + orgId: orgA, + chatId: otherChat, + messageId: foreignAnchor.messageId, + awaiting: [], + source: null, + feed: null, + }), + ]) + assert.include(yield* Effect.flip(collision), { reason: "not_found" }); for (const retry of [ repo .addWaiting({ diff --git a/apps/server/src/kin/chat/KinChatRepository.ts b/apps/server/src/kin/chat/KinChatRepository.ts index 63443d4c2e517..eace986b93f0f 100644 --- a/apps/server/src/kin/chat/KinChatRepository.ts +++ b/apps/server/src/kin/chat/KinChatRepository.ts @@ -216,14 +216,19 @@ export class KinChatRepository extends Context.Service< readonly directKey: typeof TrimmedNonEmptyString.Type | null; }, ) => Effect.Effect; + readonly findClientMessage: ( + input: MemberScope & { readonly kind: "send" | "act"; readonly clientId: string }, + ) => Effect.Effect, RepositoryError>; readonly insertMessage: (input: InsertMessage) => Effect.Effect; readonly history: ( - input: Scope & KinChatHistoryInput, + input: Scope & KinChatHistoryInput & { readonly viewerMemberId?: KinMemberId }, ) => Effect.Effect; readonly messagesAfter: ( input: ChatScope & { readonly afterSeq: typeof NonNegativeInt.Type; readonly limit: number }, ) => Effect.Effect, RepositoryError>; - readonly insertWidget: (input: KinWidget) => Effect.Effect; + readonly insertWidget: ( + input: Omit, + ) => Effect.Effect; readonly updateWidget: ( input: Omit & { readonly expectedRevision: typeof NonNegativeInt.Type; @@ -363,13 +368,31 @@ const make = Effect.gen(function* () { Effect.mapError(toRepositoryError("KinChatRepository.getAgentThread")), ); const validateWidgetReferences = Effect.fn("KinChatRepository.validateWidgetReferences")( - function* (input: Pick) { - for (const personId of input.awaiting) + function* (input: Pick) { + for (const personId of input.awaiting) { yield* requireRecord(personOne({ orgId: input.orgId, personId })); - if (input.source?.threadId != null) yield* requireRecord( + SqlSchema.findOneOption({ + Request: Schema.Unknown, + Result: MemberRow, + execute: () => sql`SELECT ${sql.literal(memberColumns)} FROM kin_chat_members + WHERE org_id = ${input.orgId} AND chat_id = ${input.chatId} AND person_id = ${personId} AND left_at IS NULL`, + })(input), + ); + } + if (input.source !== null) { + const thread = yield* requireRecord( agentThreadOne({ orgId: input.orgId, threadId: input.source.threadId }), ); + yield* requireRecord( + SqlSchema.findOneOption({ + Request: Schema.Unknown, + Result: MemberRow, + execute: () => sql`SELECT ${sql.literal(memberColumns)} FROM kin_chat_members + WHERE org_id = ${input.orgId} AND chat_id = ${input.chatId} AND agent_id = ${thread.agentId}`, + })(input), + ); + } }, ); return KinChatRepository.of({ @@ -438,12 +461,14 @@ const make = Effect.gen(function* () { Request: Schema.Unknown, Result: AgentThreadRow, execute: () => - sql`SELECT ${sql.literal(agentThreadColumns)} FROM kin_agent_threads WHERE ended_at IS NULL ORDER BY org_id, thread_id`, + sql`SELECT ${sql.literal(agentThreadColumns)} FROM kin_agent_threads + WHERE ended_at IS NULL AND EXISTS (SELECT 1 FROM kin_agents a + WHERE a.org_id = kin_agent_threads.org_id AND a.agent_id = kin_agent_threads.agent_id AND a.retired_at IS NULL) + ORDER BY org_id, thread_id`, })(undefined).pipe(NodeSqliteClient.readOnly); }, Effect.mapError(toRepositoryError("KinChatRepository.listActiveAgentThreads")), ), - // Bootstrap discovers orgs; write-side global-id checks also cross orgs to detect hidden collisions. listAllOrgs: Effect.fn("KinChatRepository.listAllOrgs")( function* () { return yield* SqlSchema.findAll({ @@ -571,6 +596,7 @@ const make = Effect.gen(function* () { agentOne({ orgId: input.orgId, agentId: input.principal.agentId }), ); } + // Global ids must detect hidden cross-org collisions without exposing their rows. const existing = yield* SqlSchema.findAll({ Request: Schema.Unknown, Result: MemberRow, @@ -599,7 +625,7 @@ const make = Effect.gen(function* () { message: "Kin member identity conflict.", }); if (member.leftAt === null) return member; - yield* sql`UPDATE kin_chat_members SET left_at = NULL, joined_at = ${input.joinedAt} + yield* sql`UPDATE kin_chat_members SET left_at = NULL, joined_at = ${input.joinedAt}, role = ${input.role} WHERE org_id = ${input.orgId} AND member_id = ${input.memberId}`; return yield* requireRecord(memberOne(input)); } @@ -612,18 +638,40 @@ const make = Effect.gen(function* () { ), leaveChat: Effect.fn("KinChatRepository.leaveChat")( function* (input) { - const changed = yield* sql`UPDATE kin_chat_members SET left_at = ${input.leftAt} + return yield* sql.withTransaction( + Effect.gen(function* () { + const changed = yield* sql`UPDATE kin_chat_members SET left_at = ${input.leftAt} WHERE org_id = ${input.orgId} AND chat_id = ${input.chatId} AND member_id = ${input.memberId} AND left_at IS NULL RETURNING member_id`; - return changed.length > 0; + if (changed.length === 0) return false; + const member = yield* requireRecord(memberOne(input)); + if (member.principal._tag === "person") + yield* sql`UPDATE kin_waiting SET resolved_at = ${input.leftAt}, resolution = 'cancelled' + WHERE org_id = ${input.orgId} AND chat_id = ${input.chatId} AND person_id = ${member.principal.personId} AND resolved_at IS NULL`; + return true; + }), + ); }, Effect.mapError(toRepositoryError("KinChatRepository.leaveChat")), ), addWaiting: Effect.fn("KinChatRepository.addWaiting")( function* (input) { + if (input.resolvedAt !== null || input.resolution !== null) + return yield* new KinChatError({ + reason: "invalid_state", + message: "New waiting items must be open.", + }); return yield* sql.withTransaction( Effect.gen(function* () { yield* requireRecord(chatOne(input)); yield* requireRecord(personOne(input)); + yield* requireRecord( + SqlSchema.findOneOption({ + Request: Schema.Unknown, + Result: MemberRow, + execute: () => sql`SELECT ${sql.literal(memberColumns)} FROM kin_chat_members + WHERE org_id = ${input.orgId} AND chat_id = ${input.chatId} AND person_id = ${input.personId} AND left_at IS NULL`, + })(input), + ); if (input.messageId !== null) { const message = yield* requireRecord( messageOne({ orgId: input.orgId, messageId: input.messageId }), @@ -758,6 +806,18 @@ const make = Effect.gen(function* () { }, Effect.mapError(toRepositoryError("KinChatRepository.createChat")), ), + findClientMessage: Effect.fn("KinChatRepository.findClientMessage")( + function (input) { + return SqlSchema.findOneOption({ + Request: Schema.Unknown, + Result: MessageRow, + execute: () => sql`SELECT ${sql.literal(messageColumns)} FROM kin_messages + WHERE org_id = ${input.orgId} AND chat_id = ${input.chatId} AND author_member_id = ${input.memberId} + AND client_message_id = ${`${input.kind}:${input.clientId}`}`, + })(input).pipe(NodeSqliteClient.readOnly); + }, + Effect.mapError(toRepositoryError("KinChatRepository.findClientMessage")), + ), insertMessage: Effect.fn("KinChatRepository.insertMessage")( function* (input) { return yield* sql.withTransaction( @@ -786,7 +846,7 @@ const make = Effect.gen(function* () { ) return yield* new KinChatError({ reason: "not_found", - message: "Kin member not found.", + message: "Kin record not found.", }); } if (memberId !== null && clientId !== null) { @@ -801,19 +861,33 @@ const make = Effect.gen(function* () { if ( author._tag === "agent" && (existing.value.author._tag !== "agent" || - existing.value.author.threadId !== author.threadId) + existing.value.author.threadId !== author.threadId || + existing.value.author.ownerPersonId !== author.ownerPersonId) ) return yield* new KinChatError({ reason: "not_allowed", message: "Kin message author identity conflict.", }); + if ( + existing.value.body !== input.body || + existing.value.intent !== input.intent || + existing.value.replyTo !== input.replyTo || + existing.value.widgetId !== input.widgetId || + existing.value.kind !== input.kind || + existing.value.mentions.length !== input.mentions.length || + !existing.value.mentions.every((id, index) => id === input.mentions[index]) + ) + return yield* new KinChatError({ + reason: "not_allowed", + message: "Kin message retry conflict.", + }); return existing.value; } } if (member !== null && member.leftAt !== null) return yield* new KinChatError({ reason: "not_found", - message: "Kin member not found.", + message: "Kin record not found.", }); const agent = author._tag === "agent" @@ -826,11 +900,12 @@ const make = Effect.gen(function* () { if ( agent.ownerPersonId !== author.ownerPersonId || thread.agentId !== agent.agentId || - thread.endedAt !== null + thread.endedAt !== null || + agent.retiredAt !== null ) return yield* new KinChatError({ reason: "not_found", - message: "Kin agent author not found.", + message: "Kin record not found.", }); } if (input.replyTo !== null) { @@ -869,10 +944,10 @@ const make = Effect.gen(function* () { const mentioned = yield* requireRecord( memberOne({ orgId: input.orgId, memberId: mention }), ); - if (mentioned.chatId !== input.chatId) + if (mentioned.chatId !== input.chatId || mentioned.leftAt !== null) return yield* new KinChatError({ reason: "not_found", - message: "Kin member not found.", + message: "Kin record not found.", }); } const mentions = yield* encodeMentions(input.mentions); @@ -884,14 +959,21 @@ const make = Effect.gen(function* () { WHERE chat_id = ${input.chatId} AND org_id = ${input.orgId} RETURNING last_seq`, })(input); const seq = (yield* requireRecord(Effect.succeed(allocated))).last_seq; - yield* sql`INSERT INTO kin_messages (message_id, org_id, chat_id, seq, author_kind, author_person_id, author_agent_id, + const inserted = + yield* sql`INSERT INTO kin_messages (message_id, org_id, chat_id, seq, author_kind, author_person_id, author_agent_id, author_owner_person_id, author_thread_id, author_member_id, author_role, kind, body, intent, mentions_json, reply_to, widget_id, floor_run_id, status, sent_by, client_message_id, created_at, edited_at) VALUES (${input.messageId}, ${input.orgId}, ${input.chatId}, ${seq}, ${author._tag}, ${member?.principal._tag === "person" ? member.principal.personId : null}, ${member?.principal._tag === "agent" ? member.principal.agentId : null}, ${agent?.ownerPersonId ?? null}, ${author._tag === "agent" ? author.threadId : null}, ${memberId}, ${member?.role ?? "member"}, ${input.kind}, ${input.body}, ${input.intent}, ${mentions}, ${input.replyTo}, - ${input.widgetId}, ${input.floorRunId}, ${input.status}, ${input.sentBy}, ${clientId}, ${input.createdAt}, ${input.editedAt})`; + ${input.widgetId}, ${input.floorRunId}, ${input.status}, ${input.sentBy}, ${clientId}, ${input.createdAt}, ${input.editedAt}) + ON CONFLICT DO NOTHING RETURNING message_id`; + if (inserted.length === 0) + return yield* new KinChatError({ + reason: "not_found", + message: "Kin record not found.", + }); return yield* requireRecord(messageOne(input)); }), ); @@ -904,12 +986,25 @@ const make = Effect.gen(function* () { .withTransaction( Effect.gen(function* () { const request = yield* decodeHistory(input); + const viewer = + input.viewerMemberId === undefined + ? null + : yield* requireRecord( + memberOne({ orgId: input.orgId, memberId: input.viewerMemberId }), + ); + if (viewer !== null && (viewer.chatId !== input.chatId || viewer.leftAt !== null)) + return yield* new KinChatError({ + reason: "not_found", + message: "Kin record not found.", + }); const rows = yield* SqlSchema.findAll({ Request: Schema.Unknown, Result: MessageRow, execute: () => sql`SELECT ${sql.literal(messageColumns)} FROM kin_messages WHERE org_id = ${input.orgId} - AND chat_id = ${input.chatId} AND seq < ${request.beforeSeq} ORDER BY seq DESC LIMIT ${request.limit + 1}`, + AND chat_id = ${input.chatId} AND seq < ${request.beforeSeq} + AND (${viewer === null || viewer.role === "owner" ? 1 : 0} = 1 OR status NOT IN ('suggested', 'dismissed') OR author_member_id = ${viewer?.memberId ?? null}) + ORDER BY seq DESC LIMIT ${request.limit + 1}`, })(input); const messages = rows.slice(0, request.limit).reverse(); const widgets = @@ -951,11 +1046,17 @@ const make = Effect.gen(function* () { yield* validateWidgetReferences(input); const state = yield* encodeWidgetState(input.state); const awaiting = yield* encodeAwaiting(input.awaiting); - yield* sql`INSERT INTO kin_widgets (widget_id, org_id, chat_id, message_id, widget_class, type, revision, state_json, + const inserted = + yield* sql`INSERT INTO kin_widgets (widget_id, org_id, chat_id, message_id, widget_class, type, revision, state_json, source_thread_id, source_item_id, feed_kind, feed_key, awaiting_json, pinned_at, closed_at, updated_at) VALUES (${input.widgetId}, ${input.orgId}, ${input.chatId}, ${input.messageId}, ${input.widgetClass}, ${input.type}, - ${input.revision}, ${state}, ${input.source?.threadId ?? null}, ${input.source?.itemId ?? null}, - ${input.feed?.kind ?? null}, ${input.feed?.key ?? null}, ${awaiting}, ${input.pinnedAt}, ${input.closedAt}, ${input.updatedAt})`; + 1, ${state}, ${input.source?.threadId ?? null}, ${input.source?.itemId ?? null}, + ${input.feed?.kind ?? null}, ${input.feed?.key ?? null}, ${awaiting}, ${input.pinnedAt}, ${input.closedAt}, ${input.updatedAt}) + ON CONFLICT DO NOTHING RETURNING widget_id`; + if (inserted.length === 0) + return yield* new KinChatError({ reason: "not_found", message: "Kin record not found." }); + yield* sql`UPDATE kin_messages SET widget_id = ${input.widgetId} + WHERE org_id = ${input.orgId} AND chat_id = ${input.chatId} AND message_id = ${input.messageId} AND widget_id IS NULL`; }, (effect) => sql.withTransaction(effect), Effect.mapError(toRepositoryError("KinChatRepository.insertWidget")), @@ -964,8 +1065,8 @@ const make = Effect.gen(function* () { function* (input) { return yield* sql.withTransaction( Effect.gen(function* () { - yield* requireRecord(widgetOne(input)); - yield* validateWidgetReferences(input); + const widget = yield* requireRecord(widgetOne(input)); + yield* validateWidgetReferences({ ...input, chatId: widget.chatId }); const state = yield* encodeWidgetState(input.state); const awaiting = yield* encodeAwaiting(input.awaiting); const updated = yield* SqlSchema.findOneOption({ diff --git a/apps/server/src/kin/chat/KinChatService.test.ts b/apps/server/src/kin/chat/KinChatService.test.ts new file mode 100644 index 0000000000000..c642c870a7edf --- /dev/null +++ b/apps/server/src/kin/chat/KinChatService.test.ts @@ -0,0 +1,708 @@ +import { assert, describe, it } from "@effect/vitest"; +import { + AuthSessionId, + AuthStandardClientScopes, + EnvironmentId, + KinAgentId, + KinChatId, + KinMemberId, + KinMessagesSendInput, + KinOrgId, + KinPersonId, + KinTaskCardState, + KinWaitingId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as PubSub from "effect/PubSub"; +import * as Stream from "effect/Stream"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; +import type { McpInvocationScope } from "../../mcp/McpInvocationContext.ts"; +import * as Sqlite from "../../persistence/Sqlite.ts"; +import * as KinPersistence from "../persistence/KinPersistence.ts"; +import * as Hub from "./KinChatHub.ts"; +import * as Repository from "./KinChatRepository.ts"; +import * as Identity from "./KinIdentity.ts"; +import * as Service from "./KinChatService.ts"; + +const decodeKinOrgId = Schema.decodeSync(KinOrgId); +const decodeKinPersonId = Schema.decodeSync(KinPersonId); +const decodeKinWaitingId = Schema.decodeSync(KinWaitingId); +const decodeKinChatId = Schema.decodeSync(KinChatId); +const decodeKinMemberId = Schema.decodeSync(KinMemberId); +const decodeThreadId = Schema.decodeSync(ThreadId); +const decodeSend = Schema.decodeUnknownEffect(KinMessagesSendInput); +const database = Layer.provideMerge(KinPersistence.layer, Sqlite.layerMemory); +const repositories = Layer.provideMerge(Repository.layer, database); +const dependencies = Layer.provideMerge(Hub.layer, repositories); +const layer = Layer.provideMerge(Service.layer, dependencies); +const identityLayer = Identity.KinIdentity.layer.pipe( + Layer.provide( + Layer.succeed(Identity.KinIdentityConfig, { + orgName: "Kin", + ownerHandle: "owner", + ownerDisplayName: "Owner", + }), + ), +); +const session: AuthenticatedSession = { + sessionId: Schema.decodeSync(AuthSessionId)("session"), + subject: "browser", + method: "browser-session-cookie", + scopes: AuthStandardClientScopes, +}; +const agentId = Schema.decodeSync(KinAgentId)("lead"); +const threadId = decodeThreadId("lead-thread"); +const caller: McpInvocationScope = { + environmentId: Schema.decodeSync(EnvironmentId)("environment"), + capabilities: new Set(), + issuedAt: 0, + requestNamespace: "test", + client: undefined, + thread: { + threadId, + providerSessionId: "provider-session", + providerInstanceId: Schema.decodeSync(ProviderInstanceId)("provider"), + }, +}; +const timestamp = "1970-01-01T00:00:00.000Z"; +const state = Schema.decodeSync(KinTaskCardState)({ + taskId: "task", + environmentId: "environment", + threadId, + remoteEnvironmentId: null, + title: "Work", + model: null, + status: "working", + pullRequests: [], + lastError: null, + updatedAt: timestamp, +}); +const seed = Effect.gen(function* () { + const repo = yield* Repository.KinChatRepository; + const service = yield* Service.KinChatService; + const identity = yield* Identity.KinIdentity.pipe(Effect.provide(identityLayer)); + const [person] = yield* identity.resolve(session); + assert.isDefined(person); + yield* repo.insertAgent({ + orgId: person.orgId, + agentId, + ownerPersonId: person.personId, + displayName: "Lead", + role: "lead", + createdAt: timestamp, + }); + yield* identity.registerAgentThread({ orgId: person.orgId, agentId, threadId }); + const agent = yield* identity.resolveAgent(caller); + const chat = yield* service.createDirect(person, { orgId: person.orgId, agentId }); + return { repo, service, identity, person, agent, chat }; +}); + +describe("KinChatService", () => { + it.effect( + "creates exactly two members, derives authors from identity, and deduplicates sends", + () => + Effect.gen(function* () { + const { repo, service, person, agent, chat } = yield* seed; + const retries = yield* Effect.all( + Array.from({ length: 5 }, () => + service.createDirect(person, { orgId: person.orgId, agentId }), + ), + { concurrency: "unbounded" }, + ); + assert.isTrue(retries.every((row) => row.chatId === chat.chatId)); + const members = yield* repo.listMembers(chat); + assert.strictEqual(members.length, 2); + assert.deepStrictEqual(members.map((row) => row.role).sort(), ["member", "owner"]); + const forged = yield* decodeSend({ + chatId: chat.chatId, + clientMessageId: "first", + body: "Hello", + author: { _tag: "system" }, + authorRole: "owner", + status: "posted", + }); + const mixedPerson = { ...person, agentId }; + const first = yield* service.send(mixedPerson, forged); + assert.strictEqual(first.author._tag, "human"); + assert.include(first.author, { personId: person.personId }); + assert.strictEqual(first.authorRole, "owner"); + assert.strictEqual(first.intent, null); + assert.deepStrictEqual(yield* service.send(person, forged), first); + for (const changed of [ + { body: "Changed retry" }, + { mentions: members.map((row) => row.memberId) }, + { replyTo: first.messageId }, + ]) + assert.include(yield* Effect.flip(service.send(person, { ...forged, ...changed })), { + reason: "not_allowed", + }); + const agentMember = members.find((row) => row.principal._tag === "agent"); + assert.isDefined(agentMember); + const mixedAgent = { ...agent, personId: person.personId }; + const posted = yield* service.send(mixedAgent, { + chatId: chat.chatId, + clientMessageId: "first", + body: "Evidence", + intent: "evidence", + }); + assert.deepStrictEqual(posted.author, { + _tag: "agent", + agentId, + ownerPersonId: person.personId, + threadId, + memberId: agentMember.memberId, + }); + assert.include( + yield* Effect.flip( + service.send(agent, { + chatId: chat.chatId, + clientMessageId: "first", + body: "Evidence", + intent: "answer", + }), + ), + { reason: "not_allowed" }, + ); + assert.strictEqual(posted.authorRole, "member"); + assert.strictEqual(posted.seq, 2); + const resumed = decodeThreadId("new-thread"); + yield* repo.registerAgentThread({ + orgId: agent.orgId, + agentId, + threadId: resumed, + startedAt: timestamp, + endedAt: null, + }); + assert.include( + yield* Effect.flip( + service.send( + { ...agent, threadId: resumed }, + { chatId: chat.chatId, clientMessageId: "first", body: "Retry", intent: "evidence" }, + ), + ), + { reason: "not_allowed" }, + ); + for (const operation of [ + service.send(agent, { chatId: chat.chatId, clientMessageId: "no-intent", body: "Hello" }), + service.send(person, { + chatId: chat.chatId, + clientMessageId: "human-intent", + body: "Hello", + intent: "decision", + }), + service.send(person, { chatId: chat.chatId, clientMessageId: "blank", body: " " }), + ]) + assert.include(yield* Effect.flip(operation), { reason: "invalid_state" }); + assert.deepStrictEqual( + (yield* service.history(person, { chatId: chat.chatId, beforeSeq: 3, limit: 1 })) + .messages, + [posted], + ); + }).pipe(Effect.provide(layer)), + ); + + it.effect("hides foreign org ids on every method and checks active membership and roles", () => + Effect.gen(function* () { + const { repo, service, person, agent, chat } = yield* seed; + const widget = yield* service.upsertWidget(agent, { + chatId: chat.chatId, + type: "task", + state, + awaiting: [person.personId], + }); + const [waiting] = yield* repo.listOpenWaiting(person); + assert.isDefined(waiting); + const foreign = { + _tag: "person", + orgId: decodeKinOrgId("other-org"), + personId: decodeKinPersonId("other-person"), + } as const; + yield* repo.insertOrg({ orgId: foreign.orgId, name: "Other", createdAt: timestamp }); + yield* repo.insertPerson({ + ...foreign, + handle: "other", + displayName: "Other", + githubLogin: null, + createdAt: timestamp, + }); + for (const operation of [ + service.createDirect(foreign, { orgId: person.orgId, agentId }), + service.send(foreign, { chatId: chat.chatId, body: "Hidden", clientMessageId: "foreign" }), + service.history(foreign, { chatId: chat.chatId, beforeSeq: 99, limit: 100 }), + service.markRead(foreign, { chatId: chat.chatId, seq: 1 }), + service.upsertWidget(foreign, { + chatId: chat.chatId, + widgetId: widget.widgetId, + revision: 1, + type: "task", + state, + }), + service.act(foreign, { + widgetId: widget.widgetId, + revision: 1, + actionId: "done", + clientActionId: "foreign", + }), + service.addWaiting(foreign, { + chatId: chat.chatId, + personId: person.personId, + messageId: null, + widgetId: null, + reason: "question", + }), + service.resolveWaiting(foreign, { waitingId: waiting.waitingId, resolution: "answered" }), + ]) + assert.include(yield* Effect.flip(operation), { reason: "not_found" }); + const outsider = { ...person, personId: decodeKinPersonId("outsider") }; + yield* repo.insertPerson({ + ...outsider, + handle: "outsider", + displayName: "Outsider", + githubLogin: null, + createdAt: timestamp, + }); + assert.include( + yield* Effect.flip( + service.history(outsider, { chatId: chat.chatId, beforeSeq: 99, limit: 100 }), + ), + { reason: "not_found" }, + ); + const guest = yield* repo.addMember({ + ...chat, + memberId: decodeKinMemberId("guest-member"), + principal: { _tag: "person", personId: outsider.personId }, + role: "guest", + joinedAt: timestamp, + leftAt: null, + mutedUntil: null, + }); + for (const operation of [ + service + .send(outsider, { chatId: chat.chatId, body: "Guest", clientMessageId: "guest" }) + .pipe(Effect.asVoid), + service + .act(outsider, { + widgetId: widget.widgetId, + revision: 1, + actionId: "done", + clientActionId: "guest", + }) + .pipe(Effect.asVoid), + service + .upsertWidget(outsider, { chatId: chat.chatId, type: "task", state }) + .pipe(Effect.asVoid), + ]) + assert.include(yield* Effect.flip(operation), { reason: "not_allowed" }); + const guestWaiting = yield* service.addWaiting(person, { + chatId: chat.chatId, + personId: outsider.personId, + messageId: null, + widgetId: null, + reason: "mention", + }); + assert.include( + yield* Effect.flip( + service.resolveWaiting(outsider, { + waitingId: guestWaiting.waitingId, + resolution: "done", + }), + ), + { reason: "not_allowed" }, + ); + yield* service.markRead(outsider, { chatId: chat.chatId, seq: 1 }); + yield* repo.leaveChat({ ...guest, leftAt: timestamp }); + assert.include( + yield* Effect.flip(service.markRead(outsider, { chatId: chat.chatId, seq: 1 })), + { reason: "not_found" }, + ); + assert.strictEqual( + Option.getOrThrow(yield* repo.getWaiting(guestWaiting)).resolution, + "cancelled", + ); + const rejoined = yield* repo.addMember({ ...guest, role: "member" }); + assert.strictEqual(rejoined.role, "member"); + yield* service.send(outsider, { + chatId: chat.chatId, + body: "Rejoined", + clientMessageId: "rejoined", + }); + yield* service.markRead(outsider, { chatId: chat.chatId, seq: 1 }); + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE kin_chat_members SET muted_until = '2099-01-01T00:00:00.000Z' WHERE org_id = ${person.orgId} AND agent_id = ${agentId}`; + assert.include( + yield* Effect.flip( + service.send(agent, { + chatId: chat.chatId, + body: "Muted", + clientMessageId: "muted", + intent: "answer", + }), + ), + { reason: "not_allowed" }, + ); + yield* sql`UPDATE kin_chat_members SET muted_until = NULL WHERE org_id = ${person.orgId} AND agent_id = ${agentId}`; + yield* repo.endAgentThread({ orgId: agent.orgId, threadId, endedAt: timestamp }); + assert.include( + yield* Effect.flip( + service.send(agent, { + chatId: chat.chatId, + body: "Ended", + clientMessageId: "ended", + intent: "answer", + }), + ), + { reason: "not_allowed" }, + ); + }).pipe(Effect.provide(layer)), + ); + + it.effect( + "validates widget states, owns ids and revisions, resolves awaiting, and makes actions retryable", + () => + Effect.gen(function* () { + const { repo, service, person, agent, chat } = yield* seed; + for (const input of [ + { type: "approval", state }, + { type: "unknown", state }, + { type: "task", state: {} }, + { type: "task", state, revision: 8 }, + ]) { + assert.include( + yield* Effect.flip(service.upsertWidget(agent, { chatId: chat.chatId, ...input })), + { reason: input.type === "approval" ? "use_approvals" : "invalid_state" }, + ); + } + assert.strictEqual(Option.getOrThrow(yield* repo.getChat(chat)).lastSeq, 0); + const widget = yield* service.upsertWidget(agent, { + chatId: chat.chatId, + type: "task", + state, + awaiting: [person.personId], + }); + assert.strictEqual(widget.revision, 1); + assert.strictEqual( + Option.getOrThrow(yield* repo.getMessage(widget)).widgetId, + widget.widgetId, + ); + const input = { + widgetId: widget.widgetId, + revision: 1, + actionId: "done", + clientActionId: "action", + value: { checked: true }, + }; + assert.include(yield* Effect.flip(service.act(person, { ...input, revision: 2 })), { + reason: "widget_changed", + }); + const action = yield* service.act(person, input); + assert.strictEqual(action.kind, "widget_action"); + assert.strictEqual(action.author._tag, "human"); + assert.deepStrictEqual(JSON.parse(action.body), { + widgetId: widget.widgetId, + revision: 1, + actionId: "done", + value: { checked: true }, + }); + assert.deepStrictEqual(yield* repo.listOpenWaiting(person), []); + const updated = yield* service.upsertWidget(agent, { + chatId: chat.chatId, + widgetId: widget.widgetId, + revision: 1, + type: "task", + state: { ...state, status: "done" }, + awaiting: [person.personId], + }); + assert.strictEqual(updated.revision, 2); + assert.deepStrictEqual(yield* service.act(person, input), action); + assert.include(yield* Effect.flip(service.act(person, { ...input, actionId: "changed" })), { + reason: "not_allowed", + }); + assert.strictEqual((yield* repo.listOpenWaiting(person)).length, 1); + yield* service.upsertWidget(agent, { + chatId: chat.chatId, + widgetId: widget.widgetId, + revision: 2, + type: "task", + state, + awaiting: [], + }); + assert.deepStrictEqual(yield* repo.listOpenWaiting(person), []); + const another = yield* service.upsertWidget(agent, { + chatId: chat.chatId, + type: "task", + state, + awaiting: [person.personId], + }); + assert.include( + yield* Effect.flip(service.act(person, { ...input, widgetId: another.widgetId })), + { reason: "not_allowed" }, + ); + yield* service.upsertWidget(agent, { + chatId: chat.chatId, + widgetId: another.widgetId, + revision: 1, + type: "task", + state, + closed: true, + }); + assert.deepStrictEqual(yield* repo.listOpenWaiting(person), []); + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE kin_widgets SET type = 'approval' WHERE org_id = ${person.orgId} AND widget_id = ${another.widgetId}`; + assert.include( + yield* Effect.flip( + service.act(person, { + ...input, + widgetId: another.widgetId, + revision: 2, + clientActionId: "approval", + }), + ), + { reason: "use_approvals" }, + ); + }).pipe(Effect.provide(layer)), + ); + + it.effect( + "publishes question waiting and reply resolution, rolls back atomically, and keeps read state monotonic", + () => + Effect.gen(function* () { + const { repo, service, person, agent, chat } = yield* seed; + const hub = yield* Hub.KinChatHub; + const events = yield* hub.subscribe(person.orgId); + const sql = yield* SqlClient.SqlClient; + const input = { + chatId: chat.chatId, + body: "Ready?", + intent: "question", + clientMessageId: "question", + } as const; + yield* sql + .withTransaction(service.send(agent, input).pipe(Effect.andThen(Effect.fail("rollback")))) + .pipe(Effect.flip); + assert.deepStrictEqual(yield* PubSub.takeUpTo(events, 20), []); + assert.deepStrictEqual(yield* repo.listOpenWaiting(person), []); + const question = yield* service.send(agent, input); + assert.strictEqual(question.seq, 1); + assert.strictEqual((yield* PubSub.take(events)).type, "message.posted"); + assert.strictEqual((yield* PubSub.take(events)).type, "waiting.updated"); + assert.strictEqual((yield* repo.listOpenWaiting(person)).length, 1); + assert.deepStrictEqual(yield* service.send(agent, input), question); + assert.deepStrictEqual(yield* PubSub.takeUpTo(events, 20), []); + yield* service.send(person, { chatId: chat.chatId, body: "Yes", clientMessageId: "reply" }); + assert.strictEqual((yield* PubSub.take(events)).type, "message.posted"); + const resolved = yield* PubSub.take(events); + assert.strictEqual(resolved.type, "waiting.updated"); + if (resolved.type === "waiting.updated") + assert.strictEqual(resolved.item.resolution, "answered"); + assert.deepStrictEqual(yield* repo.listOpenWaiting(person), []); + const member = (yield* repo.listMembersByPerson(person))[0]; + assert.isDefined(member); + assert.strictEqual(yield* repo.unreadCount(member), 1); + yield* service.markRead(person, { chatId: chat.chatId, seq: 999 }); + yield* service.markRead(person, { chatId: chat.chatId, seq: 0 }); + assert.strictEqual(Option.getOrThrow(yield* repo.getReadState(member)).lastReadSeq, 2); + assert.strictEqual(yield* repo.unreadCount(member), 0); + const read = yield* PubSub.take(events); + assert.include(read, { type: "read.updated", seq: 2 }); + assert.deepStrictEqual(yield* PubSub.takeUpTo(events, 20), []); + const approval = { + orgId: person.orgId, + chatId: chat.chatId, + waitingId: decodeKinWaitingId("server-approval"), + personId: person.personId, + messageId: question.messageId, + widgetId: null, + reason: "approval", + createdAt: timestamp, + resolvedAt: null, + resolution: null, + } as const; + yield* repo.addWaiting(approval); + const humanQuestion = yield* service.send(person, { + chatId: chat.chatId, + body: "Another question", + clientMessageId: "human-question", + }); + const anotherQuestion = yield* service.addWaiting(person, { + ...approval, + reason: "question", + messageId: humanQuestion.messageId, + }); + const ownQuestion = yield* service.addWaiting(agent, { + ...approval, + reason: "question", + }); + for (const operation of [ + service.addWaiting(agent, { ...approval }), + service.resolveWaiting(agent, { waitingId: approval.waitingId, resolution: "approved" }), + service.resolveWaiting(person, { waitingId: approval.waitingId, resolution: "approved" }), + service.resolveWaiting(agent, { + waitingId: anotherQuestion.waitingId, + resolution: "answered", + }), + ]) + assert.include(yield* Effect.flip(operation), { reason: "not_allowed" }); + const approvalWidget = yield* service.upsertWidget(agent, { + chatId: chat.chatId, + type: "task", + state, + }); + yield* sql`UPDATE kin_widgets SET type = 'approval' WHERE org_id = ${person.orgId} AND widget_id = ${approvalWidget.widgetId}`; + for (const identity of [person, agent]) + for (const widgetId of [null, approvalWidget.widgetId]) + assert.include( + yield* Effect.flip( + service.addWaiting(identity, { + ...approval, + reason: "question", + widgetId, + messageId: approvalWidget.messageId, + }), + ), + { reason: "not_allowed" }, + ); + assert.strictEqual( + (yield* service.resolveWaiting(agent, { + waitingId: ownQuestion.waitingId, + resolution: "answered", + })).resolution, + "answered", + ); + const waiting = yield* service.addWaiting(agent, { + chatId: chat.chatId, + personId: person.personId, + messageId: question.messageId, + widgetId: null, + reason: "mention", + }); + const done = yield* service.resolveWaiting(person, { + waitingId: waiting.waitingId, + resolution: "done", + }); + assert.strictEqual(done.resolution, "done"); + assert.deepStrictEqual( + yield* service.resolveWaiting(person, { + waitingId: waiting.waitingId, + resolution: "again", + }), + done, + ); + }).pipe(Effect.provide(layer)), + ); + it.effect("filters every hub event against current viewer membership at delivery", () => + Effect.gen(function* () { + const { repo, service, person, agent, chat } = yield* seed; + const hub = yield* Hub.KinChatHub; + const viewer = yield* hub.subscribeForViewer(person); + const other = yield* repo.createChat({ + ...chat, + chatId: decodeKinChatId("other-chat"), + kind: "project_group", + directKey: null, + }); + const agentMember = (yield* repo.listMembers(chat)).find( + (row) => row.principal._tag === "agent", + ); + const personMember = (yield* repo.listMembers(chat)).find( + (row) => row.principal._tag === "person", + ); + assert.isDefined(agentMember); + assert.isDefined(personMember); + yield* repo.addMember({ + ...agentMember, + chatId: other.chatId, + memberId: decodeKinMemberId("other-agent"), + }); + const message = yield* service.send(agent, { + chatId: other.chatId, + body: "Private", + clientMessageId: "private", + intent: "answer", + }); + const widget = yield* service.upsertWidget(agent, { + chatId: other.chatId, + type: "task", + state, + }); + const events: ReadonlyArray = [ + { type: "chat.created", orgId: person.orgId, chat: other }, + { type: "message.posted", orgId: person.orgId, message }, + { + type: "message.posted", + orgId: person.orgId, + message: { ...message, status: "suggested" }, + }, + { type: "widget.updated", orgId: person.orgId, widget }, + { + type: "waiting.updated", + orgId: person.orgId, + item: { + orgId: person.orgId, + chatId: other.chatId, + waitingId: decodeKinWaitingId("private-waiting"), + personId: person.personId, + messageId: message.messageId, + widgetId: null, + reason: "suggestion", + createdAt: timestamp, + resolvedAt: null, + resolution: null, + }, + }, + { + type: "read.updated", + orgId: person.orgId, + chatId: other.chatId, + memberId: agentMember.memberId, + seq: 1, + }, + ]; + for (const event of events) yield* hub.publish(event); + const marker: Hub.KinChatHubEvent = { + type: "read.updated", + orgId: person.orgId, + chatId: chat.chatId, + memberId: personMember.memberId, + seq: 0, + }; + yield* hub.publish(marker); + assert.deepStrictEqual(Option.getOrThrow(yield* Stream.runHead(viewer)), marker); + const joined = yield* repo.addMember({ + ...personMember, + chatId: other.chatId, + memberId: decodeKinMemberId("other-person"), + }); + for (const event of events) yield* hub.publish(event); + yield* repo.leaveChat({ ...joined, leftAt: timestamp }); + yield* hub.publish(marker); + assert.deepStrictEqual(Option.getOrThrow(yield* Stream.runHead(viewer)), marker); + yield* repo.addMember(joined); + for (const event of events) yield* hub.publish(event); + assert.deepStrictEqual( + yield* Stream.runCollect(viewer.pipe(Stream.take(events.length))), + events, + ); + const agentViewer = yield* hub.subscribeForViewer(agent); + const suggestion: Hub.KinChatHubEvent = { + type: "message.posted", + orgId: person.orgId, + message: { + ...message, + chatId: chat.chatId, + status: "suggested", + author: { _tag: "human", personId: person.personId, memberId: personMember.memberId }, + }, + }; + yield* hub.publish(suggestion); + yield* hub.publish(marker); + assert.deepStrictEqual(Option.getOrThrow(yield* Stream.runHead(agentViewer)), marker); + assert.deepStrictEqual(Option.getOrThrow(yield* Stream.runHead(viewer)), suggestion); + }).pipe(Effect.provide(layer)), + ); +}); diff --git a/apps/server/src/kin/chat/KinChatService.ts b/apps/server/src/kin/chat/KinChatService.ts new file mode 100644 index 0000000000000..970b125421c54 --- /dev/null +++ b/apps/server/src/kin/chat/KinChatService.ts @@ -0,0 +1,555 @@ +import { + KinChatError, + KinChatId, + KinMemberId, + KinMessageId, + KinWaitingId, + KinWidgetId, + KinMessagesSendInput, + KinWidgetsActInput, + KinAgentIntent, + type KinAuthor, + type KinChat, + type KinChatHistoryInput, + type KinChatHistoryResult, + type KinChatMember, + type KinChatsCreateDirectInput, + type KinMessage, + type KinMessagesMarkReadInput, + type KinPersonId, + type KinWaitingItem, + type KinWidget, +} from "@t3tools/contracts"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +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 * as SqlError from "effect/sql/SqlError"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import { toPersistenceSqlError } from "../../persistence/Errors.ts"; +import { validateState } from "../widgets/registry.ts"; +import * as Hub from "./KinChatHub.ts"; +import * as Repository from "./KinChatRepository.ts"; +import type { AgentIdentity, PersonIdentity } from "./KinIdentity.ts"; + +type Identity = PersonIdentity | AgentIdentity; +type ServiceError = Repository.RepositoryError; +type SendInput = KinMessagesSendInput & { readonly intent?: KinAgentIntent }; +type WidgetUpsertInput = { + readonly chatId: KinChatId; + readonly widgetId?: KinWidgetId; + readonly revision?: number; + readonly type: string; + readonly state: unknown; + readonly awaiting?: ReadonlyArray; + readonly closed?: boolean; +}; +type WaitingInput = Pick< + KinWaitingItem, + "chatId" | "personId" | "messageId" | "widgetId" | "reason" +>; + +export class KinChatService extends Context.Service< + KinChatService, + { + readonly createDirect: ( + identity: PersonIdentity, + input: KinChatsCreateDirectInput, + ) => Effect.Effect; + readonly send: ( + identity: Identity, + input: SendInput, + ) => Effect.Effect; + readonly history: ( + identity: Identity, + input: KinChatHistoryInput, + ) => Effect.Effect; + readonly markRead: ( + identity: Identity, + input: KinMessagesMarkReadInput, + ) => Effect.Effect; + readonly upsertWidget: ( + identity: Identity, + input: WidgetUpsertInput, + ) => Effect.Effect; + readonly act: ( + identity: PersonIdentity, + input: KinWidgetsActInput, + ) => Effect.Effect; + readonly addWaiting: ( + identity: Identity, + input: WaitingInput, + ) => Effect.Effect; + readonly resolveWaiting: ( + identity: Identity, + input: { readonly waitingId: KinWaitingId; readonly resolution: string }, + ) => Effect.Effect; + } +>()("t3/kin/chat/KinChatService") {} + +const decodeChatId = Schema.decodeEffect(KinChatId); +const decodeMemberId = Schema.decodeEffect(KinMemberId); +const decodeMessageId = Schema.decodeEffect(KinMessageId); +const decodeWidgetId = Schema.decodeEffect(KinWidgetId); +const decodeWaitingId = Schema.decodeEffect(KinWaitingId); +const decodeSend = Schema.decodeEffect(KinMessagesSendInput); +const decodeIntent = Schema.decodeEffect(KinAgentIntent); +const decodeAct = Schema.decodeEffect(KinWidgetsActInput); +const encodeAction = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); +const invalidState = new KinChatError({ reason: "invalid_state", message: "Invalid chat input." }); +const notFound = new KinChatError({ reason: "not_found", message: "Kin record not found." }); +const notAllowed = new KinChatError({ + reason: "not_allowed", + message: "Chat operation not allowed.", +}); +const requireRecord = Effect.fn("KinChatService.requireRecord")(function* ( + effect: Effect.Effect, E, R>, +) { + const value = yield* effect; + return Option.isSome(value) ? value.value : yield* notFound; +}); + +const make = Effect.gen(function* () { + const repo = yield* Repository.KinChatRepository; + const hub = yield* Hub.KinChatHub; + const sql = yield* SqlClient.SqlClient; + const transaction = (effect: Effect.Effect) => + sql + .withTransaction(effect) + .pipe( + Effect.mapError((cause) => + SqlError.isSqlError(cause) + ? toPersistenceSqlError("KinChatService.transaction")(cause) + : cause, + ), + ); + const now = DateTime.now.pipe(Effect.map(DateTime.formatIso)); + const memberFor = Effect.fn("KinChatService.memberFor")(function* ( + identity: Identity, + chatId: KinChatId, + ) { + const chat = yield* requireRecord(repo.getChat({ orgId: identity.orgId, chatId })); + const members = yield* repo.listMembers(chat); + const member = members.find( + (row) => + row.leftAt === null && + (identity._tag === "person" + ? row.principal._tag === "person" && row.principal.personId === identity.personId + : row.principal._tag === "agent" && row.principal.agentId === identity.agentId), + ); + if (member === undefined) return yield* notFound; + if (identity._tag === "agent") { + const agent = yield* requireRecord(repo.getAgent(identity)); + const thread = yield* requireRecord(repo.getAgentThread(identity)); + if ( + agent.retiredAt !== null || + thread.endedAt !== null || + thread.agentId !== agent.agentId || + agent.ownerPersonId !== identity.ownerPersonId + ) + return yield* notAllowed; + } + return member; + }); + const authorFor = (identity: Identity, member: KinChatMember): KinAuthor => + identity._tag === "person" + ? { _tag: "human", personId: identity.personId, memberId: member.memberId } + : { + _tag: "agent", + agentId: identity.agentId, + ownerPersonId: identity.ownerPersonId, + threadId: identity.threadId, + memberId: member.memberId, + }; + const canWrite = Effect.fn("KinChatService.canWrite")(function* ( + identity: Identity, + member: KinChatMember, + ) { + if (member.role === "guest") return yield* notAllowed; + if ( + identity._tag === "agent" && + member.mutedUntil !== null && + Date.parse(member.mutedUntil) > (yield* Clock.currentTimeMillis) + ) + return yield* notAllowed; + }); + const resolve = Effect.fn("KinChatService.resolve")(function* ( + item: KinWaitingItem, + resolution: string, + ) { + if (yield* repo.resolveWaiting({ ...item, resolution, resolvedAt: yield* now })) { + const updated = yield* requireRecord(repo.getWaiting(item)); + yield* hub.publish({ type: "waiting.updated", orgId: item.orgId, item: updated }); + return updated; + } + return item; + }); + const add = Effect.fn("KinChatService.add")(function* (identity: Identity, input: WaitingInput) { + const member = yield* memberFor(identity, input.chatId); + yield* canWrite(identity, member); + const waitingId = yield* decodeWaitingId(SecureRandom.uuidV4Unsafe()).pipe(Effect.orDie); + const item: KinWaitingItem = { + ...input, + orgId: identity.orgId, + waitingId, + createdAt: yield* now, + resolvedAt: null, + resolution: null, + }; + if (yield* repo.addWaiting(item)) { + yield* hub.publish({ type: "waiting.updated", orgId: identity.orgId, item }); + return item; + } + const existing = (yield* repo.listOpenWaiting({ + orgId: identity.orgId, + personId: input.personId, + })).find((row) => row.widgetId === input.widgetId && row.chatId === input.chatId); + if (existing === undefined) return yield* notFound; + return existing; + }); + const post = Effect.fn("KinChatService.post")(function* ( + identity: Identity, + member: KinChatMember, + input: { + readonly chatId: KinChatId; + readonly body: string; + readonly intent: KinAgentIntent | null; + readonly mentions: ReadonlyArray; + readonly replyTo: KinMessageId | null; + readonly widgetId: KinWidgetId | null; + readonly kind: "text" | "widget_action"; + readonly publish?: boolean; + readonly clientId: { readonly kind: "send" | "act"; readonly id: string } | null; + }, + ) { + const messageId = yield* decodeMessageId(SecureRandom.uuidV4Unsafe()).pipe(Effect.orDie); + const message = yield* repo.insertMessage({ + orgId: identity.orgId, + chatId: input.chatId, + messageId, + author: authorFor(identity, member), + kind: input.kind, + body: input.body, + intent: input.intent, + mentions: input.mentions, + replyTo: input.replyTo, + widgetId: input.widgetId, + floorRunId: null, + status: "posted", + sentBy: null, + clientMessageId: input.clientId, + createdAt: yield* now, + editedAt: null, + }); + if (message.messageId !== messageId || input.publish === false) return message; + yield* hub.publish({ type: "message.posted", orgId: identity.orgId, message }); + if (message.author._tag === "agent" && message.intent === "question") { + const chat = yield* requireRecord(repo.getChat(member)); + const members = yield* repo.listMembers(member); + for (const recipient of members) { + if (recipient.leftAt !== null || recipient.principal._tag !== "person") continue; + if (chat.kind !== "direct" && !message.mentions.includes(recipient.memberId)) continue; + yield* add(identity, { + chatId: message.chatId, + personId: recipient.principal.personId, + messageId: message.messageId, + widgetId: null, + reason: "question", + }); + } + } + if (identity._tag === "person") { + for (const item of yield* repo.listOpenWaiting(identity)) { + if (item.chatId !== message.chatId || item.reason !== "question" || item.messageId === null) + continue; + const question = yield* requireRecord( + repo.getMessage({ orgId: identity.orgId, messageId: item.messageId }), + ); + if (question.seq < message.seq) yield* resolve(item, "answered"); + } + } + return message; + }); + return KinChatService.of({ + createDirect: Effect.fn("KinChatService.createDirect")(function* (identity, input) { + if (identity.orgId !== input.orgId) return yield* notFound; + const person = yield* requireRecord(repo.getPerson(identity)); + const agent = yield* requireRecord(repo.getAgent(input)); + if (agent.ownerPersonId !== person.personId || agent.retiredAt !== null) + return yield* notAllowed; + const chatId = yield* decodeChatId(SecureRandom.uuidV4Unsafe()).pipe(Effect.orDie); + const chat = yield* repo.createChat({ + orgId: identity.orgId, + chatId, + kind: "direct", + directKey: `${person.personId}:${agent.agentId}`, + title: null, + teamId: null, + lastMessageAt: null, + createdAt: yield* now, + archivedAt: null, + }); + if (chat.chatId !== chatId) { + yield* memberFor(identity, chat.chatId); + return chat; + } + for (const principal of [ + { _tag: "person", personId: person.personId }, + { _tag: "agent", agentId: agent.agentId }, + ] as const) { + yield* repo.addMember({ + orgId: chat.orgId, + chatId: chat.chatId, + memberId: yield* decodeMemberId(SecureRandom.uuidV4Unsafe()).pipe(Effect.orDie), + principal, + role: principal._tag === "person" ? "owner" : "member", + joinedAt: chat.createdAt, + leftAt: null, + mutedUntil: null, + }); + } + yield* hub.publish({ type: "chat.created", orgId: identity.orgId, chat }); + return chat; + }, transaction), + send: Effect.fn("KinChatService.send")(function* (identity, input) { + const request = yield* decodeSend(input).pipe(Effect.mapError(() => invalidState)); + const member = yield* memberFor(identity, request.chatId); + yield* canWrite(identity, member); + if ( + (identity._tag === "agent" && input.intent === undefined) || + (identity._tag === "person" && input.intent !== undefined) + ) + return yield* invalidState; + const intent = + input.intent === undefined + ? null + : yield* decodeIntent(input.intent).pipe(Effect.mapError(() => invalidState)); + return yield* post(identity, member, { + ...request, + kind: "text", + intent, + mentions: request.mentions ?? [], + replyTo: request.replyTo ?? null, + widgetId: null, + clientId: { kind: "send", id: request.clientMessageId }, + }); + }, transaction), + history: Effect.fn("KinChatService.history")( + function* (identity, input) { + const member = yield* memberFor(identity, input.chatId); + return yield* repo.history({ + ...input, + orgId: identity.orgId, + viewerMemberId: member.memberId, + }); + }, + (effect) => transaction(effect).pipe(NodeSqliteClient.readOnly), + ), + markRead: Effect.fn("KinChatService.markRead")(function* (identity, input) { + const member = yield* memberFor(identity, input.chatId); + const previous = yield* repo.getReadState(member); + yield* repo.markRead({ ...member, seq: input.seq, updatedAt: yield* now }); + const updated = yield* requireRecord(repo.getReadState(member)); + if (Option.isNone(previous) || updated.lastReadSeq !== previous.value.lastReadSeq) + yield* hub.publish({ + type: "read.updated", + orgId: identity.orgId, + chatId: input.chatId, + memberId: member.memberId, + seq: updated.lastReadSeq, + }); + }, transaction), + upsertWidget: Effect.fn("KinChatService.upsertWidget")(function* (identity, input) { + const member = yield* memberFor(identity, input.chatId); + yield* canWrite(identity, member); + if (input.type === "approval") + return yield* new KinChatError({ + reason: "use_approvals", + message: "Use the signed approvals service.", + }); + const state = yield* validateState(input.type, input.state); + let widget: KinWidget; + if (input.widgetId === undefined) { + if (input.revision !== undefined) return yield* invalidState; + const message = yield* post(identity, member, { + chatId: input.chatId, + body: "", + intent: identity._tag === "agent" ? "answer" : null, + kind: "text", + mentions: [], + replyTo: null, + widgetId: null, + clientId: null, + publish: false, + }); + widget = { + orgId: identity.orgId, + chatId: input.chatId, + widgetId: yield* decodeWidgetId(SecureRandom.uuidV4Unsafe()).pipe(Effect.orDie), + messageId: message.messageId, + widgetClass: "native", + type: input.type, + revision: 1, + state, + source: null, + feed: null, + awaiting: input.closed === true ? [] : (input.awaiting ?? []), + pinnedAt: null, + closedAt: input.closed === true ? yield* now : null, + updatedAt: yield* now, + }; + yield* repo.insertWidget(widget); + const anchor = yield* requireRecord( + repo.getMessage({ orgId: identity.orgId, messageId: message.messageId }), + ); + yield* hub.publish({ type: "message.posted", orgId: identity.orgId, message: anchor }); + } else { + const existing = yield* requireRecord( + repo.getWidget({ orgId: identity.orgId, widgetId: input.widgetId }), + ); + if (existing.chatId !== input.chatId) return yield* notFound; + if (existing.type !== input.type || input.revision === undefined) + return yield* invalidState; + widget = yield* repo.updateWidget({ + ...existing, + state, + awaiting: + input.closed === true || (input.closed === undefined && existing.closedAt !== null) + ? [] + : (input.awaiting ?? existing.awaiting), + expectedRevision: input.revision, + closedAt: + input.closed === undefined ? existing.closedAt : input.closed ? yield* now : null, + updatedAt: yield* now, + }); + } + for (const person of yield* repo.listMembers(member)) { + if (person.principal._tag !== "person") continue; + const personId = person.principal.personId; + for (const item of yield* repo.listOpenWaiting({ orgId: identity.orgId, personId })) { + if ( + item.widgetId === widget.widgetId && + (widget.closedAt !== null || !widget.awaiting.includes(personId)) + ) + yield* resolve(item, widget.closedAt !== null ? "closed" : "superseded"); + } + } + if (widget.closedAt === null) + for (const personId of new Set(widget.awaiting)) + yield* add(identity, { + chatId: widget.chatId, + personId, + messageId: widget.messageId, + widgetId: widget.widgetId, + reason: "decision", + }); + yield* hub.publish({ type: "widget.updated", orgId: identity.orgId, widget }); + return widget; + }, transaction), + act: Effect.fn("KinChatService.act")(function* (identity, input) { + const request = yield* decodeAct(input).pipe(Effect.mapError(() => invalidState)); + const widget = yield* requireRecord( + repo.getWidget({ orgId: identity.orgId, widgetId: request.widgetId }), + ); + const member = yield* memberFor(identity, widget.chatId); + yield* canWrite(identity, member); + if (widget.type === "approval") + return yield* new KinChatError({ + reason: "use_approvals", + message: "Use the signed approvals service.", + }); + const body = yield* encodeAction({ + widgetId: request.widgetId, + revision: request.revision, + actionId: request.actionId, + ...(request.value === undefined ? {} : { value: request.value }), + }).pipe(Effect.mapError(() => invalidState)); + const previous = yield* repo.findClientMessage({ + ...member, + kind: "act", + clientId: request.clientActionId, + }); + if (Option.isSome(previous)) { + if ( + previous.value.author._tag !== "human" || + previous.value.author.personId !== identity.personId || + previous.value.widgetId !== request.widgetId || + previous.value.body !== body + ) + return yield* notAllowed; + return previous.value; + } + if (widget.revision !== request.revision) + return yield* new KinChatError({ + reason: "widget_changed", + message: "Widget revision changed.", + }); + if (widget.closedAt !== null) return yield* invalidState; + const message = yield* post(identity, member, { + chatId: widget.chatId, + kind: "widget_action", + body, + intent: null, + mentions: [], + replyTo: widget.messageId, + widgetId: widget.widgetId, + clientId: { kind: "act", id: request.clientActionId }, + }); + for (const item of yield* repo.listOpenWaiting(identity)) + if (item.widgetId === widget.widgetId) yield* resolve(item, "acted"); + return message; + }, transaction), + addWaiting: Effect.fn("KinChatService.addWaiting")(function* (identity, input) { + yield* memberFor(identity, input.chatId); + if (input.reason === "approval") return yield* notAllowed; + const message = + input.messageId === null + ? null + : yield* requireRecord( + repo.getMessage({ orgId: identity.orgId, messageId: input.messageId }), + ); + if (message !== null && message.chatId !== input.chatId) return yield* notFound; + for (const widgetId of new Set([input.widgetId, message?.widgetId ?? null])) { + if (widgetId === null) continue; + const widget = yield* requireRecord(repo.getWidget({ orgId: identity.orgId, widgetId })); + if (widget.chatId !== input.chatId) return yield* notFound; + if (widget.type === "approval") return yield* notAllowed; + } + return yield* add(identity, input); + }, transaction), + resolveWaiting: Effect.fn("KinChatService.resolveWaiting")(function* (identity, input) { + if (input.resolution.trim().length === 0) return yield* invalidState; + const item = yield* requireRecord( + repo.getWaiting({ orgId: identity.orgId, waitingId: input.waitingId }), + ); + const member = yield* memberFor(identity, item.chatId); + if (member.role === "guest" || item.reason === "approval") return yield* notAllowed; + const message = + item.messageId === null + ? null + : yield* requireRecord( + repo.getMessage({ orgId: identity.orgId, messageId: item.messageId }), + ); + for (const widgetId of new Set([item.widgetId, message?.widgetId ?? null])) { + if (widgetId === null) continue; + const widget = yield* requireRecord(repo.getWidget({ orgId: identity.orgId, widgetId })); + if (widget.type === "approval") return yield* notAllowed; + } + if (identity._tag === "agent") { + if (item.reason !== "question" || message === null) return yield* notAllowed; + if (message.author._tag !== "agent" || message.author.agentId !== identity.agentId) + return yield* notAllowed; + } else if (member.role !== "owner" && identity.personId !== item.personId) { + return yield* notAllowed; + } + return yield* resolve(item, input.resolution); + }, transaction), + }); +}); + +export const layer = Layer.effect(KinChatService, make); diff --git a/apps/server/src/kin/chat/KinIdentity.test.ts b/apps/server/src/kin/chat/KinIdentity.test.ts index ab1c7ea10d94f..072b3e916be38 100644 --- a/apps/server/src/kin/chat/KinIdentity.test.ts +++ b/apps/server/src/kin/chat/KinIdentity.test.ts @@ -309,6 +309,7 @@ describe("KinIdentity", () => { assert.deepStrictEqual(yield* repository.getAgentThread(input), original); assert.isTrue(identity.isAgentThread(threadId)); assert.deepStrictEqual(yield* identity.resolveAgent(caller()), { + _tag: "agent", ...input, ownerPersonId: owner.personId, }); @@ -381,6 +382,7 @@ describe("KinIdentity", () => { const restarted = yield* startInScope(secondScope); assert.isTrue(restarted.isAgentThread(threadId)); assert.deepStrictEqual(yield* restarted.resolveAgent(caller()), { + _tag: "agent", ...input, ownerPersonId: owner.personId, }); @@ -405,6 +407,7 @@ describe("KinIdentity", () => { assert.isFalse(afterEnd.isAgentThread(threadId)); assert.isTrue(afterEnd.isAgentThread(secondThreadId)); assert.deepStrictEqual(yield* afterEnd.resolveAgent(caller(secondThreadId)), { + _tag: "agent", ...input, threadId: secondThreadId, ownerPersonId: owner.personId, diff --git a/apps/server/src/kin/chat/KinIdentity.ts b/apps/server/src/kin/chat/KinIdentity.ts index 8ca9e73cc07c1..df99409c662d2 100644 --- a/apps/server/src/kin/chat/KinIdentity.ts +++ b/apps/server/src/kin/chat/KinIdentity.ts @@ -42,8 +42,13 @@ export class KinIdentityConfig extends Context.Service< } type IdentityError = KinChatRepository.RepositoryError; -export type PersonIdentity = { readonly orgId: KinOrgId; readonly personId: KinPersonId }; +export type PersonIdentity = { + readonly _tag: "person"; + readonly orgId: KinOrgId; + readonly personId: KinPersonId; +}; export type AgentIdentity = { + readonly _tag: "agent"; readonly orgId: KinOrgId; readonly agentId: KinAgentId; readonly ownerPersonId: KinPersonId; @@ -93,7 +98,7 @@ export class KinIdentity extends Context.Service< resolve: Effect.fn("KinIdentity.resolve")(function (session) { return Effect.succeed( AuthStandardClientScopes.every((scope) => session.scopes.includes(scope)) - ? [{ orgId: owner.orgId, personId: owner.personId }] + ? [{ _tag: "person", orgId: owner.orgId, personId: owner.personId }] : [], ); }), @@ -118,6 +123,7 @@ export class KinIdentity extends Context.Service< message: "Kin agent identity required.", }); return { + _tag: "agent", orgId: row.value.orgId, agentId: agent.value.agentId, ownerPersonId: agent.value.ownerPersonId, @@ -146,7 +152,7 @@ export class KinIdentity extends Context.Service< if (Option.isNone(row)) return yield* new KinChatError({ reason: "not_found", - message: "Kin agent thread not found.", + message: "Kin record not found.", }); const ended = yield* repository.endAgentThread({ ...input, diff --git a/apps/server/src/kin/widgets/registry.test.ts b/apps/server/src/kin/widgets/registry.test.ts new file mode 100644 index 0000000000000..584dd1d57f797 --- /dev/null +++ b/apps/server/src/kin/widgets/registry.test.ts @@ -0,0 +1,43 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import { validateState } from "./registry.ts"; + +const state = { + taskId: "task", + environmentId: "environment", + threadId: "thread", + remoteEnvironmentId: null, + title: "Work", + model: null, + status: "working", + pullRequests: [], + lastError: null, + updatedAt: "2026-11-07T00:00:00.000Z", +}; + +describe("Kin widget registry", () => { + it.effect("validates task state and refuses unknown or invalid state without a fallback", () => + Effect.gen(function* () { + assert.deepStrictEqual(yield* validateState("task", state), state); + for (const [type, value] of [ + ["unknown", state], + ["approval", state], + ["decision", state], + ["task", {}], + ["task", { ...state, status: "approved" }], + ["task", { ...state, threadId: 1 }], + ["task", { ...state, title: "" }], + ] as const) { + assert.include( + yield* validateState(type, value).pipe( + Effect.match({ + onFailure: (error) => error, + onSuccess: () => assert.fail("Expected invalid widget state"), + }), + ), + { reason: "invalid_state" }, + ); + } + }), + ); +}); diff --git a/apps/server/src/kin/widgets/registry.ts b/apps/server/src/kin/widgets/registry.ts new file mode 100644 index 0000000000000..59c189ee84d71 --- /dev/null +++ b/apps/server/src/kin/widgets/registry.ts @@ -0,0 +1,19 @@ +import { KinChatError, KinTaskCardState } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +const schemas = new Map>([["task", KinTaskCardState]]); + +export const validateState = Effect.fn("KinWidgetRegistry.validateState")(function* ( + type: string, + state: unknown, +) { + const schema = schemas.get(type); + if (schema === undefined) + return yield* new KinChatError({ reason: "invalid_state", message: "Unknown widget type." }); + return yield* Schema.decodeUnknownEffect(schema)(state).pipe( + Effect.mapError( + () => new KinChatError({ reason: "invalid_state", message: "Invalid widget state." }), + ), + ); +}); diff --git a/docs/kin/specs/chat.md b/docs/kin/specs/chat.md index b98dc0e07ccd3..56fe99904d1f2 100644 --- a/docs/kin/specs/chat.md +++ b/docs/kin/specs/chat.md @@ -46,7 +46,7 @@ Every row carries `orgId`. Phase 1 has one org, created on first start. Bootstra - **Session to person** (`KinIdentity.resolve(session)`): - Phase 1: after the RPC scope check, a `/ws` session holding every scope in `AuthStandardClientScopes` resolves to the default org owner. A narrower session resolves to an empty list, never to a person inferred from `subject`. The result is a list of `{ orgId, personId }` entries so phase-2 bindings do not change callers. Only the owner may pair devices before CHAT-11. - Phase 2: a row in `kin_session_bindings (session_id, org_id, person_id)` decides. A session without a binding is the owner only if it holds `AuthStandardClientScopes`. Members get sessions with the new `kin:chat` scope only (CHAT-11), so their device never gets the owner's terminal or files. -- **Agent thread to agent** (`KinIdentity.resolveAgent(mcpScope)`): the lead spec registers each lead session's thread with `registerAgentThread({ orgId, agentId, threadId })`. Kin MCP tools look up `McpInvocationScope.thread.threadId`. An absent caller thread, no registry row, an ended row, or `subagent: true` means `not_allowed`. Resolution reads the database, not the tool-visibility cache, and derives `{ orgId, agentId, ownerPersonId, threadId }` only from stored rows. Retired agents are refused with `not_allowed` by both resolution and registration. Workers never post; they report to their lead. The lead calls `endAgentThread({ orgId, threadId })` when the session ends; an ended thread cannot be registered again. +- **Agent thread to agent** (`KinIdentity.resolveAgent(mcpScope)`): the lead spec registers each lead session's thread with `registerAgentThread({ orgId, agentId, threadId })`. Kin MCP tools look up `McpInvocationScope.thread.threadId`. An absent caller thread, no registry row, an ended row, or `subagent: true` means `not_allowed`. Resolution reads the database, not the tool-visibility cache, and derives `{ orgId, agentId, ownerPersonId, threadId }` only from stored rows. Retired agents are refused with `not_allowed` by both resolution and registration. Workers never post; they report to their lead. The lead calls `endAgentThread({ orgId, threadId })` when the session ends; an ended thread cannot be registered again. Retiring an agent ends its threads through `KinIdentity`; active-thread discovery also excludes retired agents. ### Chats, members, roles @@ -108,6 +108,7 @@ Rules: - **team_group / project_group:** any number of people and agents. Exactly one `owner` person per chat (the org owner in phases 1 to 4). - **router:** one per owner person; its agent has role `router`. Created by the router task in phase 3. The kind exists now so no row changes later. - **guest:** a person with role `guest` reads the chat and posts **suggestions** only. A suggestion reaches nobody but the guest and the owner until the owner sends or dismisses it, the same model as `ThreadGuestMessage.status` (`pending | sent | dismissed`) in `guestShare.ts`. Kin keeps `GUEST_MESSAGE_MAX_LENGTH` (4,000) and `GUEST_PENDING_MESSAGE_LIMIT` (3 waiting per guest per chat) and copies the name check regex. +- System messages store `authorRole: "member"`; approval ceilings use `author._tag`, never that role alone. - A role change never rewrites old messages. Each message stores the author's role at the time it was posted (`authorRole`), because provenance ceilings (approvals spec) use it. ### Messages and authors @@ -156,7 +157,8 @@ export const KinMessage = Schema.Struct({ ``` - **The send input has no author field.** `kin.messages.send` takes `{ chatId, clientMessageId, body, mentions?, replyTo? }`. Effect Schema drops unknown keys on decode, so an `author` sent by a client never reaches the service. -- **Idempotency:** unique `(chat_id, author_member_id, client_message_id)`. A retried send returns the first message. +- **Mentions:** each mentioned member must still be active in the same org and chat, checked inside the send transaction; mentions of members who have left are refused. +- **Idempotency:** unique `(chat_id, author_member_id, client_message_id)`. An identical retry returns the first insert; a changed retry (body, mentions, replyTo, or intent) fails `not_allowed`. - **Agent posts** come only through the Kin MCP tool `kin_chat_post` (CHAT-7). The author is built from `KinIdentity.resolveAgent`. Agent text is never trusted as a claim about authority (section 9.3); that rule lives in the approvals spec, but the chat never offers a way to make agent text look human. - **Citable link:** `kinMessageLink({ orgId, chatId, messageId })` returns `kin-chat:////`. kin-memory items use it as `source`. - **Deletion** sets `status: "deleted"` and clears `body`. Purge and retention are phase 5 (org policy). @@ -196,7 +198,7 @@ export const KinWidget = Schema.Struct({ }); ``` -- **State schemas** are registered per type in `apps/server/src/kin/widgets/registry.ts` (**new**). Owners: `task` (this spec), `approval` (approvals spec, drawn from `KinPendingAction`), `deferral` (lead spec), `decision`, `poll`, `checklist`, `form`, `date` (this spec, phase 2, CHAT-13). An unknown type, or state that fails its schema, is refused at upsert. +- **State schemas** are registered per type in `apps/server/src/kin/widgets/registry.ts` (**new**). Owners: `task` (this spec, registered in CHAT-5; updater in CHAT-8), `approval` (approvals spec, drawn from `KinPendingAction`), `deferral` (lead spec), `decision`, `poll`, `checklist`, `form`, `date` (this spec, phase 2, CHAT-13). An unknown type, or state that fails its schema, is refused at upsert. CHAT-5 registers only `task`; other owners add their schemas with their features. - **Acting:** `kin.widgets.act({ widgetId, revision, actionId, value?, clientActionId })` posts a `widget_action` message authored by the session's person, with `{ widgetId, revision, actionId, value }` as its structured body. The lead acts on it under its own permissions. A stale `revision` fails with `widget_changed`. - **Approval cards never go through `act`.** `act` refuses `type: "approval"` with `use_approvals`. Approving is the approvals spec's signed-grant RPC (section 9.2). Approval widgets are created only by the approvals spec's server code; the MCP upsert tool refuses that type too, so an agent can't draw one. - **Generated widgets** carry `source`, the lead thread's turn item that produced the MCP App resource. The client renders it with the existing `ThreadMcpApp`, which already calls `mcpApps.*` RPCs scoped to `{ threadId, itemId }`. This works for the owner only, since those RPCs need `orchestration:*` scopes. Members seeing generated widgets is an open question. @@ -244,7 +246,11 @@ Flow: - a widget upsert with `awaiting` (one row per person; removed people resolve as `superseded`), - an agent message with `intent: "question"` that mentions a person, or any agent question in a direct chat, - a guest suggestion (for the owner), - - the approvals spec calling `addWaiting` for its approval cards. + - the approvals spec calling the server-only repository `addWaiting` inside its transaction for its approval cards, then publishing `waiting.updated` after commit. +- Public `KinChatService.addWaiting` refuses `reason: "approval"` and any row anchored on an approval widget (including through its message) with `not_allowed`; only the approvals spec creates these rows through the server-only repository entry point, never a transport. +- Agents may resolve only `question` rows on their own messages, never approval rows or approval-widget anchors, even with an owner role. Persons may resolve their own rows; chat owners may resolve any row. Nobody resolves approval rows or approval-widget anchors through the public service; only the approvals spec's signed-grant flow does. Guests cannot resolve rows. Refusals use `not_allowed`. +- When a person leaves a chat, their open waiting rows in that chat resolve as `cancelled` in the same transaction; rejoining applies the requested role and does not reopen cancelled rows. +- New waiting rows must be unresolved; a caller-supplied resolution is refused. - A row resolves when the widget closes, the person acts on it, the person replies in the chat after the question (for `question`), or the source calls `resolveWaiting`. - The list streams with the chat list. Without an `orgId` the stream merges every org the session is bound to, each item labelled with `orgId` (10a, "one switcher"). Only this list is highlighted in the UI (interface rule 1); push and lock-screen buttons are the mobile and approvals specs' work. @@ -266,7 +272,7 @@ K001 (phase 1, includes everything phase 2 needs for existing rows): | `kin_agents` | `agent_id` PK, `org_id`, `display_name`, `role`, `owner_person_id`, `created_at`, `retired_at` | | `kin_agent_threads` | `thread_id` PK, `org_id`, `agent_id`, `started_at`, `ended_at` | | `kin_session_bindings` | (`session_id`, `org_id`) PK, `person_id`, `bound_at`, `revoked_at` (empty in phase 1) | -| `kin_chats` | `chat_id` PK, `org_id`, `kind`, `title`, `team_id`, `direct_key` (unique with `org_id`, null for groups), `last_seq`, `last_message_at`, `created_at`, `archived_at`; index on (`org_id`) | +| `kin_chats` | `chat_id` PK, `org_id`, `kind`, `title`, `team_id`, `direct_key` (unique with `org_id`, null for groups), `last_seq`, `last_message_at`, `created_at`, `archived_at`; index on (`org_id`, `chat_id`) (added by K002) | | `kin_chat_members` | `member_id` PK, `org_id`, `chat_id`, `principal_kind`, `person_id`, `agent_id`, `role`, `joined_at`, `left_at`, `muted_until`; unique (`chat_id`, `person_id`), (`chat_id`, `agent_id`); indexes on (`org_id`, `person_id`), (`org_id`, `agent_id`) | | `kin_messages` | `message_id` PK, `org_id`, `chat_id`, `seq`, `author_kind`, `author_person_id`, `author_agent_id`, `author_owner_person_id`, `author_thread_id`, `author_member_id`, `author_role`, `kind`, `body`, `intent`, `mentions_json`, `reply_to`, `widget_id`, `floor_run_id`, `status`, `sent_by`, `client_message_id`, `created_at`, `edited_at`; unique (`chat_id`, `seq`), (`chat_id`, `author_member_id`, `client_message_id`) | | `kin_widgets` | `widget_id` PK, `org_id`, `chat_id`, `message_id`, `widget_class`, `type`, `revision`, `state_json`, `source_thread_id`, `source_item_id`, `feed_kind`, `feed_key`, `awaiting_json`, `pinned_at`, `closed_at`, `updated_at`; indexes on (`type`, `closed_at`), (`org_id`, `chat_id`, `message_id`) | @@ -277,7 +283,7 @@ K001 uses `TEXT` for ids, ISO timestamps and JSON, and `INTEGER` for sequences a The next free migration number (phase 2): `kin_floor_runs`, `kin_floor_bids`, `kin_judge_log` (below). New tables only. -**Seq allocation:** in one `sql.withTransaction`: `UPDATE kin_chats SET last_seq = last_seq + 1, last_message_at = ? WHERE chat_id = ? AND org_id = ? RETURNING last_seq`, then insert the message with that seq. Look up an existing `(chat_id, author_member_id, client_message_id)` inside the transaction before allocating a seq. Store sends as `send:` and widget actions as `act:` so the namespaces cannot collide. History returns the newest page before `beforeSeq` in ascending seq order, with `hasMore` from one extra row. Publish to the in-process hub only after commit. +**Seq allocation:** in one `sql.withTransaction`: `UPDATE kin_chats SET last_seq = last_seq + 1, last_message_at = ? WHERE chat_id = ? AND org_id = ? RETURNING last_seq`, then insert the message with that seq. Look up an existing `(chat_id, author_member_id, client_message_id)` inside the transaction before allocating a seq. Store sends as `send:` and widget actions as `act:` so the namespaces cannot collide. History returns the newest page before `beforeSeq` in ascending seq order, with `hasMore` from one extra row. Message and widget ids are server-generated; widget revisions start at 1 and are server-owned. Publish to the in-process hub only after commit. ### RPC surface @@ -334,7 +340,7 @@ export const KinChatStreamEvent = Schema.Union([ ### Authorisation, in two layers 1. **Scope (coarse):** `KIN_CHAT_RPC_SCOPES` in `kinChat.ts` maps each method to a scope; `RpcAuthorization.ts` spreads it into `RPC_REQUIRED_SCOPES`. Phase 1 uses existing scopes (table above). Phase 2 adds `kin:chat` and moves every `kin.*` method to it (CHAT-11). -2. **Membership (fine):** inside `KinChatService`, every call resolves the person, loads the chat by id, and checks an active member row in the same org. A client-sent `orgId` must match the chat's. Role checks: only `owner` adds or removes members, sets roles, resolves suggestions, pins. `guest` can only `send` (stored as `suggested`), `markRead` and subscribe. Muted agents can't post. +2. **Membership (fine):** inside `KinChatService`, every call resolves the person, loads the chat by id, and checks an active member row in the same org. A client-sent `orgId` must match the chat's. Role checks: only `owner` adds or removes members, sets roles, resolves suggestions, pins. `guest` can only `send` (stored as `suggested`), `markRead` and subscribe. Until CHAT-12 supplies the suggestion flow, CHAT-5 refuses guest writes rather than posting them as normal messages. Muted agents can't post. ### Agent tools (MCP) @@ -433,7 +439,7 @@ export const JUDGE_THRESHOLDS = { act: 0.8, ask: 0.5 } as const; // below ask: a ### Failure cases -- **Sending while offline:** the client keeps `clientMessageId` and retries; the server returns the first insert. +- **Sending while offline:** the client keeps `clientMessageId` and retries; an identical retry returns the first insert; a changed retry fails `not_allowed`. - **Two sends in one chat at once:** the seq update serialises them; SQLite has one writer, and `busy_timeout = 5000` in `Sqlite.ts` covers contention with the CLI process. - **Hub publish lost** (crash after commit): resubscribing reads the backlog from SQLite, so nothing is lost. - **Agent thread ends mid-post:** the registry row has `ended_at`; `resolveAgent` refuses it with `not_allowed`. The repository rechecks that row inside the post transaction, so an identity resolved before the end cannot post afterwards. @@ -468,7 +474,7 @@ Upstream files touched, hooks only: ## Interfaces to other specs - **Lead spec:** calls `KinIdentity.registerAgentThread` / `endAgentThread` around each lead session. Subscribes to `KinChatHub` for `message.posted` and `widget_action` to build `KinEvent`s. Uses the Kin MCP tools to post. Owns `KinAgent` config beyond identity, the `deferral` card state, levels per chat (its own table keyed by `chatId`), and the brief builder that quotes non-owner text. Receives `floor.offer` wake requests from the floor manager. -- **Approvals spec:** creates `approval` widgets server-side from `KinPendingAction` and calls `addWaiting` / `resolveWaiting`. Reads `KinMessage.author` and `authorRole` as provenance for ceilings. Its signed-grant RPC is the only way to approve; `kin.widgets.act` refuses approvals. Shows "Waiting on Nishchay" to members from `KinWidget.awaiting`. +- **Approvals spec:** creates `approval` widgets server-side from `KinPendingAction` and creates approval waiting rows through the server-only repository `addWaiting` in its transaction, never the public chat service or a transport. It resolves rows through its signed-grant flow; agents cannot create or resolve them. Reads `KinMessage.author` and `authorRole` as provenance for ceilings. Its signed-grant RPC is the only way to approve; `kin.widgets.act` refuses approvals. Shows "Waiting on Nishchay" to members from `KinWidget.awaiting`. - **Triggers spec:** deferral and routine posts arrive as lead notices; nothing here. Its upstream contract tests should cover what this spec depends on: `Migrator` `table` option, `WsRpcGroup` and `RPC_REQUIRED_SCOPES` shapes, `layerWsRpc` session argument, `McpInvocationScope.thread`, `toolkitRegistration`, `getThreadShell` and `streamDomainEvents`, `OrchestratorMcpDelegateTaskResult`. - **Mobile spec:** consumes `kin.*` RPCs and both streams through the normal WS client; draws native cards from `KinWidget.type` and `state`; renders generated widgets with `ThreadMcpApp`; opens task threads with `formatThreadLink`; folds runs by `floorRunId`; avatars from `KinAuthor._tag` (rule 7). @@ -512,11 +518,11 @@ Run with `cd apps/server && vp test run src/kin` and `cd packages/contracts && v **CHAT-5. Chat service and hub.** What: `KinChatService` (createDirect, send, history, markRead, widget upsert and act, addWaiting and resolveWaiting, membership and role checks) and `KinChatHub`. Files: `KinChatService.ts`, `KinChatHub.ts`, `widgets/registry.ts`, tests. Depends on: CHAT-4. Done when: author, isolation, widget, read state and waiting tests pass. Owner: backend. -**CHAT-6. WS RPCs and streams.** What: `makeKinChatHandlers(session)`, both stream handlers with resume, `KinChat.layer`; `packages/contracts/src/kinRpcs.ts` exporting `KinRpcs` and `KIN_RPC_SCOPES`, which combine every Kin spec's RPCs and scopes (`KinChatRpcs` first; other specs add theirs here, never to upstream files); hooks in `rpc.ts`, `ws.ts`, `RpcAuthorization.ts`, `server.ts`. Files: `kinRpcs.ts`, `apps/server/src/kin/chat/rpcHandlers.ts`, `layer.ts`. Depends on: CHAT-5. Done when: a `ws.test.ts`-style test over a real socket sends, subscribes, resumes with `afterSeq`, and gets `not_found` across orgs; `vp run typecheck` shows no `any` in the handler layer requirements (see Design corrections 6). Owner: backend. Provide one shared `KinIdentity` instance for WS handlers and the `/kin/mcp` toolkit and test that it is shared. A Kin identity failure must disable Kin without stopping T3 startup. +**CHAT-6. WS RPCs and streams.** Both streams must use `KinChatHub.subscribeForViewer(identity)`, which checks current membership at delivery for every event and hides suggestions from everyone except their author and the chat owner; the org-wide subscription is for trusted server consumers only. What: `makeKinChatHandlers(session)`, both stream handlers with resume, `KinChat.layer`; `packages/contracts/src/kinRpcs.ts` exporting `KinRpcs` and `KIN_RPC_SCOPES`, which combine every Kin spec's RPCs and scopes (`KinChatRpcs` first; other specs add theirs here, never to upstream files); hooks in `rpc.ts`, `ws.ts`, `RpcAuthorization.ts`, `server.ts`. Files: `kinRpcs.ts`, `apps/server/src/kin/chat/rpcHandlers.ts`, `layer.ts`. Depends on: CHAT-5. Done when: a `ws.test.ts`-style test over a real socket sends, subscribes, resumes with `afterSeq`, and gets `not_found` across orgs; `vp run typecheck` shows no `any` in the handler layer requirements (see Design corrections 6). Owner: backend. Provide one shared `KinIdentity` instance for WS handlers and the `/kin/mcp` toolkit and test that it is shared. A Kin identity failure must disable Kin without stopping T3 startup. **CHAT-7. Agent MCP tools.** What: `KinChatToolkit` with `kin_chat_post`, `kin_chat_read`, `kin_widget_upsert`; `EnabledWhen` from the registry; hook in `McpHttpServer.ts`. Files: `apps/server/src/kin/mcp/*`. Depends on: CHAT-5. Done when: agent-post tests pass and `AgentContextBudget.test.ts` passes unchanged. Owner: backend. Use the same shared `KinIdentity` instance as WS handlers and test that it is shared. -**CHAT-8. Task cards.** What: `task` state schema, `TaskCardUpdater` following `streamDomainEvents` and `getThreadShell`, startup recheck. Files: `apps/server/src/kin/chat/TaskCardUpdater.ts`, `widgets/taskCard.ts`, tests. Depends on: CHAT-5, CHAT-7. Done when: the task card test passes, and a manual run of `delegate_task` from a lead thread shows the card change state in `kin.chat.subscribe` output. Owner: backend. +**CHAT-8. Task cards.** What: `TaskCardUpdater` following `streamDomainEvents` and `getThreadShell`, startup recheck. Files: `apps/server/src/kin/chat/TaskCardUpdater.ts`, `widgets/taskCard.ts`, tests. Depends on: CHAT-5, CHAT-7. Done when: the task card test passes, and a manual run of `delegate_task` from a lead thread shows the card change state in `kin.chat.subscribe` output. Owner: backend. **CHAT-9. Floor manager.** What: pure `FloorManager.ts` (rules 1 to 5, replies vs notices), floor tables at the next free migration number, grant tokens in `kin_chat_post`, implicit grants in direct chats, notice rate limit. Files: `apps/server/src/kin/floor/FloorManager.ts`, `migrations/KNNN_Floor.ts` (next free number), tests. Depends on: CHAT-7. Done when: floor table tests pass and a direct-chat test shows a second unprompted reply refused with `floor_not_granted` while a notice passes. Owner: backend.