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
1 change: 1 addition & 0 deletions KIN.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,6 @@ git merge upstream/main
sed -i.bak -E 's/runs-on: blacksmith-[0-9]+vcpu-ubuntu-2404/runs-on: ubuntu-24.04/; s/runs-on: blacksmith-[0-9]+vcpu-macos-26/runs-on: macos-26/' .github/workflows/ci.yml .github/workflows/mobile-fingerprint-check.yml && rm .github/workflows/*.bak
vp i
vp run check:changed upstream/main
(cd apps/server && vp test run kin-contract)
git push origin main kin
```
29 changes: 29 additions & 0 deletions apps/server/src/kin/contract/delegateTask.kin-contract.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { assert, it } from "@effect/vitest";
import {
OrchestratorMcpDelegateTaskInput,
OrchestratorMcpDelegateTaskResult,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";

const decodeInput = Schema.decodeSync(OrchestratorMcpDelegateTaskInput);

const decodeResult = Schema.decodeSync(
Schema.Struct({ childThreadId: OrchestratorMcpDelegateTaskResult.fields.childThreadId }),
);

it("decodes LEAD's worktree brief and the durable child thread result", () => {
const task =
"You were called by another agent. Do this task yourself. Review the PR and report findings.";
const input = decodeInput({
task,
isolation: "worktree",
target: { providerInstanceId: "codex", model: "gpt-6.1-sol", options: { effort: "medium" } },
});
assert.equal(input.task, task);
assert.equal(input.isolation, "worktree");
assert.equal(input.target?.providerInstanceId, "codex");
assert.equal(input.target?.model, "gpt-6.1-sol");
assert.deepEqual(input.target?.options, [{ id: "effort", value: "medium" }]);
const result = decodeResult({ childThreadId: "thread-child-18" });
assert.equal(result.childThreadId, "thread-child-18");
});
131 changes: 131 additions & 0 deletions apps/server/src/kin/contract/fixtures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import {
OrchestrationV2DomainEventJson,
ScheduledTaskUpsertInput,
type ManagedPolicyDocument,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/sql/SqlClient";

import { emptyProjection } from "../../orchestration-v2/ProjectionStore.ts";
import * as ThreadLaunch from "../../orchestration-v2/ThreadLaunchService.ts";
import * as ThreadManagement from "../../orchestration-v2/ThreadManagementService.ts";
import * as ManagedPolicy from "../../policy/ManagedPolicy.ts";
import * as ManagedProjectFolders from "../../project/ManagedProjectFolders.ts";
import * as ScheduledTasks from "../../scheduledTasks/ScheduledTaskService.ts";
import * as Scheduler from "../../scheduling/Scheduler.ts";
import * as SecretRequests from "../../secrets/SecretRequests.ts";
import * as KinTriggerSink from "../triggers/KinTriggerSink.ts";

const decodeEvent = Schema.decodeSync(OrchestrationV2DomainEventJson);

const decodeUpsert = Schema.decodeEffect(ScheduledTaskUpsertInput);

const projection = () => {
const event = decodeEvent({
id: "event-contract",
threadId: "thread-contract",
type: "thread.created",
occurredAt: "2026-11-08T00:00:00.000Z",
payload: {
id: "thread-contract",
projectId: "project-contract",
title: "Inbox",
providerInstanceId: "codex",
modelSelection: { instanceId: "codex", model: "gpt-5.4" },
runtimeMode: "approval-required",
interactionMode: "plan",
branch: null,
worktreePath: null,
activeProviderThreadId: null,
lineage: {
parentThreadId: null,
relationshipToParent: null,
rootThreadId: "thread-contract",
},
forkedFrom: null,
createdBy: "system",
creationSource: "server",
createdAt: "2026-11-08T00:00:00.000Z",
updatedAt: "2026-11-08T00:00:00.000Z",
archivedAt: "2026-11-08T00:00:00.000Z",
deletedAt: null,
},
});
if (event.type !== "thread.created") throw new Error("Expected thread.created");
return emptyProjection(event);
};

export const webhookInput = (overrides: Partial<typeof ScheduledTaskUpsertInput.Encoded> = {}) =>
decodeUpsert({
id: "kin-github",
title: "GitHub inbox",
prompt: "Review {{body}}",
enabled: true,
schedule: { type: "webhook" },
projectId: "project-contract",
threadMode: "new_thread",
workspaceStrategy: { type: "root" },
modelSelection: { instanceId: "codex", model: "gpt-6.1-sol" },
runtimeMode: "full-access",
interactionMode: "default",
...overrides,
});

export const withScheduledTasks = Effect.fn("KinContract.withScheduledTasks")(function* <A, E>(
body: (input: {
service: ScheduledTasks.ScheduledTaskService["Service"];
launches: Queue.Queue<ThreadLaunch.ThreadLaunchInput>;
sends: Queue.Queue<ThreadManagement.ThreadManagementSendInput>;
launchDeliveries: Queue.Queue<ReadonlyArray<{ readonly receivedAt: unknown }>>;
}) => Effect.Effect<A, E, SqlClient.SqlClient>,
policy?: ManagedPolicyDocument,
) {
const sql = yield* SqlClient.SqlClient;
const launchDeliveries =
yield* Queue.unbounded<ReadonlyArray<{ readonly receivedAt: unknown }>>();
const launches = yield* Queue.unbounded<ThreadLaunch.ThreadLaunchInput>();
const sends = yield* Queue.unbounded<ThreadManagement.ThreadManagementSendInput>();
const dependencies = Layer.mergeAll(
NodeCrypto.layer,
Scheduler.layer,
ManagedPolicy.layerTest(policy),
Layer.mock(ThreadLaunch.ThreadLaunchService)({
launch: Effect.fn("KinContract.launch")(function* (input) {
const taskId = input.initialMessage?.scheduledTaskId;
const prefix = `scheduled-task:${taskId}:webhook:`;
const deliveryId = input.commandId.slice(prefix.length);
const rows = yield* KinTriggerSink.findLaunchDelivery(sql, {
taskId: taskId ?? "",
deliveryId,
projectId: input.projectId,
}).pipe(Effect.orDie);
yield* Queue.offer(launchDeliveries, rows);
yield* Queue.offer(launches, input);
const result = projection();
return { threadId: result.thread.id, projection: result, resumed: false };
}),
}),
Layer.mock(ThreadManagement.ThreadManagementService)({
// Only the input boundary is under contract; no orchestrator runs in this fixture.
sendToThread: (input) =>
Queue.offer(sends, input).pipe(Effect.andThen(Effect.die("send boundary reached"))),
}),
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
namedProjectsRoot: "/projects",
isScratchProject: () => Effect.succeed(false),
}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.succeed(
ScheduledTasks.ScheduledTaskWebhookOrigin,
Effect.succeed({ relayHookBaseUrl: null }),
),
);
return yield* Effect.gen(function* () {
const service = yield* ScheduledTasks.ScheduledTaskService;
return yield* body({ service, launches, sends, launchDeliveries });
}).pipe(Effect.provide(Layer.fresh(ScheduledTasks.layer.pipe(Layer.provide(dependencies)))));
});
52 changes: 52 additions & 0 deletions apps/server/src/kin/contract/managedPolicy.kin-contract.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { assert, it } from "@effect/vitest";
import { ManagedPolicyDocument } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Sqlite from "../../persistence/Sqlite.ts";
import { webhookInput, withScheduledTasks } from "./fixtures.ts";

const decodePolicy = Schema.decodeEffect(ManagedPolicyDocument);

it.effect("decodes locked settings and marks existing webhook tasks blocked by policy", () =>
Effect.gen(function* () {
const policy = yield* decodePolicy({
schemaVersion: 1,
organization: "Kin",
settings: { "storageCleanup.logsAfterDays": { value: 14, locked: true } },
limits: { webhookTasks: false },
});
assert.deepEqual(policy.settings?.["storageCleanup.logsAfterDays"], {
value: 14,
locked: true,
});
assert.equal(policy.limits?.webhookTasks, false);
const task = yield* withScheduledTasks(({ service }) =>
webhookInput().pipe(
Effect.flatMap(service.upsert),
Effect.map(({ task }) => task),
),
);
yield* withScheduledTasks(
({ service, launches }) =>
Effect.gen(function* () {
const listed = (yield* service.list()).tasks.find(({ id }) => id === task.id);
assert.isString(listed?.blockedByPolicy);
assert.isNotEmpty(listed?.blockedByPolicy);
const response = yield* service.triggerWebhook({
hookId: task.id,
token: task.webhook?.path.split("/").at(-1) ?? "",
method: "POST",
path: `/api/hooks/${task.id}`,
query: "",
headers: {},
body: new TextEncoder().encode("{}"),
bodyText: "{}",
});
assert.equal(response._tag, "blocked_by_policy");
assert.equal(yield* Queue.size(launches), 0);
}),
policy,
);
}).pipe(Effect.provide(Sqlite.layerMemory)),
);
88 changes: 88 additions & 0 deletions apps/server/src/kin/contract/relay.kin-contract.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
import * as NodeCrypto from "node:crypto";
import * as PlatformCrypto from "@effect/platform-node/NodeCrypto";
import { assert, it } from "@effect/vitest";
import { EnvironmentId } from "@t3tools/contracts";
import { signRelayJwt, RELAY_HOOK_DELIVERY_TYP } from "@t3tools/shared/relayJwt";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
import { CLOUD_MINT_PUBLIC_KEY, RELAY_ISSUER_SECRET } from "../../cloud/config.ts";
import * as ServerEnvironment from "../../environment/ServerEnvironment.ts";
import * as RelayDeliveryProof from "../../scheduledTasks/RelayDeliveryProof.ts";

it.effect(
"verifies a relay-signed delivery using Kin's header names and returns receivedAt",
() => {
const keys = NodeCrypto.generateKeyPairSync("ed25519", {
privateKeyEncoding: { format: "pem", type: "pkcs8" },
publicKeyEncoding: { format: "pem", type: "spki" },
});
const environmentId = EnvironmentId.make("env-contract");
const issuer = "https://relay.example.test";
const secrets = new Map([
[CLOUD_MINT_PUBLIC_KEY, keys.publicKey],
[RELAY_ISSUER_SECRET, issuer],
]);
return Effect.gen(function* () {
const now = Math.floor((yield* Clock.currentTimeMillis) / 1000);
const receivedAt = "1970-01-01T00:00:00.000Z";
const proof = yield* signRelayJwt({
privateKey: keys.privateKey,
typ: RELAY_HOOK_DELIVERY_TYP,
payload: {
iss: issuer,
aud: `t3-env:${environmentId}`,
sub: environmentId,
jti: "proof-contract",
iat: now,
exp: now + 3600,
environmentId,
deliveryId: "relay-contract",
receivedAt,
hookId: "kin-github",
},
});
const verifier = yield* RelayDeliveryProof.RelayDeliveryProof;
const headers = {
"x-t3-relay-delivery": proof,
"x-t3-relay-delivery-id": "relay-contract",
"x-t3-relay-received-at": receivedAt,
};
assert.deepEqual(
yield* verifier.verify({ hookId: "kin-github", headers }),
Option.some({ deliveryId: "relay-contract", receivedAt }),
);
assert.deepEqual(
yield* verifier.verify({
hookId: "kin-github",
headers: { ...headers, "x-t3-relay-received-at": "1970-01-01T00:01:00.000Z" },
}),
Option.none(),
);
}).pipe(
Effect.provide(
RelayDeliveryProof.layer.pipe(
Layer.provideMerge(
Layer.mergeAll(
Layer.mock(ServerSecretStore.ServerSecretStore)({
get: (name) =>
Effect.succeed(
Option.map(Option.fromUndefinedOr(secrets.get(name)), (value) =>
new TextEncoder().encode(value),
),
),
}),
Layer.mock(ServerEnvironment.ServerEnvironment)({
getEnvironmentId: Effect.succeed(environmentId),
}),
PlatformCrypto.layerSignature,
),
),
),
),
);
},
);
Loading
Loading