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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/server/src/kin/KinServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -26,6 +28,8 @@ export type Services =
| KinStop
| KinLevelGate
| KinShadowSummary
| KinPromotion
| KinPromotionCards
| KinGithubWebhookLock
| ApproverKeys
| GrantVerifier
Expand Down
23 changes: 23 additions & 0 deletions apps/server/src/kin/approvals/PendingActions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
[
Expand Down
22 changes: 16 additions & 6 deletions apps/server/src/kin/approvals/PendingActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, KinActionKind>([
[KIN_APPROVER_KEYS_REQUESTER, "register_approver_key"],
[KIN_PROMOTION_REQUESTER, "set_level"],
]);
const CreateInput = Schema.Struct({
orgId: KinOrgId,
kind: KinActionKind,
Expand All @@ -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;
Expand Down
62 changes: 62 additions & 0 deletions apps/server/src/kin/approvals/handlers/setLevel.ts
Original file line number Diff line number Diff line change
@@ -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<KinLevels.KinLevelRefused["reason"], string> = {
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 };
});
2 changes: 2 additions & 0 deletions apps/server/src/kin/chat/KinChatService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
7 changes: 4 additions & 3 deletions apps/server/src/kin/layer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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, {
Expand Down
40 changes: 34 additions & 6 deletions apps/server/src/kin/lead/KinLevels.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<string, string>();
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<string> = [];
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)),
);
Loading