diff --git a/apps/server/src/kin/KinServer.ts b/apps/server/src/kin/KinServer.ts index 88500cae506fd..779e4d013e70a 100644 --- a/apps/server/src/kin/KinServer.ts +++ b/apps/server/src/kin/KinServer.ts @@ -12,6 +12,8 @@ import { GrantVerifier } from "./approvals/GrantVerifier.ts"; import { KinStop } from "./lead/KinStop.ts"; import type { KinShadowSummary } from "./lead/KinLevels.ts"; import type { KinLevelGate } from "./lead/LevelGate.ts"; +import type { KinPromotion } from "./levels/Promotion.ts"; +import type { KinPromotionCards } from "./lead/KinLevels.ts"; import type { KinGithubWebhookLock } from "./triggers/githubWebhooks.ts"; import type { KinPushDevices } from "./push/KinPushDevices.ts"; import type { KinPushPresence } from "./push/KinPushPresence.ts"; @@ -26,6 +28,8 @@ export type Services = | KinStop | KinLevelGate | KinShadowSummary + | KinPromotion + | KinPromotionCards | KinGithubWebhookLock | ApproverKeys | GrantVerifier diff --git a/apps/server/src/kin/approvals/PendingActions.test.ts b/apps/server/src/kin/approvals/PendingActions.test.ts index a3224dac62c33..c47c311ce7ac5 100644 --- a/apps/server/src/kin/approvals/PendingActions.test.ts +++ b/apps/server/src/kin/approvals/PendingActions.test.ts @@ -129,6 +129,29 @@ describe("KinPendingActions", () => { ); assert.isTrue(Exit.isFailure(posing)); } + // set_level comes only from the owner's promotion card, never from a lead or another kind. + const level = { _tag: "level", agentId: "lead", level: "L1" }; + for (const [kind, target, requestedBy] of [ + ["set_level", level, { agentId: "lead", threadId: "thread-lead" }], + ["set_level", level, { agentId: "kin-promotion", threadId: "thread-lead" }], + ["set_level", level, { agentId: "kin-approver-keys", threadId: "kin-approver-keys" }], + [ + "merge_pull_request", + request("x").target, + { agentId: "kin-promotion", threadId: "kin-promotion" }, + ], + ] as const) { + const posing = yield* Effect.exit( + actions.create({ + ...request("webhook-delivery-3"), + kind, + target, + resolved: { _tag: "none" }, + requestedBy, + } as unknown as KinPendingActionCreateInput), + ); + assert.isTrue(Exit.isFailure(posing), `${kind} from ${requestedBy.agentId}`); + } const twice = yield* Effect.all( [ diff --git a/apps/server/src/kin/approvals/PendingActions.ts b/apps/server/src/kin/approvals/PendingActions.ts index 1693ce52f8aae..563ac67e4d142 100644 --- a/apps/server/src/kin/approvals/PendingActions.ts +++ b/apps/server/src/kin/approvals/PendingActions.ts @@ -45,6 +45,12 @@ const GRANT_ACCEPTED_TTL_MS = 15 * 60 * 1000; /** `registerKey`'s requester: the phone asked, not an agent, so no agent may use this id. */ export const KIN_APPROVER_KEYS_REQUESTER = "kin-approver-keys"; +/** The owner's promotion card asked, never a lead: `set_level` has no other requester. */ +export const KIN_PROMOTION_REQUESTER = "kin-promotion"; +const RESERVED_REQUESTERS = new Map([ + [KIN_APPROVER_KEYS_REQUESTER, "register_approver_key"], + [KIN_PROMOTION_REQUESTER, "set_level"], +]); const CreateInput = Schema.Struct({ orgId: KinOrgId, kind: KinActionKind, @@ -57,12 +63,16 @@ const CreateInput = Schema.Struct({ source: KinEventId, }).check( Schema.makeFilter( - ({ kind, requestedBy: { agentId, threadId } }) => - (agentId !== KIN_APPROVER_KEYS_REQUESTER && threadId !== KIN_APPROVER_KEYS_REQUESTER) || - (kind === "register_approver_key" && - agentId === KIN_APPROVER_KEYS_REQUESTER && - threadId === KIN_APPROVER_KEYS_REQUESTER), - { expected: `a requester other than the reserved ${KIN_APPROVER_KEYS_REQUESTER}` }, + ({ kind, requestedBy: { agentId, threadId } }) => { + const byAgent = RESERVED_REQUESTERS.get(agentId); + const byThread = RESERVED_REQUESTERS.get(threadId); + if (kind === "set_level") + return agentId === KIN_PROMOTION_REQUESTER && threadId === KIN_PROMOTION_REQUESTER; + return ( + (byAgent === undefined && byThread === undefined) || (byAgent === kind && byThread === kind) + ); + }, + { expected: "a reserved requester only for its own kind, and set_level only from promotion" }, ), ); export type KinPendingActionCreateInput = typeof CreateInput.Type; diff --git a/apps/server/src/kin/approvals/handlers/setLevel.ts b/apps/server/src/kin/approvals/handlers/setLevel.ts new file mode 100644 index 0000000000000..dfef26d2ca2fe --- /dev/null +++ b/apps/server/src/kin/approvals/handlers/setLevel.ts @@ -0,0 +1,62 @@ +import { KinApprovalError, type KinGrant, type KinPendingAction } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as KinLevels from "../../lead/KinLevels.ts"; + +const refuse = (message: string) => + Effect.fail(new KinApprovalError({ reason: "invalid_state", message })); + +const REFUSALS: Record = { + not_a_lead: "The lead is retired or gone.", + not_running: "The lead isn't running.", + conflict: "The level changed meanwhile.", + limit: "The level can't change now.", + not_found: "The lead is no longer in that chat.", + invalid_level: "The level no longer matches what was approved.", + not_eligible: "The lead is no longer eligible for this level.", + not_granted: "No claimed owner grant backs this raise.", +}; +const refusal = (error: KinLevels.KinLevelRefused) => refuse(REFUSALS[error.reason]); + +/** + * Raises a lead's level, or a chat's cap, once the owner's grant for the `set_level` action is + * verified and claimed. Shaped as spec section 6's `KinActionHandler`; APPR-9 registers it. + */ +export const makeSetLevelHandler = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const reached = Effect.fn("setLevel.reached")(function* (action: KinPendingAction) { + if (action.kind !== "set_level" || action.target._tag !== "level") + return yield* refuse("Not a level change."); + const target = action.target; + const level = yield* KinLevels.effectiveLevel({ + orgId: action.orgId, + agentId: target.agentId, + chatId: target.chatId, + }).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + Effect.catchTags({ KinLevelRefused: refusal }), + ); + return KinLevels.atLeast(level, target.level); + }); + + const precheck = Effect.fn("setLevel.precheck")(function* (action: KinPendingAction) { + if (yield* reached(action)) return yield* refuse("The lead is already at this level."); + }); + + const run = Effect.fn("setLevel.run")(function* (action: KinPendingAction, _grant: KinGrant) { + const raised = yield* KinLevels.raiseByGrant({ orgId: action.orgId, actionId: action.id }).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + Effect.catchTags({ KinLevelRefused: refusal }), + ); + yield* KinLevels.refreshPromotion({ orgId: action.orgId, agentId: raised.agentId }); + return "succeeded" as const; + }); + + const reconcile = Effect.fn("setLevel.reconcile")(function* (action: KinPendingAction) { + return (yield* reached(action)) ? ("done" as const) : ("not_done" as const); + }); + + return { kind: "set_level" as const, precheck, run, reconcile }; +}); diff --git a/apps/server/src/kin/chat/KinChatService.ts b/apps/server/src/kin/chat/KinChatService.ts index 7186c342629ac..e6f17e13525f9 100644 --- a/apps/server/src/kin/chat/KinChatService.ts +++ b/apps/server/src/kin/chat/KinChatService.ts @@ -1153,6 +1153,8 @@ const make = Effect.gen(function* () { reason: "use_approvals", message: "Use the signed approvals service.", }); + // Verdicts and raises go to the owner-only kin.levels methods, never the lead's queue. + if (widget.type === "shadow_review" || widget.type === "promotion") return yield* notAllowed; if (widget.type === "owner_check") { if (member.role !== "owner") return yield* notAllowed; const card = yield* decodeOwnerCheckCard(widget.state).pipe( diff --git a/apps/server/src/kin/layer.ts b/apps/server/src/kin/layer.ts index 33064c0a8add2..7929e300c68fd 100644 --- a/apps/server/src/kin/layer.ts +++ b/apps/server/src/kin/layer.ts @@ -11,6 +11,7 @@ import * as Option from "effect/Option"; import * as KinChat from "./chat/layer.ts"; import * as KinApprovals from "./approvals/layer.ts"; import * as KinPush from "./push/layer.ts"; +import * as Promotion from "./levels/Promotion.ts"; import { KinChatHub } from "./chat/KinChatHub.ts"; import { KinServer, type Services } from "./KinServer.ts"; @@ -39,10 +40,10 @@ const enabled = Layer.effect( ).pipe( Layer.provide( Layer.mergeAll( - KinChat.layer, - KinPush.layer.pipe(Layer.provideMerge(KinApprovals.layer)), + // Promotion asks for set_level through the same pending actions the executor watches. + Layer.mergeAll(KinPush.layer, Promotion.layer).pipe(Layer.provideMerge(KinApprovals.layer)), GithubWebhooks.lockLayer, - ), + ).pipe(Layer.provideMerge(KinChat.layer)), ), ); const disabled = Layer.succeed(KinServer, { diff --git a/apps/server/src/kin/lead/KinLevels.test.ts b/apps/server/src/kin/lead/KinLevels.test.ts index d07cbb14efd6c..8735a2695d367 100644 --- a/apps/server/src/kin/lead/KinLevels.test.ts +++ b/apps/server/src/kin/lead/KinLevels.test.ts @@ -149,8 +149,9 @@ it.effect("a shadow entry needs the caller's running wake-up and is idempotent b }).pipe(Effect.provide(layer)), ); -// Raising a level is LEAD-12's signed kin.level.set action; until it lands nothing writes levels. -it.effect("no Kin server code writes a lead's or a chat's level", () => +// Levels change only through owner-authorised paths: `raiseByGrant` behind a claimed set_level +// grant, and `lower` for the owner's RPC and the server's automatic demotion. +it.effect("only KinLevels writes levels, and no agent path reaches its writers", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -162,11 +163,38 @@ it.effect("no Kin server code writes a lead's or a chat's level", () => !file.endsWith(".testkit.ts") && !file.startsWith("persistence/migrations/"), ); + const sources = new Map(); + for (const file of files) sources.set(file, yield* fs.readFileString(path.join(kin, file))); const writes = /\b(?:INSERT\s+(?:OR\s+\w+\s+)?INTO|REPLACE\s+INTO|DELETE\s+FROM)\s+kin_(?:leads|chat_levels)\b|\bUPDATE\s+kin_chat_levels\b|\bUPDATE\s+kin_leads\s+SET\b[^`]*\blevel\b/i; - const offenders: Array = []; - for (const file of files) - if (writes.test(yield* fs.readFileString(path.join(kin, file)))) offenders.push(file); - assert.deepStrictEqual(offenders, []); + const using = (pattern: RegExp) => + [...sources] + .filter(([, text]) => pattern.test(text)) + .map(([file]) => file) + .toSorted(); + assert.deepStrictEqual(using(writes), ["lead/KinLevels.ts"]); + assert.deepStrictEqual(using(/\braiseByGrant\b/), [ + "approvals/handlers/setLevel.ts", + "lead/KinLevels.ts", + ]); + assert.deepStrictEqual(using(/\bKinLevels\.lower\b/), [ + "lead/KinLevels.ts", + "levels/Promotion.ts", + ]); + // Tool handlers and the lead's MCP surface never import the level services. + const agentFacing = [...sources.keys()].filter( + (file) => + file.startsWith("mcp/") || + file.startsWith("lead/mcp/") || + file === "approvals/mcp.ts" || + file === "approvals/RequestAction.ts", + ); + assert.isNotEmpty(agentFacing); + for (const file of agentFacing) + assert.notMatch( + sources.get(file) ?? "", + /Promotion\.ts|handlers\/setLevel|\b(?:raiseByGrant|checkRaise|KinPromotion)\b|KinLevels\.lower\b/, + file, + ); }).pipe(Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/kin/lead/KinLevels.ts b/apps/server/src/kin/lead/KinLevels.ts index 311657cc28bb0..d92d1a0715076 100644 --- a/apps/server/src/kin/lead/KinLevels.ts +++ b/apps/server/src/kin/lead/KinLevels.ts @@ -2,7 +2,9 @@ import * as NodeCrypto from "node:crypto"; import { + KinActionTarget, KinLevel, + type KinActionId, type KinAgentId, type KinChatId, type KinOrgId, @@ -24,8 +26,23 @@ const ORDER: ReadonlyArray = ["L0", "L1", "L2", "L3"]; export const atLeast = (level: KinLevel, required: KinLevel) => ORDER.indexOf(level) >= ORDER.indexOf(required); +const nextLevel = (level: KinLevel): KinLevel | undefined => ORDER[ORDER.indexOf(level) + 1]; +export const previousLevel = (level: KinLevel): KinLevel | undefined => + ORDER[ORDER.indexOf(level) - 1]; + export class KinLevelRefused extends Schema.TaggedError()("KinLevelRefused", { - reason: Schema.Literals(["not_a_lead", "not_running", "conflict", "limit"]), + reason: Schema.Literals([ + "not_a_lead", + "not_running", + "conflict", + "limit", + "not_found", + // Lowering must go down, raising must go up one step (or a chat up to the lead's level). + "invalid_level", + "not_eligible", + // No claimed, owner-granted `set_level` action backs the raise. + "not_granted", + ]), }) {} /** Bounds what one wake-up can put in the owner's review, whatever keys the lead picks. */ @@ -172,3 +189,274 @@ export const refreshSummary = Effect.fn("KinLevels.refreshSummary")(function* (i const summary = yield* Effect.serviceOption(KinShadowSummary); if (summary._tag === "Some") yield* summary.value.refresh(input); }); + +const DAY_MS = 86_400_000; +/** Lead spec, "Level promotion": thresholds for moving from level N to N+1. */ +const promotionRule = { minDays: 7, minReviewed: 20, minFineShare: 0.8 } as const; + +const query = + (operation: string) => + (effect: Effect.Effect) => + effect.pipe(Effect.mapError(toPersistenceSqlError(operation))); +const decode = (operation: string) => (value: unknown) => + decodeLevel(value).pipe(Effect.mapError(toPersistenceDecodeError(operation))); +// Statements map their own errors; this catches a transaction's begin and commit. +const inTransaction = + (operation: string) => + (effect: Effect.Effect) => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + return yield* sql + .withTransaction(effect) + .pipe( + Effect.mapError((error) => + SqlError.isSqlError(error) ? toPersistenceSqlError(operation)(error) : error, + ), + ); + }); + +const activeLead = Effect.fn("KinLevels.activeLead")(function* (input: { + readonly orgId: KinOrgId; + readonly agentId: KinAgentId; +}) { + const sql = yield* SqlClient.SqlClient; + const [row] = yield* query("KinLevels.activeLead")(sql<{ + level: string; + since: number; + owner: string; + }>`SELECT l.level, l.level_since AS since, a.owner_person_id AS owner FROM kin_leads l + JOIN kin_agents a ON a.org_id = l.org_id AND a.agent_id = l.agent_id + WHERE l.org_id = ${input.orgId} AND l.agent_id = ${input.agentId} + AND a.role = 'lead' AND a.retired_at IS NULL + ORDER BY l.agent_id`); + if (row === undefined) return yield* new KinLevelRefused({ reason: "not_a_lead" }); + return { + level: yield* decode("KinLevels.activeLead")(row.level), + since: row.since, + owner: row.owner, + }; +}); + +/** The chat's stored cap, or undefined; the chat must be one the lead is an active member of. */ +const chatCap = Effect.fn("KinLevels.chatCap")(function* (input: { + readonly orgId: KinOrgId; + readonly agentId: KinAgentId; + readonly chatId: KinChatId; +}) { + const sql = yield* SqlClient.SqlClient; + const [chat] = yield* query("KinLevels.chatCap")(sql<{ level: string | null }>` + SELECT c.level FROM kin_chat_members m + LEFT JOIN kin_chat_levels c ON c.org_id = m.org_id AND c.agent_id = m.agent_id + AND c.chat_id = m.chat_id + WHERE m.org_id = ${input.orgId} AND m.chat_id = ${input.chatId} + AND m.agent_id = ${input.agentId} AND m.left_at IS NULL + ORDER BY m.chat_id`); + if (chat === undefined) return yield* new KinLevelRefused({ reason: "not_found" }); + return chat.level === null ? undefined : yield* decode("KinLevels.chatCap")(chat.level); +}); + +/** Review counts for the lead's trial at its current level, counted since it reached it. */ +export const promotionStats = Effect.fn("KinLevels.promotionStats")(function* (input: { + readonly orgId: KinOrgId; + readonly agentId: KinAgentId; +}) { + const sql = yield* SqlClient.SqlClient; + const lead = yield* activeLead(input); + const to = nextLevel(lead.level) ?? null; + const rows = + to === null + ? [] + : yield* query("KinLevels.promotionStats")(sql<{ verdict: string | null; n: number }>` + SELECT verdict, COUNT(*) AS n FROM kin_shadow_entries + WHERE org_id = ${input.orgId} AND agent_id = ${input.agentId} + AND unlocks_level = ${to} AND created_at >= ${lead.since} + GROUP BY verdict ORDER BY verdict`); + const count = (verdict: string | null) => rows.find((row) => row.verdict === verdict)?.n ?? 0; + const unreviewed = count(null); + const reviewed = rows.reduce((sum, row) => sum + row.n, 0) - unreviewed; + const fine = count("fine"); + const harmful = count("harmful"); + const daysAtLevel = Math.max( + 0, + Math.floor(((yield* Clock.currentTimeMillis) - lead.since) / DAY_MS), + ); + const rule = promotionRule; + return { + from: lead.level, + to, + daysAtLevel, + reviewed, + fine, + harmful, + unreviewed, + // Integer percentages, so 16 of 20 meets 80% exactly. Every entry in the trial is reviewed. + eligible: + to !== null && + daysAtLevel >= rule.minDays && + reviewed >= rule.minReviewed && + fine * 100 >= reviewed * Math.round(rule.minFineShare * 100) && + harmful === 0 && + unreviewed === 0, + rule, + levelSince: lead.since, + }; +}); + +/** + * Lowers the lead's level, or one chat's cap, at once and without a grant (lead spec, Levels). + * Callers are the owner's RPC and the server's automatic demotion only. + */ +export const lower = Effect.fn("KinLevels.lower")(function* (input: { + readonly orgId: KinOrgId; + readonly agentId: KinAgentId; + readonly chatId?: KinChatId | undefined; + readonly level: KinLevel; +}) { + const sql = yield* SqlClient.SqlClient; + const run = query("KinLevels.lower"); + return yield* inTransaction("KinLevels.lower")( + Effect.gen(function* () { + const lead = yield* activeLead(input); + const now = yield* Clock.currentTimeMillis; + if (input.chatId === undefined) { + if (atLeast(input.level, lead.level)) + return yield* new KinLevelRefused({ reason: "invalid_level" }); + const updated = yield* run(sql`UPDATE kin_leads SET level = ${input.level}, + level_since = ${now} + WHERE org_id = ${input.orgId} AND agent_id = ${input.agentId} AND level = ${lead.level} + RETURNING agent_id`); + if (updated.length === 0) return yield* new KinLevelRefused({ reason: "conflict" }); + return { from: lead.level, to: input.level }; + } + const chatId = input.chatId; + const cap = yield* chatCap({ ...input, chatId }); + const current = cap === undefined || atLeast(cap, lead.level) ? lead.level : cap; + if (atLeast(input.level, current)) + return yield* new KinLevelRefused({ reason: "invalid_level" }); + const inserted = yield* run(sql`INSERT INTO kin_chat_levels + (org_id, agent_id, chat_id, level, level_since) + VALUES (${input.orgId}, ${input.agentId}, ${chatId}, ${input.level}, ${now}) + ON CONFLICT DO NOTHING RETURNING chat_id`); + if (inserted.length === 0) { + const updated = yield* run(sql`UPDATE kin_chat_levels SET level = ${input.level}, + level_since = ${now} + WHERE org_id = ${input.orgId} AND agent_id = ${input.agentId} AND chat_id = ${chatId} + AND level = ${cap ?? null} + RETURNING chat_id`); + if (updated.length === 0) return yield* new KinLevelRefused({ reason: "conflict" }); + } + return { from: current, to: input.level }; + }), + ); +}); + +/** + * Whether the owner may ask to raise: the lead one step up once eligible, or a chat's cap back up + * to at most the lead's level. Raising always needs the owner's grant on top. + */ +export const checkRaise = Effect.fn("KinLevels.checkRaise")(function* (input: { + readonly orgId: KinOrgId; + readonly agentId: KinAgentId; + readonly chatId?: KinChatId | undefined; + readonly level: KinLevel; +}) { + const lead = yield* activeLead(input); + if (input.chatId === undefined) { + if (nextLevel(lead.level) !== input.level) + return yield* new KinLevelRefused({ reason: "invalid_level" }); + if (!(yield* promotionStats(input)).eligible) + return yield* new KinLevelRefused({ reason: "not_eligible" }); + return { from: lead.level }; + } + const cap = yield* chatCap({ ...input, chatId: input.chatId }); + const current = cap === undefined || atLeast(cap, lead.level) ? lead.level : cap; + if (atLeast(current, input.level) || !atLeast(lead.level, input.level)) + return yield* new KinLevelRefused({ reason: "invalid_level" }); + return { from: current }; +}); + +const decodeTarget = Schema.decodeUnknownEffect(Schema.fromJsonString(KinActionTarget)); + +/** + * Applies an owner-granted `set_level` raise. Only the executor's handler calls it, for an action + * it claimed: every write below also requires that claim, so no other path can raise a level. + */ +export const raiseByGrant = Effect.fn("KinLevels.raiseByGrant")(function* (input: { + readonly orgId: KinOrgId; + readonly actionId: KinActionId; +}) { + const sql = yield* SqlClient.SqlClient; + const run = query("KinLevels.raiseByGrant"); + return yield* inTransaction("KinLevels.raiseByGrant")( + Effect.gen(function* () { + // Only what was requested; whether it may apply is decided by the guarded write below. + const [action] = yield* run(sql<{ targetJson: string }>` + SELECT target_json AS "targetJson" FROM kin_pending_actions + WHERE org_id = ${input.orgId} AND action_id = ${input.actionId} AND kind = 'set_level' + ORDER BY action_id`); + if (action === undefined) return yield* new KinLevelRefused({ reason: "not_granted" }); + const target = yield* decodeTarget(action.targetJson).pipe( + Effect.mapError(toPersistenceDecodeError("KinLevels.raiseByGrant")), + ); + if (target._tag !== "level") return yield* new KinLevelRefused({ reason: "not_granted" }); + const ref = { orgId: input.orgId, agentId: target.agentId }; + const lead = yield* activeLead(ref); + // This target, claimed (executing, one open execution) under a consumed grant that the + // lead's own owner signed; another person's grant never applies. + const claimed = sql`EXISTS ( + SELECT 1 FROM kin_pending_actions p + JOIN kin_executions x ON x.org_id = p.org_id AND x.action_id = p.action_id + AND x.finished_at IS NULL + JOIN kin_grants g ON g.org_id = x.org_id AND g.grant_id = x.grant_id + AND g.action_id = p.action_id AND g.revision = p.revision AND g.consumed_at IS NOT NULL + WHERE p.org_id = ${input.orgId} AND p.action_id = ${input.actionId} + AND p.kind = 'set_level' AND p.state = 'executing' + AND p.target_json = ${action.targetJson} AND g.approver_human_id = ${lead.owner})`; + const now = yield* Clock.currentTimeMillis; + const { from } = yield* checkRaise({ ...ref, chatId: target.chatId, level: target.level }); + if (target.chatId === undefined) { + const updated = yield* run(sql`UPDATE kin_leads SET level = ${target.level}, + level_since = ${now} + WHERE org_id = ${input.orgId} AND agent_id = ${target.agentId} + AND level = ${from} AND ${claimed} + RETURNING agent_id`); + if (updated.length === 0) return yield* new KinLevelRefused({ reason: "not_granted" }); + return { agentId: target.agentId, from, to: target.level }; + } + // Back at the lead's level, the chat follows the lead again. + const written = + target.level === lead.level + ? yield* run(sql`DELETE FROM kin_chat_levels + WHERE org_id = ${input.orgId} AND agent_id = ${target.agentId} + AND chat_id = ${target.chatId} AND ${claimed} + RETURNING chat_id`) + : yield* run(sql`UPDATE kin_chat_levels SET level = ${target.level}, + level_since = ${now} + WHERE org_id = ${input.orgId} AND agent_id = ${target.agentId} + AND chat_id = ${target.chatId} AND level = ${from} AND ${claimed} + RETURNING chat_id`); + if (written.length === 0) return yield* new KinLevelRefused({ reason: "not_granted" }); + return { agentId: target.agentId, from, to: target.level }; + }), + ); +}); + +/** Redraws the owner's promotion card; supplied by the Kin services like `KinShadowSummary`. */ +export class KinPromotionCards extends Context.Service< + KinPromotionCards, + { + readonly refresh: (input: { + readonly orgId: KinOrgId; + readonly agentId: KinAgentId; + }) => Effect.Effect; + } +>()("t3/kin/lead/KinLevels/KinPromotionCards") {} + +/** Without Kin services the card is redrawn on the next review, evening or level change. */ +export const refreshPromotion = Effect.fn("KinLevels.refreshPromotion")(function* (input: { + readonly orgId: KinOrgId; + readonly agentId: KinAgentId; +}) { + const cards = yield* Effect.serviceOption(KinPromotionCards); + if (cards._tag === "Some") yield* cards.value.refresh(input); +}); diff --git a/apps/server/src/kin/lead/LevelGate.ts b/apps/server/src/kin/lead/LevelGate.ts index 2829fc2e5000b..8023a9791369a 100644 --- a/apps/server/src/kin/lead/LevelGate.ts +++ b/apps/server/src/kin/lead/LevelGate.ts @@ -1,4 +1,5 @@ import { + KIN_HIDDEN_CHARACTER, KinChatError, KinChatId, KinMessageId, @@ -63,28 +64,113 @@ const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unkno const field = (value: unknown, key: string): unknown => typeof value === "object" && value !== null ? (value as Record)[key] : undefined; const text = (value: unknown) => (typeof value === "string" ? value : ""); -const clip = (value: string) => - value.length <= PREVIEW_MAX ? value : `${value.slice(0, PREVIEW_MAX - 1)}…`; -/** One plain-text line per entry; the input is the lead's own, so it is shown, never trusted. */ -const preview = (tool: string, input: unknown) => { - switch (tool) { - case "kin_chat_post": - return clip(text(field(input, "body"))); - case "kin_delegate": - return clip(`${text(field(input, "kind"))}: ${text(field(input, "title"))}`); - case "kin_follow_up": - return clip(text(field(input, "brief"))); - case "request_action": { - const target = field(input, "target"); - const repo = text(field(target, "repo")); - const number = field(target, "number"); - const named = repo === "" ? "" : ` ${repo}${typeof number === "number" ? `#${number}` : ""}`; - return clip(`${text(field(input, "kind"))}${named}: ${text(field(input, "reason"))}`); - } +const lines = (...parts: ReadonlyArray) => parts.filter((part) => part !== "").join("\n"); +const labelled = (label: string, value: string) => (value === "" ? "" : `${label}: ${value}`); +const targetText = (target: unknown) => { + const repo = text(field(target, "repo")); + switch (field(target, "_tag")) { + case "pull_request": + return `${repo}#${String(field(target, "number"))}, merge method ${text(field(target, "mergeMethod"))}${field(target, "deleteBranchAfter") === true ? ", then delete the branch" : ""}`; + case "branch": + return `${repo} branch ${text(field(target, "ref"))}`; default: - return clip(tool); + return target === undefined ? "" : stableStringify(target); } }; +const modelText = (model: unknown) => + typeof model === "string" || model === undefined + ? text(model) + : `${text(field(model, "model"))} (${text(field(model, "instanceId"))})`; +const isStrings = (value: unknown): value is ReadonlyArray => + Array.isArray(value) && value.every((item) => typeof item === "string"); +/** The whole action as text; `complete` is false when a field it holds can't be shown. */ +const fullText = (tool: string, input: unknown) => { + let complete = true; + const optional = (key: string) => { + const value = field(input, key); + if (value === undefined || value === null || typeof value === "string") return text(value); + complete = false; + return ""; + }; + const list = (key: string) => { + const value = field(input, key); + if (value === undefined || value === null) return ""; + if (isStrings(value)) return value.join(", "); + complete = false; + return ""; + }; + const quoted = () => { + const value = field(input, "quoted"); + if (value === undefined) return []; + if (!Array.isArray(value)) { + complete = false; + return []; + } + return value.map((item: unknown) => { + const parts = ["role", "name", "text"].map((key) => field(item, key)); + if (!isStrings(parts)) { + complete = false; + return ""; + } + const [role, name, said] = parts; + return `Quoted (${name === "" ? role : `${role}, ${name}`}): ${said}`; + }); + }; + const shown = (() => { + switch (tool) { + case "kin_chat_post": + return lines( + text(field(input, "body")), + labelled("Intent", optional("intent")), + labelled("Mentions", list("mentions")), + labelled("Reply to", optional("replyTo")), + ); + case "kin_delegate": + return lines( + `${text(field(input, "kind"))}: ${text(field(input, "title"))}`, + labelled("Project", text(field(input, "projectId"))), + labelled("Base", optional("baseRef")), + labelled("Model", modelText(field(input, "model"))), + labelled("Reviews", optional("reviewOf")), + labelled("Goal", text(field(input, "goal"))), + labelled("Brief", text(field(input, "brief"))), + labelled("Memory", list("memoryItemIds")), + ...quoted(), + ); + case "kin_follow_up": + return lines( + labelled("Worker", text(field(input, "workerId"))), + labelled("Brief", text(field(input, "brief"))), + ...quoted(), + ); + case "request_action": + return lines( + `${text(field(input, "kind"))}: ${targetText(field(input, "target"))}`, + labelled("Reason", text(field(input, "reason"))), + ); + default: + return tool; + } + })(); + return { text: shown, complete }; +}; +const HIDDEN = new RegExp(KIN_HIDDEN_CHARACTER.source, "gu"); +/** Lead-written text with direction overrides and invisible characters spelled out. */ +export const plainText = (value: string) => + value.replace(HIDDEN, (char) => + char === "\n" || char === "\t" + ? char + : `[U+${(char.codePointAt(0) ?? 0).toString(16).toUpperCase().padStart(4, "0")}]`, + ); +/** Plain text of what the entry would have done; the input is the lead's own, so never trusted. */ +export const describe = (tool: string, input: unknown, max: number) => { + const full = fullText(tool, input); + const shown = plainText(full.text); + return shown.length <= max + ? { text: shown, truncated: !full.complete } + : { text: `${shown.slice(0, max - 1)}…`, truncated: true }; +}; +const preview = (tool: string, input: unknown) => describe(tool, input, PREVIEW_MAX).text; const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; @@ -155,7 +241,7 @@ const make = Effect.gen(function* () { tool: row.tool, level: row.level, unlocksLevel: row.unlocksLevel, - wouldTarget: row.wouldTarget, + wouldTarget: plainText(row.wouldTarget), preview: preview(row.tool, parsed), ...(typeof ceiling === "boolean" ? { ceilingBelowOwner: ceiling } : {}), createdAt: DateTime.formatIso(DateTime.makeUnsafe(row.createdAt)), diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index b81282c9df2bd..99c860ee274cb 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -131,6 +131,7 @@ describe("WakeupRunner", () => { dreamBase: () => Effect.die("unused"), commitDream: () => Effect.die("unused"), deleteDreamBranch: () => Effect.die("unused"), + settleShadow: () => Effect.die("unused"), stage: (_org, wakeup) => Effect.sync(() => { assert.isTrue(owner === undefined || owner === wakeup); @@ -221,6 +222,7 @@ describe("WakeupRunner", () => { dreamBase: () => Effect.die("unused"), commitDream: () => Effect.die("unused"), deleteDreamBranch: () => Effect.die("unused"), + settleShadow: () => Effect.die("unused"), discard: () => Effect.void, appendJournal: (_org, _wakeup, lines) => Effect.sync(() => diff --git a/apps/server/src/kin/lead/WakeupRunner.ts b/apps/server/src/kin/lead/WakeupRunner.ts index a22d9f5577c57..d3315cbbec6b2 100644 --- a/apps/server/src/kin/lead/WakeupRunner.ts +++ b/apps/server/src/kin/lead/WakeupRunner.ts @@ -40,6 +40,7 @@ import { KinLeadPrompt } from "./LeadPrompt.ts"; import * as RoutineContent from "./RoutineContent.ts"; import { PAUSE_POLL_INTERVAL_MS } from "./KinStop.ts"; import { isOrgPaused } from "./orgState.ts"; +import { KinPromotion } from "../levels/Promotion.ts"; const ownerCheckDispatcherReady = false; @@ -102,6 +103,7 @@ const ulid = Effect.gen(function* () { const make = Effect.gen(function* () { const ownerCheck = yield* Effect.serviceOption(OwnerCheck.OwnerCheck); + const promotion = yield* Effect.serviceOption(KinPromotion); const routineContent = yield* Effect.serviceOption(RoutineContent.KinRoutineContent); const sql = yield* SqlClient.SqlClient; const queue = yield* KinEventQueue.KinEventQueue; @@ -416,6 +418,9 @@ const make = Effect.gen(function* () { : Effect.void, ), ); + const eveningRun = events.some( + (event) => event._tag === "routine" && event.routine === "evening_summary", + ); if (Option.isSome(ownerCheck)) { for (const event of events) { if (event._tag === "routine" && event.routine === "owner_check") @@ -454,6 +459,11 @@ const make = Effect.gen(function* () { ), ), ); + } + // The review and promotion cards are server-drawn after the summary, never the lead's. + if (eveningRun && Option.isSome(promotion)) + yield* promotion.value.evening({ orgId, agentId }); + if (Option.isSome(routineContent)) { events = events.filter((event) => !RoutineContent.isRoutineContent(event)); if (events.length === 0) { yield* queue.finish({ orgId, wakeupId, status: "completed" }); diff --git a/apps/server/src/kin/lead/layer.ts b/apps/server/src/kin/lead/layer.ts index 308559a368022..d304179a0028e 100644 --- a/apps/server/src/kin/lead/layer.ts +++ b/apps/server/src/kin/lead/layer.ts @@ -38,6 +38,7 @@ import { KinLeadPrompt } from "./LeadPrompt.ts"; import * as WakeupRunner from "./WakeupRunner.ts"; import * as RoutineContent from "./RoutineContent.ts"; import * as KinStop from "./KinStop.ts"; +import { KinPromotion } from "../levels/Promotion.ts"; import * as DreamRunner from "../dreaming/DreamRunner.ts"; import * as DreamSession from "../dreaming/DreamSession.ts"; import * as Workers from "./Workers.ts"; @@ -86,6 +87,11 @@ const runner = Layer.effectDiscard( Effect.gen(function* () { const runner = yield* WakeupRunner.WakeupRunner; const stop = yield* KinStop.KinStop; + // The owner's keep-or-discard of shadow memory runs on this runtime's writer. + const writer = yield* Effect.serviceOption(Writer.MemoryWriter); + const promotion = yield* Effect.serviceOption(KinPromotion); + if (Option.isSome(writer) && Option.isSome(promotion)) + yield* promotion.value.attachShadowMemory(writer.value.settleShadow); yield* Effect.gen(function* () { const context = yield* Layer.build(routineRuntime); yield* Layer.build(dreamRuntime.pipe(Layer.provide(Layer.succeedContext(context)))).pipe( diff --git a/apps/server/src/kin/levels/Promotion.test.ts b/apps/server/src/kin/levels/Promotion.test.ts new file mode 100644 index 0000000000000..9df43f72d84ca --- /dev/null +++ b/apps/server/src/kin/levels/Promotion.test.ts @@ -0,0 +1,858 @@ +import { assert, it } from "@effect/vitest"; +import { + AuthOrchestrationReadScope, + AuthSessionId, + AuthStandardClientScopes, + KinAgentId, + KinChatId, + KinKeyThumbprint, + type KinActionId, + KinLevelRpcs, + KinOrgId, + KinPersonId, + KinPromotionCard, + KinShadowReviewCard, + KinWidgetId, + RpcScopeAuthorization, + WsRpcGroup, + WS_METHODS, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as ConfigProvider from "effect/ConfigProvider"; +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 RpcGroup from "effect/rpc/RpcGroup"; +import * as RpcTest from "effect/rpc/RpcTest"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as TestClock from "effect/testing/TestClock"; + +import * as RpcAuthorization from "../../auth/RpcAuthorization.ts"; +import * as Sqlite from "../../persistence/Sqlite.ts"; +import * as Audit from "../approvals/Audit.ts"; +import { makeSetLevelHandler } from "../approvals/handlers/setLevel.ts"; +import * as PendingActions from "../approvals/PendingActions.ts"; +import * as Chat from "../chat/layer.ts"; +import { KinChatService } from "../chat/KinChatService.ts"; +import * as Repository from "../chat/KinChatRepository.ts"; +import { KinIdentity } from "../chat/KinIdentity.ts"; +import * as Kin from "../layer.ts"; +import { makeKinHandlers } from "../rpcHandlers.ts"; +import * as KinLevels from "../lead/KinLevels.ts"; +import { dormantLeadDependencies } from "../lead/layer.testkit.ts"; +import { KinPromotion, type KinShadowSettle } from "./Promotion.ts"; + +const DAY = 86_400_000; +const session = { + sessionId: AuthSessionId.make("owner-session"), + subject: "browser", + method: "browser-session-cookie" as const, + scopes: AuthStandardClientScopes, +}; +const agentId = KinAgentId.make("lead"); +const group = KinChatId.make("group"); +const memberId = KinPersonId.make("priya"); +const kid = KinKeyThumbprint.make("Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E"); +const memberKid = KinKeyThumbprint.make("Z1ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E"); +const root = Kin.layer.pipe( + Layer.provide(dormantLeadDependencies), + Layer.provideMerge(Chat.layer), + Layer.provide(ConfigProvider.layer(ConfigProvider.fromUnknown({ KIN_ENABLED: true }))), + Layer.provideMerge(PendingActions.layer.pipe(Layer.provideMerge(Audit.layer))), + Layer.provideMerge(Sqlite.layerMemory), +); +const probe = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude["_tag"], typeof WS_METHODS.serverProbe> => + tag !== WS_METHODS.serverProbe, + ), +); +const rpcs = RpcGroup.make(...KinLevelRpcs, ...probe.requests.values()).middleware( + RpcScopeAuthorization, +); +const decodePromotion = Schema.decodeUnknownSync(KinPromotionCard); +const decodeReview = Schema.decodeUnknownSync(KinShadowReviewCard); + +const clientFor = ( + handlers: Effect.Success>, + scopes: ReadonlyArray<(typeof AuthStandardClientScopes)[number]> = AuthStandardClientScopes, +) => + RpcTest.makeClient(rpcs).pipe( + Effect.provide( + Layer.merge( + rpcs.toLayer({ ...handlers, "server.probe": () => Effect.succeed({}) }), + RpcAuthorization.layer(scopes), + ), + ), + ); + +/** An L0 lead, its owner's direct chat, a group it is in, and one finished wake-up. */ +const seed = Effect.gen(function* () { + const kin = yield* Kin.KinServer; + const services = Option.getOrThrow(kin.services); + const identity = Context.get(services, KinIdentity); + const chat = Context.get(services, KinChatService); + const repo = yield* Repository.KinChatRepository; + const sql = yield* SqlClient.SqlClient; + const [owner] = yield* identity.resolve(session); + assert.isDefined(owner); + const { orgId } = owner; + const at = "1970-01-01T00:00:00.000Z"; + yield* repo.insertAgent({ + orgId, + agentId, + displayName: "Lead", + role: "lead", + ownerPersonId: owner.personId, + createdAt: at, + }); + const direct = yield* chat.createDirect(owner, { orgId, agentId }); + yield* sql`INSERT INTO kin_leads (agent_id, org_id, name, level, level_since, models_json, worker_projects_json, owner_chat_id) + VALUES (${agentId}, ${orgId}, 'Lead', 'L0', 0, '{}', '[]', ${direct.chatId})`; + yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, last_seq, created_at) + VALUES (${group}, ${orgId}, 'team_group', 0, ${at})`; + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, agent_id, role, joined_at) + VALUES ('group-lead', ${orgId}, ${group}, 'agent', ${agentId}, 'member', ${at})`; + yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, thread_id, model, started_at, status, event_ids) + VALUES ('wake', ${orgId}, ${agentId}, 'lead-thread', 'test', 0, 'completed', '[]')`; + yield* repo.insertPerson({ + orgId, + personId: memberId, + handle: "priya", + displayName: "Priya", + githubLogin: null, + createdAt: at, + }); + const lead = { orgId, agentId }; + for (const [human, thumbprint] of [ + [owner.personId, kid], + [memberId, memberKid], + ] as const) + yield* sql`INSERT INTO kin_approver_keys (thumbprint, org_id, public_jwk_json, human_id, + device_label, platform, hardware, attested, state, created_at) + VALUES (${thumbprint}, ${orgId}, '{}', ${human}, 'Pixel 9', 'android', 'tee', 1, 'active', 0)`; + const pending = yield* PendingActions.KinPendingActions; + let jti = 0; + /** Signs the action as `human`, then claims it as the executor would unless `claim` is false. */ + const sign = ( + actionId: KinActionId, + { human = owner.personId, claim = true }: { human?: KinPersonId; claim?: boolean } = {}, + ) => + Effect.gen(function* () { + const action = Option.getOrThrow(yield* pending.get({ orgId, actionId })); + const iat = Math.floor((yield* Clock.currentTimeMillis) / 1000); + const approved = yield* pending.approve({ + orgId, + actionId, + revision: action.revision, + nonce: action.nonce, + jti: `jti-raise-${String(jti++).padStart(16, "0")}`, + approverHumanId: human, + keyThumbprint: human === owner.personId ? kid : memberKid, + compact: "compact", + iat, + exp: iat + 600, + }); + if (approved._tag !== "approved") return assert.fail(`not approved: ${approved._tag}`); + if (!claim) return { action, grant: approved.grant }; + assert.isTrue( + yield* pending.claim({ + orgId, + actionId, + revision: action.revision, + grantId: approved.grant.id, + }), + ); + return { action: { ...action, state: "executing" as const }, grant: approved.grant }; + }); + const entries = ( + ids: ReadonlyArray, + options: { readonly level?: string; readonly unlocks?: string; readonly at?: number } = {}, + ) => + Effect.forEach( + ids, + (id) => sql`INSERT INTO kin_shadow_entries + (entry_id, org_id, agent_id, wakeup_id, level, unlocks_level, tool, input_json, would_target, created_at) + VALUES (${id}, ${orgId}, ${agentId}, 'wake', ${options.level ?? "L0"}, ${options.unlocks ?? "L1"}, + 'kin_chat_post', ${JSON.stringify({ body: `Draft ${id}` })}, ${group}, ${options.at ?? DAY})`, + { discard: true }, + ); + const handlers = yield* makeKinHandlers(session); + const memberHandlers = yield* makeKinHandlers(session).pipe( + Effect.provideService(Kin.KinServer, { + ...kin, + services: Option.some( + Context.add(services, KinIdentity, { + ...identity, + resolve: () => Effect.succeed([{ _tag: "person", orgId, personId: memberId }]), + }), + ), + }), + ); + const widget = (id: string) => + repo + .getWidget({ orgId, widgetId: KinWidgetId.make(id) }) + .pipe(Effect.map(Option.getOrUndefined)); + const level = Effect.gen(function* () { + const [row] = yield* sql<{ + level: string; + }>`SELECT level FROM kin_leads WHERE org_id = ${orgId} ORDER BY agent_id`; + return row?.level; + }); + return { + owner, + lead, + direct, + sql, + services, + pending, + sign, + entries, + widget, + level, + client: yield* clientFor(handlers), + member: yield* clientFor(memberHandlers), + readOnly: yield* clientFor(handlers, [AuthOrchestrationReadScope]), + }; +}); + +const ids = (prefix: string, n: number) => Array.from({ length: n }, (_, i) => `${prefix}-${i}`); + +it.effect( + "eligibility: 20 reviewed, 16 Fine, none Harmful or unreviewed after 7 days; one Harmful blocks it", + () => + Effect.gen(function* () { + const { lead, client, entries, widget, services } = yield* seed; + yield* entries(ids("e", 21)); + // Entries that unlock another level never count toward this one. + yield* entries(ids("l2", 5), { unlocks: "L2" }); + for (const [index, id] of ids("e", 20).entries()) + yield* client["kin.levels.review"]({ + orgId: lead.orgId, + entryId: id, + verdict: index < 16 ? "fine" : "change", + }); + for (const id of ids("l2", 5)) + yield* client["kin.levels.review"]({ orgId: lead.orgId, entryId: id, verdict: "fine" }); + let view = yield* client["kin.levels.get"](lead); + assert.deepInclude(view.promotion, { from: "L0", to: "L1", reviewed: 20, fine: 16 }); + assert.isFalse(view.promotion.eligible); + // That day's evening: the review card holds its entries and their verdicts. + const promotion = Context.get(services, KinPromotion); + yield* TestClock.adjust("36 hours"); + yield* promotion.evening(lead); + assert.isUndefined(yield* widget(`promotion:${agentId}:L1`)); + const review = yield* widget(`shadow-review:${agentId}:1970-01-02`); + assert.isDefined(review); + const reviewed = decodeReview(review.state); + assert.strictEqual(reviewed.total, 26); + assert.strictEqual(reviewed.unreviewed, 1); + assert.strictEqual( + reviewed.title, + "Review what Lead would have done today: 25 of 26 reviewed, 1 unreviewed", + ); + assert.strictEqual( + reviewed.entries.find((entry) => entry.entryId === "e-0")?.verdict, + "fine", + ); + assert.strictEqual(reviewed.entries.find((entry) => entry.entryId === "e-20")?.verdict, null); + + yield* TestClock.adjust("6 days"); + yield* promotion.evening(lead); + // An unreviewed entry in the trial holds the promotion back. + view = yield* client["kin.levels.get"](lead); + assert.deepInclude(view.promotion, { unreviewed: 1, eligible: false }); + assert.isUndefined(yield* widget(`promotion:${agentId}:L1`)); + yield* client["kin.levels.review"]({ orgId: lead.orgId, entryId: "e-20", verdict: "fine" }); + view = yield* client["kin.levels.get"](lead); + assert.deepInclude(view.promotion, { reviewed: 21, unreviewed: 0, eligible: true }); + const card = yield* widget(`promotion:${agentId}:L1`); + assert.isDefined(card); + assert.deepInclude(decodePromotion(card.state), { + status: "ready", + title: + "Lead is ready for L1: 17 of 21 reviewed would have gone out unchanged, none harmful, none unreviewed.", + }); + assert.strictEqual(card.closedAt, null); + + // One Harmful, even at L0, means no promotion and no demotion. + const harmful = yield* client["kin.levels.review"]({ + orgId: lead.orgId, + entryId: "e-20", + verdict: "harmful", + }); + assert.strictEqual(harmful.loweredTo, null); + view = yield* client["kin.levels.get"](lead); + assert.isFalse(view.promotion.eligible); + const closed = yield* widget(`promotion:${agentId}:L1`); + assert.deepInclude(closed && decodePromotion(closed.state), { + status: "closed", + title: + "Lead's trial for L1: 16 of 21 reviewed would have gone out unchanged, 1 harmful, 0 unreviewed.", + }); + assert.isNotNull(closed?.closedAt ?? null); + assert.include( + yield* client["kin.levels.raise"]({ ...lead, level: "L1" }).pipe(Effect.flip), + { reason: "invalid_state" }, + ); + }).pipe(Effect.provide(root)), +); + +it.effect("the review card shows each action in full and lists unreviewed entries first", () => + Effect.gen(function* () { + const { lead, client, entries, sql, services, widget } = yield* seed; + yield* entries(ids("e", 55)); + const brief = "b".repeat(3_000); + const inputs = [ + [ + "delegate", + "kin_delegate", + { + kind: "build", + title: "Fix login", + goal: "Users can log in", + brief: "Patch the form", + projectId: "project-1", + model: "cheap", + }, + ], + ["follow-up", "kin_follow_up", { workerId: "worker-1", brief: "Also add a test" }], + [ + "delegate-all", + "kin_delegate", + { + kind: "review", + title: "Review login", + goal: "Find bugs", + brief: "", + projectId: "project-1", + baseRef: "origin/main", + reviewOf: "worker-1", + memoryItemIds: ["memory-1", "memory-2"], + quoted: [{ role: "owner", name: "Sam", text: "Ship it" }], + }, + ], + [ + "follow-up-quoted", + "kin_follow_up", + { + workerId: "worker-1", + brief: "Again", + quoted: [{ role: "github", name: "", text: "CI failed" }], + }, + ], + [ + "post", + "kin_chat_post", + { + chatId: "group", + body: "ok \u202Egnp.exe\u200B\nnext", + intent: "decision", + mentions: ["member-2"], + replyTo: "message-1", + }, + ], + ["opaque", "kin_chat_post", { body: "Hi", mentions: "everyone" }], + [ + "request", + "request_action", + { + kind: "merge_pull_request", + target: { + _tag: "pull_request", + host: "github.com", + repo: "acme/app", + number: 12, + mergeMethod: "squash", + deleteBranchAfter: true, + }, + reason: "Checks are green", + }, + ], + ["long", "kin_follow_up", { workerId: "worker-1", brief }], + ] as const; + for (const [id, tool, input] of inputs) + yield* sql`INSERT INTO kin_shadow_entries + (entry_id, org_id, agent_id, wakeup_id, level, unlocks_level, tool, input_json, would_target, created_at) + VALUES (${`a-${id}`}, ${lead.orgId}, ${agentId}, 'wake', 'L0', 'L2', ${tool}, + ${JSON.stringify(input)}, 'target', ${DAY})`; + const promotion = Context.get(services, KinPromotion); + yield* TestClock.adjust("36 hours"); + yield* promotion.evening(lead); + const read = Effect.gen(function* () { + const card = yield* widget(`shadow-review:${agentId}:1970-01-02`); + assert.isDefined(card); + return decodeReview(card.state); + }); + let card = yield* read; + assert.deepInclude(card, { total: 63, unreviewed: 63 }); + assert.strictEqual(card.entries.length, 50); + const shown = (id: string) => card.entries.find((entry) => entry.entryId === id); + assert.deepInclude(shown("a-delegate"), { + preview: + "build: Fix login\nProject: project-1\nModel: cheap\nGoal: Users can log in\nBrief: Patch the form", + truncated: false, + }); + assert.strictEqual(shown("a-follow-up")?.preview, "Worker: worker-1\nBrief: Also add a test"); + assert.deepInclude(shown("a-delegate-all"), { + preview: + "review: Review login\nProject: project-1\nBase: origin/main\nReviews: worker-1\nGoal: Find bugs\nMemory: memory-1, memory-2\nQuoted (owner, Sam): Ship it", + truncated: false, + }); + assert.strictEqual( + shown("a-follow-up-quoted")?.preview, + "Worker: worker-1\nBrief: Again\nQuoted (github): CI failed", + ); + // Direction overrides and invisible characters are spelled out, never applied. + assert.deepInclude(shown("a-post"), { + preview: + "ok [U+202E]gnp.exe[U+200B]\nnext\nIntent: decision\nMentions: member-2\nReply to: message-1", + truncated: false, + }); + assert.deepInclude(shown("a-opaque"), { preview: "Hi", truncated: true }); + assert.strictEqual( + shown("a-request")?.preview, + "merge_pull_request: acme/app#12, merge method squash, then delete the branch\nReason: Checks are green", + ); + assert.deepInclude(shown("a-long"), { truncated: true }); + assert.strictEqual(shown("a-long")?.preview.length, 2_000); + // Fine vouches for the whole action, so an action the card cut short can't be marked Fine. + for (const entryId of ["a-long", "a-opaque"]) { + assert.include( + yield* client["kin.levels.review"]({ orgId: lead.orgId, entryId, verdict: "fine" }).pipe( + Effect.flip, + ), + { reason: "invalid_state" }, + ); + assert.include( + yield* client["kin.levels.review"]({ orgId: lead.orgId, entryId, verdict: "harmful" }), + { verdict: "harmful" }, + ); + } + // Reviewing what the card shows brings the rest of the backlog onto it. + for (const entry of card.entries) + if (!entry.truncated) + yield* client["kin.levels.review"]({ + orgId: lead.orgId, + entryId: entry.entryId, + verdict: "fine", + }); + card = yield* read; + assert.deepInclude(card, { total: 63, unreviewed: 13 }); + assert.deepStrictEqual(card.entries.filter((entry) => entry.verdict === null).length, 13); + }).pipe(Effect.provide(root)), +); + +it.effect("every trial day with unreviewed entries gets a card, late entries included", () => + Effect.gen(function* () { + const { lead, client, entries, services, widget } = yield* seed; + const promotion = Context.get(services, KinPromotion); + const total = (day: string) => + Effect.map(widget(`shadow-review:${agentId}:${day}`), (card) => + card === undefined ? undefined : decodeReview(card.state).total, + ); + // 1970-01-02 had no evening run: the routine was off, or the org paused. + yield* entries(["skipped"]); + yield* TestClock.adjust(`${3 * 24 + 10} hours`); + yield* entries(["today"], { at: 3 * DAY + 9 * 3_600_000 }); + yield* client["kin.levels.get"](lead); + assert.strictEqual(yield* total("1970-01-02"), 1); + // Today's card waits for the evening summary. + assert.isUndefined(yield* total("1970-01-04")); + yield* TestClock.adjust("2 hours"); + yield* promotion.evening(lead); + assert.strictEqual(yield* total("1970-01-04"), 1); + // An entry made after that evening's card lands on it at the next evening. + yield* entries(["late"], { at: 3 * DAY + 20 * 3_600_000 }); + yield* TestClock.adjust("1 day"); + yield* promotion.evening(lead); + assert.strictEqual(yield* total("1970-01-04"), 2); + }).pipe(Effect.provide(root)), +); + +it.effect("only the lead's owner reads, reviews, lowers or raises; others are refused", () => + Effect.gen(function* () { + const { lead, client, member, readOnly, entries, sql, level } = yield* seed; + yield* entries(["e-0"]); + yield* sql`UPDATE kin_leads SET level = 'L2' WHERE org_id = ${lead.orgId}`; + const lowerGroup = { ...lead, chatId: group, level: "L0" as const }; + const refusals = yield* Effect.all([ + member["kin.levels.get"](lead).pipe(Effect.flip), + member["kin.levels.review"]({ orgId: lead.orgId, entryId: "e-0", verdict: "harmful" }).pipe( + Effect.flip, + ), + member["kin.levels.lower"](lowerGroup).pipe(Effect.flip), + member["kin.levels.raise"]({ ...lead, level: "L3" }).pipe(Effect.flip), + member["kin.levels.deferPromotion"](lead).pipe(Effect.flip), + member["kin.levels.shadowMemory"]({ ...lead, choice: "keep" }).pipe(Effect.flip), + ]); + for (const refusal of refusals) + assert.include(refusal, { _tag: "KinChatError", reason: "not_allowed" }); + assert.include( + yield* client["kin.levels.get"]({ orgId: KinOrgId.make("foreign"), agentId }).pipe( + Effect.flip, + ), + { reason: "not_found" }, + ); + // A read-only session may look, never change. + assert.strictEqual((yield* readOnly["kin.levels.get"](lead)).level, "L2"); + const forbidden = yield* Effect.all([ + readOnly["kin.levels.lower"](lowerGroup).pipe(Effect.flip), + readOnly["kin.levels.raise"]({ ...lead, level: "L3" }).pipe(Effect.flip), + readOnly["kin.levels.review"]({ orgId: lead.orgId, entryId: "e-0", verdict: "fine" }).pipe( + Effect.flip, + ), + ]); + for (const refusal of forbidden) + assert.strictEqual(refusal._tag, "EnvironmentAuthorizationError"); + const [entry] = yield* sql<{ + verdict: string | null; + }>`SELECT verdict FROM kin_shadow_entries ORDER BY entry_id`; + assert.strictEqual(entry?.verdict, null); + assert.strictEqual(yield* level, "L2"); + + // Lowering applies at once and shows; a chat goes back up only through a grant. + let view = yield* client["kin.levels.lower"](lowerGroup); + assert.deepStrictEqual( + view.chats.map(({ chatId, level }) => ({ chatId, level })), + [{ chatId: group, level: "L0" }], + ); + assert.strictEqual( + yield* KinLevels.effectiveLevel({ ...lead, chatId: group }).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + ), + "L0", + ); + view = yield* client["kin.levels.lower"]({ ...lead, level: "L1" }); + assert.strictEqual(view.level, "L1"); + assert.include(yield* client["kin.levels.lower"]({ ...lead, level: "L1" }).pipe(Effect.flip), { + reason: "invalid_state", + }); + const raised = yield* client["kin.levels.raise"]({ ...lead, chatId: group, level: "L1" }); + assert.strictEqual( + (yield* client["kin.levels.raise"]({ ...lead, chatId: group, level: "L1" })).actionId, + raised.actionId, + ); + view = yield* client["kin.levels.get"](lead); + assert.strictEqual(view.chats[0]?.level, "L0"); + assert.include( + yield* client["kin.levels.raise"]({ ...lead, chatId: group, level: "L2" }).pipe(Effect.flip), + { reason: "invalid_state" }, + ); + // Once the lead has left the chat, no raise for it is created or handed back. + yield* sql`UPDATE kin_chat_members SET left_at = '1970-01-02T00:00:00.000Z' + WHERE org_id = ${lead.orgId} AND member_id = 'group-lead'`; + yield* sql`UPDATE kin_pending_actions SET state = 'rejected' WHERE org_id = ${lead.orgId}`; + assert.include( + yield* client["kin.levels.raise"]({ ...lead, chatId: group, level: "L1" }).pipe(Effect.flip), + { reason: "not_found" }, + ); + const [actions] = yield* sql<{ n: number }>`SELECT COUNT(*) AS n FROM kin_pending_actions + WHERE org_id = ${lead.orgId} ORDER BY n`; + assert.strictEqual(actions?.n, 1); + }).pipe(Effect.provide(root)), +); + +/** 20 Fine entries reviewed and a week at L0: the lead is eligible for L1. */ +const eligible = (ctx: Effect.Success) => + Effect.gen(function* () { + yield* ctx.entries(ids("e", 20)); + for (const id of ids("e", 20)) + yield* ctx.client["kin.levels.review"]({ + orgId: ctx.lead.orgId, + entryId: id, + verdict: "fine", + }); + yield* TestClock.adjust("7 days"); + yield* Context.get(ctx.services, KinPromotion).evening(ctx.lead); + }); + +const executor = (ctx: Effect.Success) => + Effect.gen(function* () { + const withSql = Effect.provideService(SqlClient.SqlClient, ctx.sql); + const cards = Effect.provideService( + KinLevels.KinPromotionCards, + Context.get(ctx.services, KinLevels.KinPromotionCards), + ); + const handler = yield* makeSetLevelHandler.pipe(withSql); + const raiseByGrant = (actionId: KinActionId) => + KinLevels.raiseByGrant({ orgId: ctx.lead.orgId, actionId }).pipe(withSql, Effect.flip); + return { handler, cards, raiseByGrant }; + }); + +it.effect("a raise applies only through the claimed set_level action its own owner signed", () => + Effect.gen(function* () { + const ctx = yield* seed; + const { lead, client, widget, sql, level, pending, sign } = ctx; + yield* eligible(ctx); + assert.include(yield* client["kin.levels.raise"]({ ...lead, level: "L2" }).pipe(Effect.flip), { + reason: "invalid_state", + }); + const { actionId } = yield* client["kin.levels.raise"]({ ...lead, level: "L1" }); + assert.strictEqual( + (yield* client["kin.levels.raise"]({ ...lead, level: "L1" })).actionId, + actionId, + ); + const action = Option.getOrThrow(yield* pending.get({ orgId: lead.orgId, actionId })); + assert.deepInclude(action, { kind: "set_level", state: "awaiting_approval" }); + assert.deepStrictEqual(action.requestedBy, { + agentId: "kin-promotion", + threadId: "kin-promotion", + }); + assert.deepStrictEqual((yield* client["kin.levels.get"](lead)).pendingRaises, [ + { actionId, chatId: null, level: "L1", state: "awaiting_approval" }, + ]); + const card = yield* widget(`promotion:${agentId}:L1`); + assert.deepInclude(card && decodePromotion(card.state), { + status: "awaiting_approval", + actionId, + }); + + const { handler, cards, raiseByGrant } = yield* executor(ctx); + const notGranted = { _tag: "KinLevelRefused", reason: "not_granted" } as const; + // Without a verified, claimed grant nothing raises the level. + assert.include(yield* raiseByGrant(actionId), notGranted); + // Approved but not claimed by the executor is still not enough. + const approved = yield* sign(actionId, { human: memberId, claim: false }); + assert.include(yield* handler.run(action, approved.grant).pipe(Effect.flip), { + reason: "invalid_state", + }); + // Claimed under another person's grant, even an owner of the org, it never applies. + assert.isTrue( + yield* pending.claim({ + orgId: lead.orgId, + actionId, + revision: action.revision, + grantId: approved.grant.id, + }), + ); + const claimedByMember = { ...action, state: "executing" as const }; + assert.include(yield* handler.run(claimedByMember, approved.grant).pipe(Effect.flip), { + reason: "invalid_state", + }); + assert.include(yield* raiseByGrant(actionId), notGranted); + assert.strictEqual(yield* level, "L0"); + // Once that execution failed, the action never applies, though the lead is still eligible. + yield* pending.finish({ orgId: lead.orgId, actionId, outcome: "failed", error: "refused" }); + assert.include(yield* raiseByGrant(actionId), notGranted); + assert.strictEqual(yield* level, "L0"); + + const second = (yield* client["kin.levels.raise"]({ ...lead, level: "L1" })).actionId; + assert.notStrictEqual(second, actionId); + const signed = yield* sign(second); + yield* handler.precheck(signed.action); + assert.strictEqual(yield* handler.run(signed.action, signed.grant).pipe(cards), "succeeded"); + assert.strictEqual(yield* level, "L1"); + assert.strictEqual(yield* handler.reconcile(signed.action), "done"); + const raised = yield* widget(`promotion:${agentId}:L1`); + assert.deepInclude(raised && decodePromotion(raised.state), { + status: "raised", + shadowMemory: "pending", + }); + // After success the action is spent: with the lead back at L0 and eligible, it still refuses. + yield* pending.finish({ orgId: lead.orgId, actionId: second, outcome: "succeeded" }); + yield* sql`UPDATE kin_leads SET level = 'L0', level_since = 0 WHERE org_id = ${lead.orgId}`; + assert.isTrue((yield* client["kin.levels.get"](lead)).promotion.eligible); + assert.include(yield* raiseByGrant(second), notGranted); + assert.strictEqual(yield* level, "L0"); + }).pipe(Effect.provide(root)), +); + +it.effect("lowering withdraws the raises it overtook and shows what stays open", () => + Effect.gen(function* () { + const ctx = yield* seed; + const { lead, client, sql, pending, sign, entries } = ctx; + const state = (actionId: KinActionId) => + pending + .get({ orgId: lead.orgId, actionId }) + .pipe(Effect.map((action) => Option.getOrThrow(action).state)); + yield* sql`UPDATE kin_leads SET level = 'L3' WHERE org_id = ${lead.orgId}`; + yield* client["kin.levels.lower"]({ ...lead, chatId: group, level: "L1" }); + const toL2 = (yield* client["kin.levels.raise"]({ ...lead, chatId: group, level: "L2" })) + .actionId; + const toL3 = (yield* client["kin.levels.raise"]({ ...lead, chatId: group, level: "L3" })) + .actionId; + assert.deepStrictEqual( + (yield* client["kin.levels.get"](lead)).pendingRaises.map(({ level }) => level), + ["L2", "L3"], + ); + // A lower lead level withdraws a chat raise above it and keeps the one it still allows. + let view = yield* client["kin.levels.lower"]({ ...lead, level: "L2" }); + assert.deepStrictEqual( + view.pendingRaises.map(({ actionId }) => actionId), + [toL2], + ); + assert.strictEqual(yield* state(toL3), "cancelled"); + view = yield* client["kin.levels.lower"]({ ...lead, chatId: group, level: "L0" }); + assert.deepStrictEqual(view.pendingRaises, []); + assert.strictEqual(yield* state(toL2), "cancelled"); + + // An approved raise of the lead itself is voided when the lead goes below it. + yield* sql`UPDATE kin_leads SET level = 'L1', level_since = 0 WHERE org_id = ${lead.orgId}`; + yield* entries(ids("u", 20), { level: "L1", unlocks: "L2" }); + for (const id of ids("u", 20)) + yield* client["kin.levels.review"]({ orgId: lead.orgId, entryId: id, verdict: "fine" }); + yield* TestClock.adjust("7 days"); + const toLeadL2 = (yield* client["kin.levels.raise"]({ ...lead, level: "L2" })).actionId; + yield* sign(toLeadL2, { claim: false }); + assert.strictEqual(yield* state(toLeadL2), "approved"); + view = yield* client["kin.levels.lower"]({ ...lead, level: "L0" }); + assert.deepStrictEqual(view.pendingRaises, []); + assert.strictEqual(yield* state(toLeadL2), "voided"); + }).pipe(Effect.provide(root)), +); + +it.effect("Harmful on what the lead did at L1 or above lowers it a level and tells the owner", () => + Effect.gen(function* () { + const { lead, client, entries, sql, direct, level } = yield* seed; + yield* sql`UPDATE kin_leads SET level = 'L1' WHERE org_id = ${lead.orgId}`; + yield* entries(["at-l1"], { level: "L1", unlocks: "L2" }); + const first = yield* client["kin.levels.review"]({ + orgId: lead.orgId, + entryId: "at-l1", + verdict: "harmful", + }); + assert.strictEqual(first.loweredTo, "L0"); + assert.strictEqual(yield* level, "L0"); + const [notice] = yield* sql<{ body: string }>`SELECT body FROM kin_messages + WHERE org_id = ${lead.orgId} AND chat_id = ${direct.chatId} + AND message_id = 'kin-level-lowered:at-l1' + ORDER BY message_id`; + assert.include(notice?.body ?? "", "moved down to L0"); + // The same verdict again lowers nothing further. + assert.strictEqual( + (yield* client["kin.levels.review"]({ + orgId: lead.orgId, + entryId: "at-l1", + verdict: "harmful", + })).loweredTo, + null, + ); + assert.strictEqual(yield* level, "L0"); + }).pipe(Effect.provide(root)), +); + +/** Raises an eligible L0 lead to L1 with a writer attached that lists `listed`. */ +const raisedFromL0 = (ctx: Effect.Success, listed: ReadonlyArray) => + Effect.gen(function* () { + const settled: Array[2]> = []; + yield* Context.get(ctx.services, KinPromotion).attachShadowMemory((_org, _agent, choice) => + Effect.sync(() => { + settled.push(choice); + return { paths: listed }; + }), + ); + yield* eligible(ctx); + const { actionId } = yield* ctx.client["kin.levels.raise"]({ ...ctx.lead, level: "L1" }); + const signed = yield* ctx.sign(actionId); + const { handler, cards } = yield* executor(ctx); + yield* handler.run(signed.action, signed.grant).pipe(cards); + const card = yield* ctx.widget(`promotion:${agentId}:L1`); + return { settled, card: card && decodePromotion(card.state) }; + }); + +it.effect("Keep shadow memory commits only the paths the card listed, after L0", () => + Effect.gen(function* () { + const ctx = yield* seed; + const { lead, client } = ctx; + const input = { ...lead, choice: "keep" as const }; + assert.include(yield* client["kin.levels.shadowMemory"](input).pipe(Effect.flip), { + reason: "invalid_state", + }); + const listed = ["deferrals/def-001.md", "journal/2026/11-09.md"]; + const settled = yield* Effect.scoped( + Effect.gen(function* () { + const { settled, card } = yield* raisedFromL0(ctx, listed); + assert.deepInclude(card, { + shadowMemory: "pending", + shadowChanges: { paths: listed, truncated: false, ownerReviewed: [] }, + }); + yield* client["kin.levels.shadowMemory"](input); + const kept = yield* ctx.widget(`promotion:${agentId}:L1`); + assert.strictEqual(kept && decodePromotion(kept.state).shadowMemory, "kept"); + return settled; + }), + ); + assert.deepStrictEqual(settled, [{ _tag: "preview" }, { _tag: "keep", paths: listed }]); + // Detached with its runtime: nothing settles memory any more. + assert.include(yield* client["kin.levels.shadowMemory"](input).pipe(Effect.flip), { + reason: "unavailable", + }); + }).pipe(Effect.provide(root)), +); + +it.effect( + "Keep is refused when shadow memory changes owner-reviewed paths; Start clean stays", + () => + Effect.gen(function* () { + const ctx = yield* seed; + const { lead, client } = ctx; + yield* Effect.scoped( + Effect.gen(function* () { + const { settled, card } = yield* raisedFromL0(ctx, [ + "decisions/dec-001.md", + "deferrals/def-001.md", + ]); + assert.deepStrictEqual(card?.shadowChanges?.ownerReviewed, ["decisions/dec-001.md"]); + const refusal = yield* client["kin.levels.shadowMemory"]({ + ...lead, + choice: "keep", + }).pipe(Effect.flip); + assert.include(refusal, { reason: "invalid_state" }); + assert.include(refusal.message, "decisions/dec-001.md"); + yield* client["kin.levels.shadowMemory"]({ ...lead, choice: "discard" }); + assert.deepStrictEqual(settled, [{ _tag: "preview" }, { _tag: "discard" }]); + const discarded = yield* ctx.widget(`promotion:${agentId}:L1`); + assert.strictEqual( + discarded && decodePromotion(discarded.state).shadowMemory, + "discarded", + ); + // With no list on a pending card, Keep has nothing the owner reviewed to commit. + assert.include( + yield* client["kin.levels.shadowMemory"]({ ...lead, choice: "keep" }).pipe(Effect.flip), + { reason: "invalid_state" }, + ); + assert.strictEqual(settled.length, 2); + }), + ); + }).pipe(Effect.provide(root)), +); + +it.effect("level cards take no taps through the lead's widget path; Another week waits", () => + Effect.gen(function* () { + const { lead, client, entries, services, owner, widget } = yield* seed; + yield* entries(ids("e", 20)); + for (const id of ids("e", 20)) + yield* client["kin.levels.review"]({ orgId: lead.orgId, entryId: id, verdict: "fine" }); + yield* TestClock.adjust("36 hours"); + yield* Context.get(services, KinPromotion).evening(lead); + yield* TestClock.adjust("6 days"); + yield* Context.get(services, KinPromotion).evening(lead); + const chat = Context.get(services, KinChatService); + for (const widgetId of [`promotion:${agentId}:L1`, `shadow-review:${agentId}:1970-01-02`]) + assert.include( + yield* chat + .act(owner, { + widgetId: KinWidgetId.make(widgetId), + revision: 1, + actionId: "raise", + clientActionId: widgetId, + }) + .pipe(Effect.flip), + { reason: "not_allowed" }, + ); + yield* client["kin.levels.deferPromotion"](lead); + const deferred = yield* widget(`promotion:${agentId}:L1`); + assert.strictEqual(deferred && decodePromotion(deferred.state).status, "deferred"); + // The card comes back after the week; Raise works from settings meanwhile. + yield* TestClock.adjust("7 days"); + yield* Context.get(services, KinPromotion).evening(lead); + const back = yield* widget(`promotion:${agentId}:L1`); + assert.strictEqual(back && decodePromotion(back.state).status, "ready"); + assert.isString((yield* client["kin.levels.raise"]({ ...lead, level: "L1" })).actionId); + }).pipe(Effect.provide(root)), +); diff --git a/apps/server/src/kin/levels/Promotion.ts b/apps/server/src/kin/levels/Promotion.ts new file mode 100644 index 0000000000000..12475fca98e33 --- /dev/null +++ b/apps/server/src/kin/levels/Promotion.ts @@ -0,0 +1,902 @@ +import { + KIN_SHADOW_CHANGES_MAX, + KIN_SHADOW_REVIEW_TEXT_MAX, + KinActionTarget, + KinChatError, + KinChatId, + KinEventId, + KinMessageId, + KinPersonId, + KinPromotionCard, + KinShadowReviewCard, + KinWidgetId, + type KinActionId, + KinLevel, + KinAgentId, + ThreadId, + type KinLevelsGetInput, + type KinLevelsRaiseResult, + type KinLevelsReviewInput, + type KinLevelsReviewResult, + type KinLevelsSetInput, + type KinLevelsShadowMemoryInput, + type KinLevelsView, + type KinOrgId, + type KinPromotionStats, + type KinShadowVerdict, + type KinWidget, +} from "@t3tools/contracts"; +import { stableStringify } from "@t3tools/shared/relaySigning"; +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 type * as Scope from "effect/Scope"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as SqlError from "effect/sql/SqlError"; + +import { toPersistenceSqlError } from "../../persistence/Errors.ts"; +import { + KinPendingActions, + KIN_PROMOTION_REQUESTER, + kinTargetDigest, +} from "../approvals/PendingActions.ts"; +import * as Hub from "../chat/KinChatHub.ts"; +import * as Repository from "../chat/KinChatRepository.ts"; +import { KinChatService } from "../chat/KinChatService.ts"; +import type { PersonIdentity } from "../chat/KinIdentity.ts"; +import * as MemoryCache from "../memory/MemoryCache.ts"; +import * as KinLevels from "../lead/KinLevels.ts"; +import { describe, plainText } from "../lead/LevelGate.ts"; +import { isOwnerReviewedPath } from "../memory/lint.ts"; + +const DAY_MS = 86_400_000; +const REVIEW_ENTRIES = 50; +const OPEN_ACTION_STATES = ["awaiting_approval", "approved", "executing"]; + +/** The writer's preview, keep or discard, attached by the lead runtime that owns the writer. */ +export type KinShadowSettle = ( + orgId: KinOrgId, + agentId: KinAgentId, + choice: + | { readonly _tag: "preview" } + | { readonly _tag: "discard" } + | { readonly _tag: "keep"; readonly paths: ReadonlyArray }, +) => Effect.Effect< + { readonly paths: ReadonlyArray }, + { readonly _tag: string; readonly reason?: string | undefined } +>; + +type Lead = { readonly orgId: KinOrgId; readonly agentId: KinAgentId }; + +/** + * The owner's side of levels (lead spec, "Level promotion"): read, lower, verdicts, the promotion + * card and asking to raise. Raising only creates a `set_level` action; the owner's signed grant + * and the executor's `set_level` handler apply it. No MCP tool or agent path reaches this service. + */ +export class KinPromotion extends Context.Service< + KinPromotion, + { + readonly view: ( + people: ReadonlyArray, + input: KinLevelsGetInput, + ) => Effect.Effect; + readonly review: ( + people: ReadonlyArray, + input: KinLevelsReviewInput, + ) => Effect.Effect; + readonly lower: ( + people: ReadonlyArray, + input: KinLevelsSetInput, + ) => Effect.Effect; + readonly raise: ( + people: ReadonlyArray, + input: KinLevelsSetInput, + ) => Effect.Effect; + readonly deferPromotion: ( + people: ReadonlyArray, + input: KinLevelsGetInput, + ) => Effect.Effect; + readonly shadowMemory: ( + people: ReadonlyArray, + input: KinLevelsShadowMemoryInput, + ) => Effect.Effect; + /** The evening summary's cards: review cards for today and open trial days, then promotion. */ + readonly evening: (lead: Lead) => Effect.Effect; + readonly attachShadowMemory: ( + settle: KinShadowSettle, + ) => Effect.Effect; + } +>()("t3/kin/levels/Promotion/KinPromotion") {} + +const reviewWidgetId = (agentId: KinAgentId, day: string) => + KinWidgetId.make(`shadow-review:${agentId}:${day}`); +const promotionWidgetId = (agentId: KinAgentId, to: KinLevel) => + KinWidgetId.make(`promotion:${agentId}:${to}`); +const decodePromotion = Schema.decodeUnknownEffect(KinPromotionCard); +const encodePromotion = Schema.encodeEffect(KinPromotionCard); +const decodeReview = Schema.decodeUnknownEffect(KinShadowReviewCard); +const encodeReview = Schema.encodeEffect(KinShadowReviewCard); +const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown)); +const decodeLevel = Schema.decodeUnknownEffect(KinLevel); +const decodeTarget = Schema.decodeUnknownEffect(Schema.fromJsonString(KinActionTarget)); +type OpenRaiseState = "awaiting_approval" | "approved" | "executing"; +const isOpenRaiseState = (state: string): state is OpenRaiseState => + OPEN_ACTION_STATES.includes(state); + +const promotionTitle = (name: string, stats: KinPromotionStats) => + stats.eligible + ? `${name} is ready for ${stats.to}: ${stats.fine} of ${stats.reviewed} reviewed would have gone out unchanged, none harmful, none unreviewed.` + : `${name}'s trial for ${stats.to ?? stats.from}: ${stats.fine} of ${stats.reviewed} reviewed would have gone out unchanged, ${stats.harmful === 0 ? "none" : stats.harmful} harmful, ${stats.unreviewed} unreviewed.`; +const iso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); + +const refused = (reason: KinChatError["reason"], message: string) => + new KinChatError({ reason, message }); +const notAllowed = refused("not_allowed", "Only the lead's owner can change its level."); +const notShownInFull = refused( + "invalid_state", + "This action was too long to show in full, so it can't be marked Fine as is. Choose another verdict.", +); +const notFound = refused("not_found", "Kin record not found."); +const unavailable = refused("unavailable", "Kin is unavailable."); +const LEVEL_REFUSALS: Record = { + not_a_lead: notFound, + not_found: notFound, + not_running: refused("invalid_state", "The lead isn't running."), + conflict: refused("invalid_state", "The level changed meanwhile; refresh and try again."), + limit: refused("limit", "The level can't change now."), + invalid_level: refused( + "invalid_state", + "Lower goes down; raise goes up one level, or a chat back up to the lead's level.", + ), + not_eligible: refused("invalid_state", "The lead isn't eligible for the next level yet."), + not_granted: refused("not_allowed", "Raising a level needs the owner's signed approval."), +}; + +const isKinChatError = Schema.is(KinChatError); +const isLevelRefused = Schema.is(KinLevels.KinLevelRefused); +const toChatError = (error: unknown) => + isKinChatError(error) + ? Effect.fail(error) + : isLevelRefused(error) + ? Effect.fail(LEVEL_REFUSALS[error.reason]) + : Effect.logWarning("Kin levels failed", error).pipe( + Effect.andThen(Effect.fail(unavailable)), + ); + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const chat = yield* KinChatService; + const repo = yield* Repository.KinChatRepository; + const hub = yield* Hub.KinChatHub; + const cache = yield* MemoryCache.MemoryCache; + const pending = yield* KinPendingActions; + let settle: KinShadowSettle | undefined; + + const withSql = (effect: Effect.Effect) => + Effect.provideService(effect, SqlClient.SqlClient, sql); + const run = (operation: string, effect: Effect.Effect) => + effect.pipe(Effect.mapError(toPersistenceSqlError(operation))); + const transaction = (effect: Effect.Effect) => + sql + .withTransaction(effect) + .pipe( + Effect.mapError((error) => + SqlError.isSqlError(error) + ? toPersistenceSqlError("KinPromotion.transaction")(error) + : error, + ), + ); + + /** The caller is the lead's own owner, read from stored rows in the caller's org. */ + const asOwner = Effect.fn("KinPromotion.asOwner")(function* ( + people: ReadonlyArray, + lead: Lead, + ) { + const person = people.find((candidate) => candidate.orgId === lead.orgId); + if (person === undefined) return yield* notFound; + const rows = yield* run( + "KinPromotion.asOwner", + sql`SELECT 1 FROM kin_leads l + JOIN kin_agents a ON a.org_id = l.org_id AND a.agent_id = l.agent_id + JOIN kin_people p ON p.org_id = a.org_id AND p.person_id = a.owner_person_id + WHERE l.org_id = ${lead.orgId} AND l.agent_id = ${lead.agentId} + AND a.role = 'lead' AND a.retired_at IS NULL AND a.owner_person_id = ${person.personId} + ORDER BY l.agent_id`, + ); + if (rows.length === 0) return yield* notAllowed; + return person; + }); + + // The lead's owner and its direct chat; cards preview entries, so they go nowhere else. + const ownerChat = Effect.fn("KinPromotion.ownerChat")(function* (lead: Lead) { + const [row] = yield* run( + "KinPromotion.ownerChat", + sql<{ name: string; chatId: string; owner: string }>` + SELECT l.name, l.owner_chat_id AS "chatId", a.owner_person_id AS owner FROM kin_leads l + JOIN kin_agents a ON a.org_id = l.org_id AND a.agent_id = l.agent_id + JOIN kin_chats c ON c.org_id = l.org_id AND c.chat_id = l.owner_chat_id AND c.kind = 'direct' + WHERE l.org_id = ${lead.orgId} AND l.agent_id = ${lead.agentId} + AND a.role = 'lead' AND a.retired_at IS NULL + ORDER BY l.agent_id`, + ); + return row; + }); + + const putCard = Effect.fn("KinPromotion.putCard")(function* (input: { + readonly lead: Lead; + readonly widgetId: KinWidgetId; + readonly type: "shadow_review" | "promotion"; + readonly title: string; + readonly state: unknown; + readonly create: boolean; + readonly waiting: boolean; + readonly closed: boolean; + }) { + const { orgId } = input.lead; + yield* transaction( + Effect.gen(function* () { + const owner = yield* ownerChat(input.lead); + if (owner === undefined) return; + const updatedAt = iso(yield* Clock.currentTimeMillis); + const awaiting = input.waiting ? [KinPersonId.make(owner.owner)] : []; + const closedAt = input.closed ? updatedAt : null; + const existing = yield* repo.getWidget({ orgId, widgetId: input.widgetId }); + if (Option.isNone(existing)) { + if (!input.create) return; + const { message } = yield* chat.notice({ + orgId, + chatId: KinChatId.make(owner.chatId), + messageId: KinMessageId.make(input.widgetId), + body: input.title, + }); + const widget: KinWidget = { + orgId, + chatId: message.chatId, + widgetId: input.widgetId, + messageId: message.messageId, + widgetClass: "native", + type: input.type, + revision: 1, + state: input.state, + source: null, + feed: null, + awaiting, + pinnedAt: null, + closedAt, + updatedAt, + }; + yield* repo.insertWidget(widget); + yield* sql.afterCommit(hub.publish({ type: "widget.updated", orgId, widget })); + return; + } + const current = existing.value; + if (current.type !== input.type) return; + if ( + stableStringify(current.state) === stableStringify(input.state) && + (current.closedAt === null) === (closedAt === null) && + current.awaiting.length === awaiting.length + ) + return; + const widget = yield* repo.updateWidget({ + ...current, + state: input.state, + awaiting, + closedAt, + expectedRevision: current.revision, + updatedAt, + }); + yield* sql.afterCommit(hub.publish({ type: "widget.updated", orgId, widget })); + }), + ); + }); + + const stats = (lead: Lead) => + withSql(KinLevels.promotionStats(lead)).pipe( + Effect.map(({ levelSince, ...promotion }) => ({ promotion, levelSince })), + ); + + /** The review card for the owner-local day holding `at`; `create` for the evening or a past day. */ + const drawReview = Effect.fn("KinPromotion.drawReview")(function* ( + lead: Lead, + at: number, + create: boolean, + ) { + const zone = yield* cache.ownerTimeZone(lead.orgId); + const start = DateTime.startOf(DateTime.makeZonedUnsafe(at, { timeZone: zone }), "day"); + const from = DateTime.toEpochMillis(start); + const until = DateTime.toEpochMillis(DateTime.add(start, { days: 1 })); + const day = DateTime.formatIsoDate(start); + const [count] = yield* run( + "KinPromotion.reviewCount", + sql<{ n: number }>`SELECT COUNT(*) AS n FROM kin_shadow_entries + WHERE org_id = ${lead.orgId} AND agent_id = ${lead.agentId} + AND created_at >= ${from} AND created_at < ${until} + ORDER BY n`, + ); + const total = count?.n ?? 0; + if (total === 0) return; + const [open] = yield* run( + "KinPromotion.reviewUnreviewed", + sql<{ n: number }>`SELECT COUNT(*) AS n FROM kin_shadow_entries + WHERE org_id = ${lead.orgId} AND agent_id = ${lead.agentId} + AND created_at >= ${from} AND created_at < ${until} AND verdict IS NULL + ORDER BY n`, + ); + const unreviewed = open?.n ?? 0; + const owner = yield* ownerChat(lead); + if (owner === undefined) return; + // Unreviewed entries first, so the newest day's backlog never hides behind reviewed ones. + const rows = yield* run( + "KinPromotion.reviewEntries", + sql<{ + entryId: string; + tool: string; + level: string; + unlocksLevel: string; + wouldTarget: string; + json: string; + createdAt: number; + verdict: KinShadowVerdict | null; + }>`SELECT entry_id AS "entryId", tool, level, unlocks_level AS "unlocksLevel", + would_target AS "wouldTarget", input_json AS json, created_at AS "createdAt", verdict + FROM kin_shadow_entries + WHERE org_id = ${lead.orgId} AND agent_id = ${lead.agentId} + AND created_at >= ${from} AND created_at < ${until} + ORDER BY verdict IS NOT NULL, created_at, entry_id LIMIT ${REVIEW_ENTRIES}`, + ); + const { promotion } = yield* stats(lead); + const title = `Review what ${owner.name} would have done today: ${total - unreviewed} of ${total} reviewed, ${unreviewed} unreviewed`; + const card = yield* decodeReview({ + agentId: lead.agentId, + title, + day, + total, + unreviewed, + entries: yield* Effect.forEach( + rows.toSorted((a, b) => a.createdAt - b.createdAt || (a.entryId < b.entryId ? -1 : 1)), + (row) => + Effect.map(decodeJson(row.json), (parsed) => { + const shown = describe(row.tool, parsed, KIN_SHADOW_REVIEW_TEXT_MAX); + return { + entryId: row.entryId, + tool: row.tool, + level: row.level, + unlocksLevel: row.unlocksLevel, + wouldTarget: plainText(row.wouldTarget), + preview: shown.text, + truncated: shown.truncated, + createdAt: iso(row.createdAt), + verdict: row.verdict, + }; + }), + ), + promotion, + }); + yield* putCard({ + lead, + widgetId: reviewWidgetId(lead.agentId, day), + type: "shadow_review", + title, + state: yield* encodeReview(card), + create, + waiting: false, + closed: false, + }); + }); + + /** + * Every trial day with unreviewed entries gets its card, so none block eligibility out of reach. + * Today's card is only updated: the evening summary posts it. + */ + const drawBacklog = Effect.fn("KinPromotion.drawBacklog")(function* (lead: Lead) { + const { promotion, levelSince } = yield* stats(lead); + if (promotion.to === null || promotion.unreviewed === 0) return; + const zone = yield* cache.ownerTimeZone(lead.orgId); + const now = yield* Clock.currentTimeMillis; + const dayStart = (at: number) => + DateTime.startOf(DateTime.makeZonedUnsafe(at, { timeZone: zone }), "day"); + const today = DateTime.toEpochMillis(dayStart(now)); + let cursor = levelSince; + // One card per owner-local day of the trial, at most. + for (let day = 0; day <= Math.ceil((now - levelSince) / DAY_MS) + 1; day++) { + const [next] = yield* run( + "KinPromotion.backlog", + sql<{ createdAt: number }>`SELECT created_at AS "createdAt" FROM kin_shadow_entries + WHERE org_id = ${lead.orgId} AND agent_id = ${lead.agentId} + AND unlocks_level = ${promotion.to} AND created_at >= ${cursor} AND verdict IS NULL + ORDER BY created_at, entry_id LIMIT 1`, + ); + if (next === undefined) return; + yield* drawReview(lead, next.createdAt, next.createdAt < today); + cursor = DateTime.toEpochMillis(DateTime.add(dayStart(next.createdAt), { days: 1 })); + } + }); + + const readPromotion = Effect.fn("KinPromotion.readPromotion")(function* ( + orgId: KinOrgId, + widgetId: KinWidgetId, + ) { + const widget = yield* repo.getWidget({ orgId, widgetId }); + if (Option.isNone(widget) || widget.value.type !== "promotion") return undefined; + return yield* decodePromotion(widget.value.state); + }); + + const putPromotion = Effect.fn("KinPromotion.putPromotion")(function* ( + lead: Lead, + card: KinPromotionCard, + ) { + yield* putCard({ + lead, + widgetId: promotionWidgetId(lead.agentId, card.stats.to ?? card.stats.from), + type: "promotion", + title: card.title, + state: yield* encodePromotion(card), + create: true, + waiting: card.status === "ready" || card.shadowMemory === "pending", + closed: + card.status === "closed" || (card.status === "raised" && card.shadowMemory !== "pending"), + }); + }); + + const actionOpen = Effect.fn("KinPromotion.actionOpen")(function* ( + orgId: KinOrgId, + actionId: KinActionId | null, + ) { + if (actionId === null) return false; + const action = yield* pending.get({ orgId, actionId }); + return Option.isSome(action) && OPEN_ACTION_STATES.includes(action.value.state); + }); + + /** What Keep would commit, for the card; null when the writer can't list it now. */ + const listShadow = Effect.fn("KinPromotion.listShadow")(function* (lead: Lead) { + if (settle === undefined) return null; + return yield* settle(lead.orgId, lead.agentId, { _tag: "preview" }).pipe( + Effect.map(({ paths }) => { + const ownerReviewed = paths.filter(isOwnerReviewedPath); + return { + paths: paths.slice(0, KIN_SHADOW_CHANGES_MAX), + truncated: paths.length > KIN_SHADOW_CHANGES_MAX, + ownerReviewed: ownerReviewed.slice(0, KIN_SHADOW_CHANGES_MAX), + }; + }), + Effect.catch((error) => + Effect.logWarning("Kin shadow memory list failed", { errorTag: error._tag }).pipe( + Effect.as(null), + ), + ), + ); + }); + + /** Lead spec step 3: one card in the owner's direct chat once the lead is eligible. */ + const refresh = Effect.fn("KinPromotion.refresh")(function* (lead: Lead) { + const { promotion } = yield* stats(lead); + const owner = yield* ownerChat(lead); + if (owner === undefined) return; + const now = yield* Clock.currentTimeMillis; + // The card that asked for the level the lead now holds has been granted. + const reached = yield* readPromotion( + lead.orgId, + promotionWidgetId(lead.agentId, promotion.from), + ); + if (reached?.status === "awaiting_approval") { + const fromL0 = reached.stats.from === "L0"; + yield* putPromotion(lead, { + ...reached, + status: "raised", + shadowMemory: fromL0 ? "pending" : null, + shadowChanges: fromL0 ? yield* listShadow(lead) : null, + }); + } else if ( + reached?.status === "raised" && + reached.shadowMemory === "pending" && + reached.shadowChanges === null + ) { + const listed = yield* listShadow(lead); + if (listed !== null) yield* putPromotion(lead, { ...reached, shadowChanges: listed }); + } + if (promotion.to === null) return; + const to = promotion.to; + const title = promotionTitle(owner.name, promotion); + const ready = { + agentId: lead.agentId, + title, + stats: promotion, + status: "ready" as const, + actionId: null, + deferredUntil: null, + shadowMemory: null, + shadowChanges: null, + }; + const card = yield* readPromotion(lead.orgId, promotionWidgetId(lead.agentId, to)); + if (card === undefined) { + if (promotion.eligible) yield* putPromotion(lead, ready); + return; + } + const updated = { ...card, title, stats: promotion }; + switch (card.status) { + case "awaiting_approval": + if (yield* actionOpen(lead.orgId, card.actionId)) return yield* putPromotion(lead, updated); + return yield* putPromotion( + lead, + promotion.eligible ? ready : { ...updated, status: "closed" }, + ); + case "deferred": { + const until = card.deferredUntil === null ? 0 : Date.parse(card.deferredUntil); + return yield* putPromotion(lead, promotion.eligible && now >= until ? ready : updated); + } + case "ready": + return yield* putPromotion( + lead, + promotion.eligible ? ready : { ...updated, status: "closed" }, + ); + case "closed": + if (promotion.eligible) yield* putPromotion(lead, ready); + return; + case "raised": + // The lead is back below this card's level: its shadow-memory choice no longer applies. + return yield* putPromotion( + lead, + promotion.eligible + ? ready + : { ...updated, status: "closed", shadowMemory: null, shadowChanges: null }, + ); + } + }); + + const bestEffort = (what: string) => + Effect.catchCause((cause) => Effect.logWarning(`Kin ${what} failed`, { cause })); + const refreshCards = (lead: Lead) => + drawBacklog(lead).pipe( + bestEffort("review backlog"), + Effect.andThen(refresh(lead).pipe(bestEffort("promotion card refresh"))), + ); + + const openRaises = Effect.fn("KinPromotion.openRaises")(function* (lead: Lead) { + const rows = yield* run( + "KinPromotion.openRaises", + sql<{ actionId: KinActionId; revision: number; state: string; targetJson: string }>` + SELECT action_id AS "actionId", revision, state, target_json AS "targetJson" + FROM kin_pending_actions + WHERE org_id = ${lead.orgId} AND kind = 'set_level' + AND json_extract(target_json, '$.agentId') = ${lead.agentId} + AND state IN ('awaiting_approval', 'approved', 'executing') + ORDER BY created_at, action_id`, + ); + return yield* Effect.forEach(rows, (row) => + decodeTarget(row.targetJson).pipe( + Effect.map((target) => + target._tag === "level" && isOpenRaiseState(row.state) + ? [{ ...row, state: row.state, chatId: target.chatId ?? null, level: target.level }] + : [], + ), + ), + ).pipe(Effect.map((all) => all.flat())); + }); + + /** + * A lower level withdraws the raises it overtook: the lead's own and every chat's above a new + * lead level, or that chat's above a new chat cap. An executing raise is refused by its handler. + */ + const closeRaises = Effect.fn("KinPromotion.closeRaises")(function* ( + lead: Lead, + lowered: { readonly chatId?: KinChatId | undefined; readonly level: KinLevel }, + ) { + for (const raise of yield* openRaises(lead)) { + if (raise.state === "executing" || KinLevels.atLeast(lowered.level, raise.level)) continue; + if (lowered.chatId !== undefined && raise.chatId !== lowered.chatId) continue; + yield* pending.transition({ + orgId: lead.orgId, + actionId: raise.actionId, + revision: raise.revision, + to: raise.state === "approved" ? "voided" : "cancelled", + reason: "level_lowered", + }); + } + }); + + const view = Effect.fn("KinPromotion.view")(function* (lead: Lead) { + const { promotion, levelSince } = yield* stats(lead); + const chats = yield* run( + "KinPromotion.chatLevels", + sql<{ chatId: string; level: string; since: number }>` + SELECT chat_id AS "chatId", level, level_since AS since FROM kin_chat_levels + WHERE org_id = ${lead.orgId} AND agent_id = ${lead.agentId} + ORDER BY chat_id`, + ); + return { + orgId: lead.orgId, + agentId: lead.agentId, + level: promotion.from, + levelSince: iso(levelSince), + chats: yield* Effect.forEach(chats, (row) => + decodeLevel(row.level).pipe( + Effect.map((level) => ({ + chatId: KinChatId.make(row.chatId), + level, + levelSince: iso(row.since), + })), + ), + ), + promotion, + pendingRaises: (yield* openRaises(lead)).map(({ actionId, chatId, level, state }) => ({ + actionId, + chatId, + level, + state, + })), + } satisfies KinLevelsView; + }); + + const promotion = KinPromotion.of({ + view: Effect.fn("KinPromotion.get")(function* (people, input) { + yield* asOwner(people, input); + yield* drawBacklog(input).pipe(bestEffort("review backlog")); + return yield* view(input); + }, Effect.catch(toChatError)), + + review: Effect.fn("KinPromotion.review")(function* (people, input) { + const now = yield* Clock.currentTimeMillis; + const reviewed = yield* transaction( + Effect.gen(function* () { + const [entry] = yield* run( + "KinPromotion.entry", + sql<{ + agentId: string; + level: string; + verdict: string | null; + createdAt: number; + tool: string; + json: string; + }>`SELECT agent_id AS "agentId", level, verdict, created_at AS "createdAt", tool, + input_json AS json + FROM kin_shadow_entries WHERE org_id = ${input.orgId} AND entry_id = ${input.entryId} + ORDER BY entry_id`, + ); + if (entry === undefined) return yield* notFound; + const lead = { orgId: input.orgId, agentId: KinAgentId.make(entry.agentId) }; + yield* asOwner(people, lead); + // Fine vouches for the whole action, so it needs the whole action on the card. + if (input.verdict === "fine") { + const parsed = yield* decodeJson(entry.json).pipe(Effect.option); + if ( + Option.isNone(parsed) || + describe(entry.tool, parsed.value, KIN_SHADOW_REVIEW_TEXT_MAX).truncated + ) + return yield* notShownInFull; + } + const updated = yield* run( + "KinPromotion.verdict", + sql`UPDATE kin_shadow_entries SET verdict = ${input.verdict}, + verdict_note = ${input.note ?? null}, reviewed_at = ${now} + WHERE org_id = ${input.orgId} AND entry_id = ${input.entryId} + AND agent_id = ${lead.agentId} + RETURNING entry_id`, + ); + if (updated.length === 0) return yield* notFound; + const done = { lead, createdAt: entry.createdAt, loweredTo: null }; + // Lead spec step 5: harm in what the lead did at L1 or above costs it a level. + const { promotion } = yield* stats(lead); + const below = KinLevels.previousLevel(promotion.from); + if ( + input.verdict !== "harmful" || + entry.verdict === "harmful" || + entry.level === "L0" || + below === undefined + ) + return done; + yield* withSql(KinLevels.lower({ ...lead, level: below })); + const owner = yield* ownerChat(lead); + if (owner !== undefined) + yield* chat.notice({ + orgId: input.orgId, + chatId: KinChatId.make(owner.chatId), + messageId: KinMessageId.make(`kin-level-lowered:${input.entryId}`), + body: `${owner.name} moved down to ${below}: you marked something it did at ${entry.level} as harmful. Raising it again takes another trial and your approval.`, + }); + return { ...done, loweredTo: below }; + }), + ); + if (reviewed.loweredTo !== null) + yield* closeRaises(reviewed.lead, { level: reviewed.loweredTo }).pipe( + bestEffort("raise withdrawal"), + ); + yield* drawReview(reviewed.lead, reviewed.createdAt, false).pipe( + bestEffort("review card refresh"), + ); + yield* refreshCards(reviewed.lead); + return { entryId: input.entryId, verdict: input.verdict, loweredTo: reviewed.loweredTo }; + }, Effect.catch(toChatError)), + + lower: Effect.fn("KinPromotion.lower")(function* (people, input) { + yield* asOwner(people, input); + yield* withSql(KinLevels.lower(input)); + yield* closeRaises(input, input).pipe(bestEffort("raise withdrawal")); + yield* refreshCards(input); + return yield* view(input); + }, Effect.catch(toChatError)), + + raise: Effect.fn("KinPromotion.raise")(function* (people, input) { + const person = yield* asOwner(people, input); + const chatKey = input.chatId ?? ""; + // The lead, chat membership and eligibility are checked in the write that creates the row. + const actionId = yield* transaction( + Effect.gen(function* () { + yield* withSql(KinLevels.checkRaise(input)); + const sameTarget = sql`kind = 'set_level' AND org_id = ${input.orgId} + AND json_extract(target_json, '$.agentId') = ${input.agentId} + AND json_extract(target_json, '$.level') = ${input.level} + AND IFNULL(json_extract(target_json, '$.chatId'), '') = ${chatKey}`; + const [open] = yield* run( + "KinPromotion.openRaise", + sql<{ actionId: KinActionId }>`SELECT action_id AS "actionId" FROM kin_pending_actions + WHERE ${sameTarget} AND state IN ('awaiting_approval', 'approved', 'executing') + ORDER BY created_at DESC, action_id LIMIT 1`, + ); + if (open !== undefined) return open.actionId; + // A closed request (rejected, expired) gets a fresh one; a double tap lands on one row. + const [count] = yield* run( + "KinPromotion.raiseCount", + sql<{ n: number }>`SELECT COUNT(*) AS n FROM kin_pending_actions WHERE ${sameTarget} + ORDER BY n`, + ); + const owner = yield* ownerChat(input); + const target = { + _tag: "level" as const, + agentId: input.agentId, + ...(input.chatId === undefined ? {} : { chatId: input.chatId }), + level: input.level, + }; + const created = yield* pending.create({ + orgId: input.orgId, + kind: "set_level", + target, + resolved: { _tag: "none" }, + targetDigest: kinTargetDigest("set_level", target, { _tag: "none" }), + reason: `Raise ${owner?.name ?? "the lead"} to ${input.level}${input.chatId === undefined ? "" : " in this chat"}, from the owner's promotion card.`, + requestedBy: { + agentId: KinAgentId.make(KIN_PROMOTION_REQUESTER), + threadId: ThreadId.make(KIN_PROMOTION_REQUESTER), + }, + provenance: { + startedBy: { humanId: person.personId }, + startedByRole: "owner", + chain: [], + ceilingBelowOwner: false, + }, + source: KinEventId.make( + `promotion:${input.agentId}:${chatKey || "lead"}:${input.level}:${count?.n ?? 0}`, + ), + }); + return created.action.id; + }), + ); + if (input.chatId === undefined) { + const card = yield* readPromotion( + input.orgId, + promotionWidgetId(input.agentId, input.level), + ); + const { promotion } = yield* stats(input); + if (card !== undefined) + yield* putPromotion(input, { + ...card, + stats: promotion, + status: "awaiting_approval", + actionId, + deferredUntil: null, + }); + } + return { actionId }; + }, Effect.catch(toChatError)), + + deferPromotion: Effect.fn("KinPromotion.deferPromotion")(function* (people, input) { + yield* asOwner(people, input); + const { promotion } = yield* stats(input); + const card = + promotion.to === null + ? undefined + : yield* readPromotion(input.orgId, promotionWidgetId(input.agentId, promotion.to)); + if (card === undefined || card.status !== "ready") + return yield* refused("invalid_state", "There is no promotion card to put off."); + const now = yield* Clock.currentTimeMillis; + yield* putPromotion(input, { + ...card, + stats: promotion, + status: "deferred", + deferredUntil: iso(now + 7 * DAY_MS), + }); + return yield* view(input); + }, Effect.catch(toChatError)), + + shadowMemory: Effect.fn("KinPromotion.shadowMemory")(function* (people, input) { + yield* asOwner(people, input); + const { promotion } = yield* stats(input); + // At L0 the lead still reads and writes its shadow branch. + if (promotion.from === "L0") + return yield* refused( + "invalid_state", + "The lead is still at L0; its shadow memory is in use.", + ); + if (settle === undefined) + return yield* refused("unavailable", "Kin memory isn't running on this host."); + const card = yield* readPromotion(input.orgId, promotionWidgetId(input.agentId, "L1")); + const pendingCard = card?.shadowMemory === "pending" ? card : undefined; + const notKept = (message: string) => + refused("invalid_state", `Shadow memory wasn't kept: ${message}`); + const relist = Effect.gen(function* () { + if (pendingCard === undefined) return; + const listed = yield* listShadow(input); + yield* putPromotion(input, { ...pendingCard, shadowChanges: listed }); + }).pipe(bestEffort("shadow memory list")); + let choice: Parameters[2] = { _tag: "discard" }; + if (input.choice === "keep") { + // The owner's tap is the review, so Keep commits only a list the card showed in full. + const shown = pendingCard?.shadowChanges ?? null; + if (shown === null) { + yield* relist; + return yield* notKept( + "check the changed paths on the promotion card, then choose again.", + ); + } + if (shown.ownerReviewed.length > 0) + return yield* notKept( + `it changes paths you review in a pull request (${shown.ownerReviewed.slice(0, 5).join(", ")}). Start clean instead.`, + ); + if (shown.truncated) + return yield* notKept( + "it changes more paths than the card can list. Start clean instead.", + ); + choice = { _tag: "keep", paths: shown.paths }; + } + yield* settle(input.orgId, input.agentId, choice).pipe( + Effect.catch((error) => + error._tag === "MemorySyncConflict" + ? relist.pipe(Effect.andThen(Effect.fail(notKept(`${error.reason ?? "it changed"}.`)))) + : Effect.fail( + error._tag === "MemorySecretBlocked" + ? notKept("it contains what looks like a secret. Start clean instead.") + : unavailable, + ), + ), + ); + if (pendingCard !== undefined) + yield* putPromotion(input, { + ...pendingCard, + shadowMemory: input.choice === "keep" ? "kept" : "discarded", + }); + return yield* view(input); + }, Effect.catch(toChatError)), + + evening: Effect.fn("KinPromotion.evening")(function* (lead) { + yield* drawBacklog(lead).pipe(bestEffort("review backlog")); + yield* drawReview(lead, yield* Clock.currentTimeMillis, true).pipe( + bestEffort("evening review card"), + ); + yield* refresh(lead).pipe(bestEffort("promotion card refresh")); + }), + + attachShadowMemory: Effect.fn("KinPromotion.attachShadowMemory")(function* (next) { + yield* Effect.acquireRelease( + Effect.sync(() => { + settle = next; + }), + () => + Effect.sync(() => { + if (settle === next) settle = undefined; + }), + ); + }), + }); + return { promotion, cards: KinLevels.KinPromotionCards.of({ refresh: refreshCards }) }; +}); + +export const layer = Layer.effectContext( + make.pipe( + Effect.map(({ promotion, cards }) => + Context.make(KinPromotion, promotion).pipe(Context.add(KinLevels.KinPromotionCards, cards)), + ), + ), +).pipe(Layer.provide(MemoryCache.layer)); diff --git a/apps/server/src/kin/levels/rpcHandlers.ts b/apps/server/src/kin/levels/rpcHandlers.ts new file mode 100644 index 0000000000000..26657b406f61c --- /dev/null +++ b/apps/server/src/kin/levels/rpcHandlers.ts @@ -0,0 +1,50 @@ +import { KinChatError, KinLevelRpcs } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as RpcGroup from "effect/rpc/RpcGroup"; + +import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; +import { KinIdentity, type PersonIdentity } from "../chat/KinIdentity.ts"; +import { KinServer } from "../KinServer.ts"; +import { KinPromotion } from "./Promotion.ts"; + +const group = RpcGroup.make(...KinLevelRpcs); +const disabled = new KinChatError({ + reason: "disabled", + message: "Kin is not running on this host.", +}); +const defect = (cause: unknown) => + Effect.logWarning("Kin RPC defect.", cause).pipe( + Effect.andThen( + Effect.fail(new KinChatError({ reason: "unavailable", message: "Kin is unavailable." })), + ), + ); + +/** Thin transport: resolve the session's people, then one `KinPromotion` call (owner-checked). */ +export const makeKinLevelHandlers = Effect.fn("makeKinLevelHandlers")(function* ( + session: AuthenticatedSession, +) { + const kin = yield* Effect.serviceOption(KinServer); + const call = Effect.fn("KinLevels.rpc")(function* ( + method: ( + promotion: KinPromotion["Service"], + people: ReadonlyArray, + ) => Effect.Effect, + ) { + if (Option.isNone(kin) || Option.isNone(kin.value.services)) return yield* disabled; + const services = kin.value.services.value; + const people = yield* Context.get(services, KinIdentity).resolve(session); + return yield* method(Context.get(services, KinPromotion), people); + }, Effect.catchDefect(defect)); + return group.of({ + "kin.levels.get": (input) => call((promotion, people) => promotion.view(people, input)), + "kin.levels.review": (input) => call((promotion, people) => promotion.review(people, input)), + "kin.levels.lower": (input) => call((promotion, people) => promotion.lower(people, input)), + "kin.levels.raise": (input) => call((promotion, people) => promotion.raise(people, input)), + "kin.levels.deferPromotion": (input) => + call((promotion, people) => promotion.deferPromotion(people, input)), + "kin.levels.shadowMemory": (input) => + call((promotion, people) => promotion.shadowMemory(people, input)), + }); +}); diff --git a/apps/server/src/kin/mcp/KinChatToolkit.test.ts b/apps/server/src/kin/mcp/KinChatToolkit.test.ts index 19496a1258b72..e21c98659268b 100644 --- a/apps/server/src/kin/mcp/KinChatToolkit.test.ts +++ b/apps/server/src/kin/mcp/KinChatToolkit.test.ts @@ -437,9 +437,9 @@ it.effect("at L0 kin_chat_post posts nothing, records a shadow entry and updates entry.preview, ]), [ - ["group-1", "Rate limiting moves to Friday."], + ["group-1", "Rate limiting moves to Friday.\nIntent: decision"], ["project-1", "code: Forged"], - ["other-direct", "Done."], + ["other-direct", "Done.\nIntent: answer"], ], ); assert.isFalse(state.entries.some((entry: object) => "ceilingBelowOwner" in entry)); diff --git a/apps/server/src/kin/memory/MemoryWriter.test.ts b/apps/server/src/kin/memory/MemoryWriter.test.ts index 1f8cbe80e1224..0b72fe0cd22da 100644 --- a/apps/server/src/kin/memory/MemoryWriter.test.ts +++ b/apps/server/src/kin/memory/MemoryWriter.test.ts @@ -52,6 +52,9 @@ it.live.each([ "P7-crash", "P8-lost-writer", "P9-shadow", + "shadow-merge", + "shadow-discard", + "shadow-owner-path", "P10-lost-git-dir", "sha256", "owner-keep", @@ -522,6 +525,100 @@ it.live.each([ }); return; } + if (scenario.startsWith("shadow-")) { + const remoteHead = (branch: string) => + git(root, [`--git-dir=${remote}`, "rev-parse", `refs/heads/${branch}`]); + for (const bad of ["x/../../main", "a b"]) { + const refused = yield* writer + .settleShadow(orgId, KinAgentId.make(bad), { _tag: "discard" }) + .pipe(Effect.flip); + expect(refused).toMatchObject({ + _tag: "MemoryWriteRejected", + reason: "Invalid agent id", + }); + } + yield* writer.stage(orgId, "wake1", { + path: "deferrals/def-001.md", + content: fixtureItem(), + sourceEventId: "owner", + }); + if (scenario === "shadow-owner-path") + yield* writer.stage(orgId, "wake1", { + path: "decisions/dec-001.md", + content: fixtureItem({ id: "dec-001", kind: "decision" }), + sourceEventId: "owner", + }); + const shadowed = yield* writer.commitWakeup(orgId, "wake1", "completed"); + const main = yield* remoteHead("main"); + expect(yield* remoteHead(`kin/shadow/${agentId}`)).toBe(shadowed.commit); + const { paths } = yield* writer.settleShadow(orgId, agentId, { _tag: "preview" }); + // Previewing writes nothing. + expect(yield* remoteHead("main")).toBe(main); + expect(yield* remoteHead(`kin/shadow/${agentId}`)).toBe(shadowed.commit); + if (scenario === "shadow-owner-path") { + expect(paths).toContain("decisions/dec-001.md"); + const refused = yield* writer + .settleShadow(orgId, agentId, { _tag: "keep", paths }) + .pipe(Effect.flip); + expect(refused._tag).toBe("MemorySyncConflict"); + expect(refused._tag === "MemorySyncConflict" && refused.reason).toContain( + "decisions/dec-001.md", + ); + expect(yield* remoteHead("main")).toBe(main); + expect(yield* remoteHead(`kin/shadow/${agentId}`)).toBe(shadowed.commit); + // Start clean stays available. + yield* writer.settleShadow(orgId, agentId, { _tag: "discard" }); + expect(yield* remoteHead(`kin/shadow/${agentId}`)).toBe(main); + return; + } + expect(paths).toHaveLength(2); + const keep = scenario === "shadow-merge"; + if (keep) { + // Keep commits only the list the owner was shown. + const stale = yield* writer + .settleShadow(orgId, agentId, { _tag: "keep", paths: paths.slice(1) }) + .pipe(Effect.flip); + expect(stale._tag).toBe("MemorySyncConflict"); + expect(yield* remoteHead("main")).toBe(main); + } + expect( + yield* writer.settleShadow( + orgId, + agentId, + keep ? { _tag: "keep", paths } : { _tag: "discard" }, + ), + ).toEqual({ kept: keep ? 2 : 0, paths: keep ? paths : [] }); + const settled = yield* remoteHead("main"); + expect(settled === main).toBe(!keep); + // Either way the next L0 trial starts from main, not the old shadow week. + expect(yield* remoteHead(`kin/shadow/${agentId}`)).toBe(settled); + const files = yield* git(root, [ + `--git-dir=${remote}`, + "ls-tree", + "-r", + "--name-only", + settled, + ]); + expect(files.includes("deferrals/def-001.md")).toBe(keep); + if (keep) { + expect( + yield* git(root, [`--git-dir=${remote}`, "log", "-1", "--format=%B", settled]), + ).toContain(`Kin-Shadow: ${shadowed.commit}`); + expect(yield* git(root, [`--git-dir=${remote}`, "show", `${settled}:rules.md`])).toBe( + "Invented rules", + ); + } + // Settling again changes nothing. + expect( + yield* writer.settleShadow( + orgId, + agentId, + keep ? { _tag: "keep", paths: [] } : { _tag: "discard" }, + ), + ).toEqual({ kept: 0, paths: [] }); + expect(yield* remoteHead("main")).toBe(settled); + return; + } if (scenario === "P8-lost-writer" || scenario === "P9-shadow") { if (scenario === "P9-shadow") yield* writer.commitWakeup(orgId, "wake0", "completed"); yield* fs.remove(paths.writer, { recursive: true }); diff --git a/apps/server/src/kin/memory/MemoryWriter.ts b/apps/server/src/kin/memory/MemoryWriter.ts index adcf9b665d7f5..67e13052bce4f 100644 --- a/apps/server/src/kin/memory/MemoryWriter.ts +++ b/apps/server/src/kin/memory/MemoryWriter.ts @@ -30,7 +30,8 @@ import { } from "./Memory.ts"; import { parseFrontMatter, MemoryItemError } from "./frontMatter.ts"; import { journalEntry, MemoryJournalError, type JournalContext } from "./journal.ts"; -import { kinShapeFailure } from "./lint.ts"; +import { mergeMemoryFiles } from "./merge.ts"; +import { isOwnerReviewedPath, kinShapeFailure } from "./lint.ts"; import { KinSecretScan, KinSecretScanError } from "./secretScan.ts"; export const LEAD_ENDED_WITHOUT_KIN_END = "Lead ended without calling kin_end."; @@ -69,6 +70,12 @@ export class MemoryWriterAuthority extends Context.Service< ) => Effect.Effect; } >()("t3/kin/memory/MemoryWriter/MemoryWriterAuthority") {} +export type ShadowChoice = + | { readonly _tag: "preview" } + | { readonly _tag: "discard" } + /** `paths` is the list the owner was shown; Keep refuses when the changes differ from it. */ + | { readonly _tag: "keep"; readonly paths: ReadonlyArray }; + export class MemoryWriteRejected extends Schema.TaggedError()( "MemoryWriteRejected", { @@ -162,6 +169,16 @@ export class MemoryWriter extends Context.Service< }, ) => Effect.Effect<{ commit: string }, Failure>; readonly deleteDreamBranch: (orgId: KinOrgId, branch: string) => Effect.Effect; + /** + * The owner's choice once a lead leaves L0: `keep` commits the shadow branch's changes onto + * the default branch; either way `kin/shadow/` then restarts from the default branch. + * `preview` only lists the changed paths. + */ + readonly settleShadow: ( + orgId: KinOrgId, + agentId: KinAgentId, + choice: ShadowChoice, + ) => Effect.Effect<{ readonly kept: number; readonly paths: ReadonlyArray }, Failure>; } >()("t3/kin/memory/MemoryWriter") {} const dreamBranch = /^dream\/\d{4}-\d{2}-\d{2}$/; @@ -1013,6 +1030,126 @@ const make = Effect.gen(function* () { }), ), ), + settleShadow: Effect.fn("MemoryWriter.settleShadow")((orgId, agentId, choice) => + locked( + orgId, + Effect.gen(function* () { + if (!/^[a-zA-Z0-9_-]+$/.test(agentId)) + return yield* new MemoryWriteRejected({ reason: "Invalid agent id" }); + const { writer } = yield* validate(orgId); + yield* refuseDuringPurge(orgId); + const repo = yield* repoFor(orgId); + const main = config.defaultBranch ?? "main"; + const shadow = `kin/shadow/${agentId}`; + const mainHead = yield* branchHead(orgId, writer, main); + const shadowHead = yield* branchHead(orgId, writer, shadow); + const conflict = (reason: string) => + new MemorySyncConflict({ orgId, operation: "push", reason }); + const shadowChanges = Effect.gen(function* () { + const mainFiles = yield* filesAt(orgId, writer, mainHead); + if (shadowHead === mainHead) return { mainFiles, changes: new Map() }; + const base = yield* git(orgId, writer, ["merge-base", mainHead, shadowHead]).pipe( + Effect.mapError(() => conflict("The shadow branch shares no history with main")), + ); + const entries = (commit: string) => + readTree(orgId, writer, commit).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(VcsProcess, vcs), + Effect.map((all) => new Map(all.map((entry) => [entry.relative, entry]))), + ); + const merged = mergeMemoryFiles( + yield* filesAt(orgId, writer, base), + yield* filesAt(orgId, writer, shadowHead), + mainFiles, + yield* entries(base), + yield* entries(shadowHead), + yield* entries(mainHead), + ); + if (merged === undefined) + return yield* conflict("Shadow memory conflicts with the default branch"); + // The writer never deletes, so a deletion means the shadow branch was edited by hand. + if ([...mainFiles.keys()].some((file) => !merged.files.has(file))) + return yield* conflict("Shadow memory deletes files on the default branch"); + const changes = new Map( + [...merged.files].filter( + ([file, bytes]) => file !== "INDEX.md" && !mainFiles.get(file)?.equals(bytes), + ), + ); + return { mainFiles, changes }; + }); + if (choice._tag === "preview") + return { kept: 0, paths: [...(yield* shadowChanges).changes.keys()].toSorted() }; + let head = mainHead; + let kept = 0; + let paths: ReadonlyArray = []; + if (choice._tag === "keep") { + const { mainFiles, changes } = yield* shadowChanges; + paths = [...changes.keys()].toSorted(); + const shown = choice.paths.toSorted(); + if (shown.length !== paths.length || paths.some((path, i) => path !== shown[i])) + return yield* conflict("Shadow memory changed since its paths were listed"); + // Outside Kin's own folders the owner reviews every change in a PR (TRIG-15). + const reviewed = paths.filter(isOwnerReviewedPath); + if (reviewed.length > 0) + return yield* conflict( + `It changes paths you review in a pull request (${reviewed.slice(0, 5).join(", ")}${reviewed.length > 5 ? ", …" : ""}); start clean instead`, + ); + if (changes.size > 0) { + kept = changes.size; + const regular = yield* regularPaths(orgId, writer, mainHead); + const combined = new Map( + [...mainFiles, ...changes] + .filter(([path]) => regular.has(path) || changes.has(path)) + .map(([path, bytes]) => [path, bytes.toString("utf8")]), + ); + changes.set("INDEX.md", Buffer.from(yield* indexFor(orgId, combined))); + const findings = yield* scanner.scan({ + orgId, + files: [...changes].map(([path, content]) => ({ path, content })), + }); + if (findings.length) return yield* new MemorySecretBlocked({ orgId, findings }); + const commit = yield* writeCommit( + orgId, + writer, + mainHead, + mainFiles, + changes, + `kin(${agentId}): keep shadow memory\n\nKin-Shadow: ${shadowHead}\n`, + ); + yield* git(orgId, writer, ["update-ref", `refs/heads/${main}`, commit, mainHead]); + yield* memory.record(orgId, main, mainHead, commit); + yield* git(orgId, writer, [ + "push", + "--", + repo.repoUrl, + `${commit}:refs/heads/${main}`, + ]).pipe(Effect.mapError(() => conflict("Push rejected; retry or reconcile remote"))); + yield* memory.rebuildCache(orgId).pipe( + Effect.catch((error) => + Effect.logWarning("Could not refresh memory cache after commit", { + orgId, + errorTag: error._tag, + }), + ), + ); + head = commit; + } + } + // A later trial at L0 starts from what the lead reads at L1, not the old shadow week. + if (shadowHead !== head) { + yield* git(orgId, writer, ["update-ref", `refs/heads/${shadow}`, head, shadowHead]); + yield* memory.record(orgId, shadow, shadowHead, head); + yield* git(orgId, writer, [ + "push", + "--", + repo.repoUrl, + `+${head}:refs/heads/${shadow}`, + ]).pipe(Effect.mapError(() => conflict("Shadow branch push rejected"))); + } + return { kept, paths }; + }), + ), + ), }); }); export const layer = Layer.effect(MemoryWriter, make).pipe(Layer.provide(MemoryCache.layer)); diff --git a/apps/server/src/kin/memory/lint.ts b/apps/server/src/kin/memory/lint.ts index 599806d7af164..2ddf04789da52 100644 --- a/apps/server/src/kin/memory/lint.ts +++ b/apps/server/src/kin/memory/lint.ts @@ -26,6 +26,9 @@ const codeowners = ".github/CODEOWNERS"; const kinOnlyPaths = ["/commitments/", "/deferrals/", "/claims/", "/journal/", "/INDEX.md"]; const kinOnlyRoots = kinOnlyPaths.map((pattern) => pattern.slice(1).replace(/\/$/, "")); const regularModes = ["100644", "100755"]; +/** CODEOWNERS denies by default: every path outside Kin's own folders waits for owner review. */ +export const isOwnerReviewedPath = (path: string) => + !kinOnlyRoots.includes(path.split("/")[0] ?? ""); export const isLintedPath = (path: string) => path === "rules.md" || diff --git a/apps/server/src/kin/rpcHandlers.ts b/apps/server/src/kin/rpcHandlers.ts index ef8b85462ab8c..aef9b741213f5 100644 --- a/apps/server/src/kin/rpcHandlers.ts +++ b/apps/server/src/kin/rpcHandlers.ts @@ -5,6 +5,7 @@ import * as RpcGroup from "effect/rpc/RpcGroup"; import type { AuthenticatedSession } from "../auth/EnvironmentAuth.ts"; import { makeKinApprovalHandlers } from "./approvals/rpcHandlers.ts"; import { makeKinChatHandlers } from "./chat/rpcHandlers.ts"; +import { makeKinLevelHandlers } from "./levels/rpcHandlers.ts"; import { KinServer } from "./KinServer.ts"; import { makeKinPushHandlers } from "./push/rpcHandlers.ts"; import { makeKinWebhookHandlers } from "./triggers/webhookRpcHandlers.ts"; @@ -21,6 +22,7 @@ export const makeKinHandlers = Effect.fn("makeKinHandlers")(function* ( session, Option.flatMap(kin, (kin) => kin.services), )), + ...(yield* makeKinLevelHandlers(session)), ...(yield* makeKinPushHandlers(session)), ...(yield* makeKinWebhookHandlers(session)), }); diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index d3ae88eb40d67..29063f36ea8fa 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -349,7 +349,7 @@ export const KinProvenance = Schema.Struct({ - The lead spec computes it from the `KinEvent` and passes it down to workers; the ceiling is the lowest role in the chain. Webhook content (PR bodies, comments) counts as `none`. - **Work** runs only if the ceiling and the chat's level allow it (`ceilingAllows`). - **Privileged** is proposed under any ceiling but runs only with the owner's grant, which is the owner's own authority for that one action. `request_action` stores `ceilingBelowOwner` from the whole batch, not the cited event: the lead can cite the owner's message while a PR comment in the same batch drove the request. When it is set, the card warns above the buttons that the request didn't come from the owner alone. `afterNonOwnerMessage` only supplies the name ("Asked for after Priya's message"); without one the card names the source kind, such as a GitHub event. -- A lead can never request `set_level`, whoever drove the wake-up: `request_action` refuses it (`unsupported_kind`) before provenance is read. Level changes reach the owner only as LEAD-12's promotion card, which the server raises from the review stats. +- A lead can never request `set_level`, whoever drove the wake-up: `request_action` refuses it (`unsupported_kind`) before provenance is read. Level raises reach the owner only through `kin.levels.raise` (LEAD-12's promotion card or settings), which creates the action under the reserved requester `kin-promotion`; `KinPendingActions.create` refuses `set_level` from any other requester. - `change_rules`, `register_approver_key`, and (later) `set_delegation` and `set_next_of_kin` are refused at `request_action` (`not_owner`) unless every event in the wake-up's chain is the owner's, which implies `startedByRole == "owner"`. The lead picks `sourceEventId`, so checking only the cited event would let it cite an owner's message while acting on a member's in the same batch. A member can't even get those cards in front of the owner. - Roles come from stored rows, never event text: a chat message's stored `author_role` (human, posted), or for other human events the actor's current chat membership. Only the lead's own owner counts as `owner`; another human holding an owner row counts as `member`. Agent, system, schedule and webhook events count as `none`. `afterNonOwnerMessage` names the first non-owner human message in the batch. diff --git a/docs/kin/specs/lead.md b/docs/kin/specs/lead.md index d17ba5a5784ca..cd1ef77b3613b 100644 --- a/docs/kin/specs/lead.md +++ b/docs/kin/specs/lead.md @@ -470,17 +470,18 @@ L0 talks only to its owner: a `kin_chat_post` to the lead's direct chat with its Per-chat levels live in `kin_chat_levels (org_id, agent_id, chat_id)` (K022), the `set_level` target's `chatId`; no row means the lead's own level. `request_action` checks the level after the provenance gate, so `not_owner` and the ban on leads requesting `set_level` refuse at every level and record nothing. Below a kind's level (L3 for every privileged kind) it records the entry, with the server-computed provenance, before GitHub is read, and rechecks inside the write. Until APPR-13 classifies risk, an L3 merge request goes to the owner like any other. -Memory at L0 goes to the shadow branch so the lead can keep track of its own deferrals during the shadow week while the default branch stays clean. Reads at L0 use the shadow branch. On promotion the owner picks "Keep shadow memory" (the writer merges the branch through a PR on the memory repo) or "Start clean". +Memory at L0 goes to the shadow branch so the lead can keep track of its own deferrals during the shadow week while the default branch stays clean. Reads at L0 use the shadow branch. After a raise from L0 the owner picks "Keep shadow memory" or "Start clean" (below); until then the shadow branch is left as it is, and the lead at L1 reads only the default branch. ### Level promotion (gap 6) -1. Every evening during a level's trial, the evening routine includes a review card for the day's shadow entries: each shows what would have been posted or done, with buttons Fine as is, I'd change it, Wrong, Harmful. A verdict is a `widget.action` from the owner, recorded on the entry. -2. A lead is eligible to move from level N to N+1 when all of these hold: at least 7 days at level N; at least 20 entries reviewed with `unlocks_level = N+1`, counted per `(org_id, agent_id, unlocks_level, verdict)`; at least 80% Fine as is; no Harmful. -3. When eligible, the owner's direct chat gets one card: "tech-lead is ready for L1: 34 of 39 would have gone out unchanged, none harmful." [Raise to L1] [Another week]. -4. Raising a level is a permission change, so it is a privileged action. The card button creates a `KinPendingAction { kind: "kin.level.set" }` through the approvals spec, and the change applies only with the owner's signed grant. The lead cannot request it. -5. Lowering a level needs no signature and applies at once (owner, settings or chat). A Harmful verdict on a live action at L1+ lowers the lead one level automatically and tells the owner why. +1. Every evening during a level's trial (any level below L3), the server posts a native `shadow_review` card (`KinShadowReviewCard`) in the owner's direct chat for that owner-local day's shadow entries, unreviewed first, each showing what would have been posted or done, with Fine as is, I'd change it, Wrong, Harmful. The card shows the whole action (a post's body, intent, mentions and reply; a delegation's title, project, base, model, review target, goal, brief, memory items and quotes; a follow-up's brief and quotes; a request's target and reason) as plain text with direction overrides and invisible characters spelled out, up to 2,000 characters, marked truncated beyond that or when a field can't be shown; a truncated entry can't be marked Fine. It counts the day's unreviewed entries, so none hide past its 50-entry list; reviewing what it shows brings the rest of the backlog onto it. Every evening, and whenever the owner reads their levels or the promotion card is redrawn, each earlier trial day that still has unreviewed entries gets or redraws its card, so a day with no evening run or an entry made after that day's card is never out of reach. A verdict is the owner's `kin.levels.review` call, recorded on the entry; the owner can change it. The lead never draws or taps these cards, and `kin.widgets.act` refuses them, so a verdict never passes through a wake-up. +2. A lead is eligible to move from level N to N+1 when all of these hold: at least 7 days at level N (since `level_since`); at least 20 reviewed entries with `unlocks_level = N+1` recorded since `level_since`, counted per `(org_id, agent_id, unlocks_level, verdict)`; at least 80% of them Fine as is; none Harmful; and no entry with `unlocks_level = N+1` recorded since `level_since` left unreviewed. +3. When eligible, the owner's direct chat gets one `promotion` card (`KinPromotionCard`, one per lead and target level): "tech-lead is ready for L1: 34 of 39 reviewed would have gone out unchanged, none harmful, none unreviewed." [Raise to L1] [Another week]. Another week (`kin.levels.deferPromotion`) puts the card off for 7 days; Raise still works from settings meanwhile. A Harmful verdict, a new unreviewed entry or a lower level closes the card, and it reopens once the lead is eligible again; meanwhile its title carries the trial's counts, unreviewed included. +4. Raising a level is a permission change, so it is a privileged action. `kin.levels.raise` (the card button, or settings) creates a `KinPendingAction { kind: "set_level" }` with the reserved requester `kin-promotion`; `KinPendingActions.create` refuses `set_level` from any other requester, and `request_action` refuses it outright, so the lead cannot request it. The change applies only when the executor claims the action under the owner's signed grant: the `set_level` handler (`approvals/handlers/setLevel.ts`) calls `KinLevels.raiseByGrant`, whose write itself requires that claimed execution and the consumed grant of the lead's own owner. A lead goes up one level at a time and must still be eligible; a chat's cap goes back up to at most the lead's level (at the lead's level its row is deleted, so the chat follows the lead again). Until APPR-9 registers the handler, an approved raise lapses unapplied. +5. Lowering a level needs no signature and applies at once (`kin.levels.lower`, owner only, from settings or chat), for the lead or one chat. Lowering withdraws the open `set_level` raises it overtook: unapproved ones are cancelled and approved ones voided, for the lead and every chat above a new lead level, or for that chat above a new chat cap. An executing raise is refused by its handler, which rechecks the level. A Harmful verdict on an entry the lead recorded at L1 or above lowers the lead one level automatically and tells the owner why in their direct chat. Live actions have no review card yet; until one exists, the shadow entries a lead records at L1 and above stand in for them. +6. After a raise from L0 the promotion card offers Keep shadow memory or Start clean (`kin.levels.shadowMemory`, owner only, refused at L0). The card first lists the paths Keep would commit. Keep commits exactly that list onto the default branch as one commit through the memory writer, refusing conflicts, deletions, secrets, a list that no longer matches the shadow branch, and any path outside Kin's own folders (`commitments/`, `deferrals/`, `claims/`, `journal/`), since TRIG-15's CODEOWNERS reserves every other path, `decisions/`, `people/`, `objectives/` and `rules.md` included, for the owner's review in a PR. There is no memory-repo PR client yet, so for those only Start clean is available; for Kin's own folders the owner's tap is the review. Either way `kin/shadow/` then restarts from the default branch, so a later trial at L0 doesn't resume the old shadow week. -Thresholds live in code (`KinLevels.promotionRule`) and are shown on the card. +`kin.levels.get` (owner only) shows the lead's level, each chat's cap, the trial's counts and any open `set_level` raise. Thresholds live in code (`KinLevels.promotionRule`) and are shown on the cards. Scopes: `get` needs `orchestration:read`, `review` and `deferPromotion` `orchestration:operate`, and `lower`, `raise` and `shadowMemory` `settings:write`; every method then checks that the caller owns the lead. ### Budget (gap 2) @@ -594,7 +595,7 @@ Upstream files touched, one line each: | This spec needs | From | | ------------------------------------------------------------------------------------------------------------------------ | --------- | | `KinChatService.postAgentMessage`, `KinChat.level`, owner direct chat id, widget update in place, `widget.action` events | chat | -| `request_action`, `KinPendingAction`, `kin.level.set` grant | approvals | +| `request_action`, `KinPendingAction`, `set_level` grant | approvals | | `MemorySecretScan.check`, `KinRoutines.pauseAll`, routine and deferral fires routed into `enqueue` | triggers | | Pause switch UI and lock screen action | mobile | @@ -623,6 +624,7 @@ Upstream files touched, one line each: - Reviewer model: `kin_delegate` with `kind: "review"` and the author's model is rejected. - Levels: at L0, `kin_chat_post` to a group returns `shadowed: true`, posts nothing, and adds a shadow entry; the owner's summary widget updates. The same post to the owner's direct chat is delivered, and a second unsolicited one is refused as at L1. - Promotion: with 20 reviewed entries, 16 Fine and 0 Harmful after 7 days, the eligibility card appears; with one Harmful it does not. +- Raising: `kin.levels.raise` leaves the level unchanged until the executor claims the owner-granted `set_level` action; `raiseByGrant` without that claim is refused. A member or a read-only session gets a permission error from every level method that changes something, and no Kin MCP tool reaches the level writers. - Stop: `kin.org.pause` interrupts a running lead and worker within 5 s; new events stay queued; `resume` produces one `resume` wake-up; a member calling `kin.org.pause` gets a permission error. - Budget: with 15% left, a P3 event is deferred and a P0 event runs. - Restart: killing the server mid wake-up and restarting finishes the wake-up once, with no duplicate commit. @@ -653,7 +655,7 @@ LEAD-10. **Budget.** Units from turn usage, daily reset in the owner's timezone, LEAD-11. **Stop switch.** `KinStop`, RPC methods with owner-only authorization, interrupt fan-out, resume event, expiry of old events. Depends on: LEAD-5, LEAD-9, CHAT-6. Done when: the stop tests pass. Owner: backend. -LEAD-12. **Promotion.** Review card in the evening summary, verdicts, the eligibility rule, the `kin.level.set` pending action, automatic demotion, shadow-branch keep or discard. Depends on: LEAD-8, APPR-4. Done when: the promotion tests pass. Owner: backend (card layout: UI, with the mobile spec). +LEAD-12. **Promotion.** Review card in the evening summary, verdicts, the eligibility rule, the `set_level` pending action, automatic demotion, shadow-branch keep or discard. Depends on: LEAD-8, APPR-4. Done when: the promotion tests pass. Owner: backend (card layout: UI, with the mobile spec). LEAD-13. **Routine content.** Morning and evening templates, data gathering (cache, open PRs, CI state, workers, budget), and an end-to-end test that a `routine` event yields one message of at most 12 lines with its widgets. Depends on: LEAD-6, LEAD-8, LEAD-10. Done when: that test passes against fixture memory. Owner: backend. diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index c456eef69bfe5..63403a0ce59a0 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -17,6 +17,7 @@ import { AuthSourceControlWriteScope, ThreadId, EnvironmentId, + KIN_LEVEL_WS_METHODS, KIN_PUSH_WS_METHODS, ORCHESTRATION_V2_WS_METHODS, ScheduledTaskId, @@ -123,6 +124,42 @@ describe("command permissions", () => { }), ), ); + it.effect.each([ + [KIN_LEVEL_WS_METHODS.get, AuthOrchestrationReadScope], + [KIN_LEVEL_WS_METHODS.review, AuthOrchestrationOperateScope], + [KIN_LEVEL_WS_METHODS.deferPromotion, AuthOrchestrationOperateScope], + [KIN_LEVEL_WS_METHODS.lower, AuthSettingsWriteScope], + [KIN_LEVEL_WS_METHODS.raise, AuthSettingsWriteScope], + [KIN_LEVEL_WS_METHODS.shadowMemory, AuthSettingsWriteScope], + ] as const)("guards %s with the destination %s grant", ([method, scope]) => + Effect.scoped( + Effect.gen(function* () { + const registry = yield* setup; + const command = createEnvironmentRpcCommand(runtime, { + label: method, + tag: method, + execute: () => Effect.die("unused"), + }); + const others = [ + AuthOrchestrationReadScope, + AuthOrchestrationOperateScope, + AuthSettingsWriteScope, + ].filter((other) => other !== scope); + registry.set( + sessions(env), + AsyncResult.success({ ...grant(false), scopes: others, permissions: others }), + ); + expect(registry.get(command.permissionAtom(env))).toBe(false); + registry.set( + sessions(env), + AsyncResult.success({ ...grant(false), scopes: [scope], permissions: [scope] }), + ); + expect(registry.get(command.permissionAtom(env))).toBe(true); + registry.set(sessions(other), AsyncResult.success(grant(false))); + expect(registry.get(command.permissionAtom(other))).toBe(false); + }), + ), + ); it.effect("guards the Kin stop switch with the destination operate grant", () => Effect.scoped( Effect.gen(function* () { diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 18a37f7c366ef..d8e3791a25d35 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -77,6 +77,7 @@ export * from "./kinChat.ts"; export * from "./kinLead.ts"; export * from "./kinTriggers.ts"; export * from "./kinApprovals.ts"; +export * from "./kinLevels.ts"; export * from "./kinPush.ts"; export * from "./kinRpcs.ts"; diff --git a/packages/contracts/src/kinLevels.ts b/packages/contracts/src/kinLevels.ts new file mode 100644 index 0000000000000..fb36fbc552108 --- /dev/null +++ b/packages/contracts/src/kinLevels.ts @@ -0,0 +1,219 @@ +import * as Rpc from "effect/rpc/Rpc"; +import * as Schema from "effect/Schema"; + +import { + AuthOrchestrationOperateScope, + AuthOrchestrationReadScope, + AuthSettingsWriteScope, + EnvironmentAuthorizationError, +} from "./auth.ts"; +import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { KinActionId } from "./kinApprovals.ts"; +import { KinAgentId, KinChatError, KinChatId, KinOrgId } from "./kinChat.ts"; +import { CanonicalUtcTimestamp, KinLevel } from "./kinLead.ts"; + +/** What the review card shows of one entry's input: the whole action, up to this many chars. */ +export const KIN_SHADOW_REVIEW_TEXT_MAX = 2_000; + +// guestShare.ts NAME_BREAKING_CHARACTER, widened to every format character (zero-width, BOM). +/** What the server spells out as `[U+XXXX]` in card previews; newlines and tabs stay. */ +export const KIN_HIDDEN_CHARACTER = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u; + +export const KinShadowVerdict = Schema.Literals(["fine", "change", "wrong", "harmful"]); +export type KinShadowVerdict = typeof KinShadowVerdict.Type; + +/** `KinLevels.promotionRule`, shown on the cards. */ +export const KinPromotionRule = Schema.Struct({ + minDays: NonNegativeInt, + minReviewed: NonNegativeInt, + minFineShare: Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 1 })), +}); +export type KinPromotionRule = typeof KinPromotionRule.Type; + +/** Review counts for the trial at `from`: entries recorded since the lead reached it. */ +export const KinPromotionStats = Schema.Struct({ + from: KinLevel, + to: Schema.NullOr(KinLevel), + daysAtLevel: NonNegativeInt, + reviewed: NonNegativeInt, + fine: NonNegativeInt, + harmful: NonNegativeInt, + /** Any unreviewed entry in the trial blocks eligibility. */ + unreviewed: NonNegativeInt, + eligible: Schema.Boolean, + rule: KinPromotionRule, +}); +export type KinPromotionStats = typeof KinPromotionStats.Type; + +/** + * Native `shadow_review` card, server-drawn in the evening summary: one owner-local day's shadow + * entries with their verdicts. Taps go to `kin.levels.review`, never `kin.widgets.act`. + */ +export const KinShadowReviewCard = Schema.Struct({ + agentId: KinAgentId, + title: TrimmedNonEmptyString, + day: Schema.String.check(Schema.isPattern(/^\d{4}-\d{2}-\d{2}$/)), + total: NonNegativeInt, + /** That day's unreviewed entries; `entries` lists them first, so none hide past the cap. */ + unreviewed: NonNegativeInt, + entries: Schema.Array( + Schema.Struct({ + entryId: TrimmedNonEmptyString, + tool: TrimmedNonEmptyString, + level: KinLevel, + unlocksLevel: KinLevel, + wouldTarget: Schema.String, + /** + * Lead-written text, hidden characters already spelled out. Clients render it and + * `wouldTarget` as plain text: no markup, links, mentions or bidi isolation tricks. + */ + preview: Schema.String.check(Schema.isMaxLength(KIN_SHADOW_REVIEW_TEXT_MAX)), + /** The preview stops short of the stored input or leaves a field out; Fine is refused. */ + truncated: Schema.Boolean, + createdAt: Schema.toEncoded(CanonicalUtcTimestamp), + verdict: Schema.NullOr(KinShadowVerdict), + }), + ).check(Schema.isMaxLength(50)), + promotion: KinPromotionStats, +}); +export type KinShadowReviewCard = typeof KinShadowReviewCard.Type; + +export const KIN_SHADOW_CHANGES_MAX = 200; + +/** + * Native `promotion` card: " is ready for L1". `ready` offers Raise (`kin.levels.raise`) and + * Another week (`kin.levels.deferPromotion`); `awaiting_approval` opens the signed approval for + * `actionId`; `raised` from L0 offers Keep shadow memory or Start clean (`kin.levels.shadowMemory`). + */ +export const KinPromotionCard = Schema.Struct({ + agentId: KinAgentId, + title: TrimmedNonEmptyString, + stats: KinPromotionStats, + status: Schema.Literals(["ready", "deferred", "awaiting_approval", "raised", "closed"]), + actionId: Schema.NullOr(KinActionId), + deferredUntil: Schema.NullOr(Schema.toEncoded(CanonicalUtcTimestamp)), + shadowMemory: Schema.NullOr(Schema.Literals(["pending", "kept", "discarded"])), + /** + * While `shadowMemory` is pending: the paths Keep would commit to the default branch, and + * those the owner reviews in a PR, which make Keep unavailable. Null when not yet listed. + */ + shadowChanges: Schema.NullOr( + Schema.Struct({ + paths: Schema.Array(Schema.String).check(Schema.isMaxLength(KIN_SHADOW_CHANGES_MAX)), + truncated: Schema.Boolean, + ownerReviewed: Schema.Array(Schema.String).check(Schema.isMaxLength(KIN_SHADOW_CHANGES_MAX)), + }), + ), +}); +export type KinPromotionCard = typeof KinPromotionCard.Type; + +export const KinLevelsView = Schema.Struct({ + orgId: KinOrgId, + agentId: KinAgentId, + level: KinLevel, + levelSince: Schema.toEncoded(CanonicalUtcTimestamp), + chats: Schema.Array( + Schema.Struct({ + chatId: KinChatId, + level: KinLevel, + levelSince: Schema.toEncoded(CanonicalUtcTimestamp), + }), + ), + promotion: KinPromotionStats, + /** Open `set_level` requests for this lead, waiting on the owner's signature or the executor. */ + pendingRaises: Schema.Array( + Schema.Struct({ + actionId: KinActionId, + chatId: Schema.NullOr(KinChatId), + level: KinLevel, + state: Schema.Literals(["awaiting_approval", "approved", "executing"]), + }), + ), +}); +export type KinLevelsView = typeof KinLevelsView.Type; + +const LeadRef = { orgId: KinOrgId, agentId: KinAgentId }; +export const KinLevelsGetInput = Schema.Struct(LeadRef); +export type KinLevelsGetInput = typeof KinLevelsGetInput.Type; +/** Without `chatId` it sets the lead's own level; with one, that chat's cap. */ +export const KinLevelsSetInput = Schema.Struct({ + ...LeadRef, + chatId: Schema.optional(KinChatId), + level: KinLevel, +}); +export type KinLevelsSetInput = typeof KinLevelsSetInput.Type; +export const KinLevelsRaiseResult = Schema.Struct({ actionId: KinActionId }); +export type KinLevelsRaiseResult = typeof KinLevelsRaiseResult.Type; +export const KinLevelsReviewInput = Schema.Struct({ + orgId: KinOrgId, + entryId: TrimmedNonEmptyString, + verdict: KinShadowVerdict, + note: Schema.optional(Schema.String.check(Schema.isMaxLength(500))), +}); +export type KinLevelsReviewInput = typeof KinLevelsReviewInput.Type; +export const KinLevelsReviewResult = Schema.Struct({ + entryId: TrimmedNonEmptyString, + verdict: KinShadowVerdict, + /** Set when this verdict lowered the lead automatically. */ + loweredTo: Schema.NullOr(KinLevel), +}); +export type KinLevelsReviewResult = typeof KinLevelsReviewResult.Type; +export const KinLevelsShadowMemoryInput = Schema.Struct({ + ...LeadRef, + choice: Schema.Literals(["keep", "discard"]), +}); +export type KinLevelsShadowMemoryInput = typeof KinLevelsShadowMemoryInput.Type; + +export const KIN_LEVEL_WS_METHODS = { + get: "kin.levels.get", + review: "kin.levels.review", + lower: "kin.levels.lower", + raise: "kin.levels.raise", + deferPromotion: "kin.levels.deferPromotion", + shadowMemory: "kin.levels.shadowMemory", +} as const; + +const error = Schema.Union([KinChatError, EnvironmentAuthorizationError]); +// Owner of the lead only, on the server; the scopes below gate the client's buttons. +export const KinLevelRpcs = [ + Rpc.make(KIN_LEVEL_WS_METHODS.get, { + payload: KinLevelsGetInput, + success: KinLevelsView, + error, + }), + Rpc.make(KIN_LEVEL_WS_METHODS.review, { + payload: KinLevelsReviewInput, + success: KinLevelsReviewResult, + error, + }), + Rpc.make(KIN_LEVEL_WS_METHODS.lower, { + payload: KinLevelsSetInput, + success: KinLevelsView, + error, + }), + Rpc.make(KIN_LEVEL_WS_METHODS.raise, { + payload: KinLevelsSetInput, + success: KinLevelsRaiseResult, + error, + }), + Rpc.make(KIN_LEVEL_WS_METHODS.deferPromotion, { + payload: KinLevelsGetInput, + success: KinLevelsView, + error, + }), + Rpc.make(KIN_LEVEL_WS_METHODS.shadowMemory, { + payload: KinLevelsShadowMemoryInput, + success: KinLevelsView, + error, + }), +] as const; + +export const KIN_LEVEL_RPC_SCOPES = { + [KIN_LEVEL_WS_METHODS.get]: AuthOrchestrationReadScope, + [KIN_LEVEL_WS_METHODS.review]: AuthOrchestrationOperateScope, + [KIN_LEVEL_WS_METHODS.deferPromotion]: AuthOrchestrationOperateScope, + // Levels are the lead's permissions, set like its budget. + [KIN_LEVEL_WS_METHODS.lower]: AuthSettingsWriteScope, + [KIN_LEVEL_WS_METHODS.raise]: AuthSettingsWriteScope, + [KIN_LEVEL_WS_METHODS.shadowMemory]: AuthSettingsWriteScope, +} as const; diff --git a/packages/contracts/src/kinRpcs.ts b/packages/contracts/src/kinRpcs.ts index bab9b2b6cbd25..a98ea83f8ebb9 100644 --- a/packages/contracts/src/kinRpcs.ts +++ b/packages/contracts/src/kinRpcs.ts @@ -10,6 +10,7 @@ import { KinOrgState, } from "./kinLead.ts"; import { KinApprovalRpcs, KIN_APPROVAL_RPC_SCOPES } from "./kinApprovals.ts"; +import { KinLevelRpcs, KIN_LEVEL_RPC_SCOPES } from "./kinLevels.ts"; import { KinChatError, KinChatRpcs, KIN_CHAT_RPC_SCOPES } from "./kinChat.ts"; import { KinPushRpcs, KIN_PUSH_RPC_SCOPES } from "./kinPush.ts"; import { @@ -66,12 +67,14 @@ export const KinChatAndBudgetRpcs = [...KinChatRpcs, ...KinBudgetRpcs, ...KinOrg export const KinRpcs = [ ...KinChatAndBudgetRpcs, ...KinApprovalRpcs, + ...KinLevelRpcs, ...KinGithubWebhookRpcs, ...KinPushRpcs, ] as const; export const KIN_RPC_SCOPES = { ...KIN_CHAT_RPC_SCOPES, ...KIN_APPROVAL_RPC_SCOPES, + ...KIN_LEVEL_RPC_SCOPES, ...KIN_PUSH_RPC_SCOPES, "kin.budget.get": AuthOrchestrationReadScope, "kin.budget.set": AuthSettingsWriteScope, @@ -111,6 +114,12 @@ export const KIN_RPC_AGGREGATES = { "kin.approvals.revokeKey": "kin-approvals", "kin.audit.list": "kin-approvals", "kin.audit.verify": "kin-approvals", + "kin.levels.get": "kin-levels", + "kin.levels.review": "kin-levels", + "kin.levels.lower": "kin-levels", + "kin.levels.raise": "kin-levels", + "kin.levels.deferPromotion": "kin-levels", + "kin.levels.shadowMemory": "kin-levels", "kin.push.registerDevice": "kin-push", "kin.push.unregisterDevice": "kin-push", "kin.push.watch": "kin-push",