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
3 changes: 2 additions & 1 deletion apps/server/src/kin/lead/layer.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as Scheduler from "../../scheduling/Scheduler.ts";
import * as Routines from "../triggers/routines.ts";
import * as DeferralFlow from "../triggers/deferralFlow.ts";
import * as OwnerCheck from "../triggers/ownerCheck.ts";
import * as TriggerScheduler from "../triggers/KinTriggerScheduler.ts";
import * as TriggerStore from "../triggers/KinTriggerStore.ts";
Expand Down Expand Up @@ -58,7 +59,7 @@ export function containStartup<A, E, R>(layer: Layer.Layer<A, E, R>) {
);
}

const routineRuntime = Routines.layer.pipe(
const routineRuntime = Layer.merge(Routines.layer, DeferralFlow.layer).pipe(
Layer.provideMerge(TriggerScheduler.layer),
Layer.provideMerge(Layer.mergeAll(TriggerStore.layer, TriggerInbox.layer)),
// Kin builds in its contained startup scope; orchestration runtime does not expose its scheduler.
Expand Down
134 changes: 1 addition & 133 deletions apps/server/src/kin/memory/Memory.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import * as NodeZlib from "node:zlib";
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Git object identity uses the native byte-oriented hash API.
import * as NodeCrypto from "node:crypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { KinAgentId, KinWakeupId, KinMemoryItemId, KinOrgId } from "@t3tools/contracts";
Expand All @@ -12,7 +10,6 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcessSpawner } from "effect/process";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import * as KinPersistence from "../persistence/KinPersistence.ts";
import * as Sqlite from "../../persistence/Sqlite.ts";
Expand All @@ -23,6 +20,7 @@ import * as MemoryCache from "./MemoryCache.ts";
import * as MemoryConfig from "./MemoryConfig.ts";
import * as ServerConfig from "../../config.ts";
import { fixtureItem } from "./__fixtures__/items.ts";
import { fakeRepository } from "./__fixtures__/repository.ts";

const memoryTestLayer = Memory.layer.pipe(
Layer.provide(
Expand All @@ -44,136 +42,6 @@ const databaseLayer = Layer.effectDiscard(
}),
).pipe(Layer.provideMerge(KinPersistence.layer.pipe(Layer.provideMerge(Sqlite.layerMemory))));

const fakeRepository = (fs: FileSystem.FileSystem) => {
const files = new Map<string, string>();
const objects = new Map<string, { type: string; bytes: Buffer }>();
const object = (type: string, bytes: Buffer) => {
const sha = NodeCrypto.createHash("sha1")
.update(`${type} ${bytes.length}\0`)
.update(bytes)
.digest("hex");
objects.set(sha, { type, bytes });
return sha;
};
const head = () => {
const tree = (prefix: string): string => {
const names = [
...new Set(
[...files.keys()]
.filter((name) => name.startsWith(prefix))
.map((name) => name.slice(prefix.length).split("/")[0] ?? ""),
),
].sort();
return object(
"tree",
Buffer.concat(
names.map((name) => {
const text = files.get(prefix + name);
const sha =
text === undefined ? tree(prefix + name + "/") : object("blob", Buffer.from(text));
return Buffer.concat([
Buffer.from(`${text === undefined ? "40000" : "100644"} ${name}\0`),
Buffer.from(sha, "hex"),
]);
}),
),
);
};
return object("commit", Buffer.from(`tree ${tree("")}\n\nfixture ${revision}\n`));
};
let validations = 0;
let treeReads = 0;
let blobReads = 0;
let revision = 0;
let corruptNextBatch = false;
const layer = Layer.succeed(
VcsProcess.VcsProcess,
VcsProcess.VcsProcess.of({
run: Effect.fn("Test.git")(({ args: rawArgs, stdin, cwd, onStdoutChunk }) => {
const args: string[] = [];
for (let i = 0; i < rawArgs.length; i++) {
const arg = rawArgs[i];
if (arg === "-c") {
i++;
continue;
}
if (
arg &&
!arg.startsWith("--git-dir=") &&
!arg.startsWith("--work-tree=") &&
arg !== "--no-replace-objects"
)
args.push(arg);
}
let stdout = "";
switch (args[0]) {
case "fetch":
case "rev-parse":
if (args.includes("refs/heads/main")) validations++;
stdout = args.includes("--show-toplevel")
? cwd
: args.includes("--git-common-dir")
? cwd.replace(/memory-read$/, "memory/.git")
: head();
break;
case "ls-remote":
stdout = `${head()}\trefs/heads/main\n`;
break;
case "cat-file": {
const chunks = (stdin?.trim().split("\n") ?? []).map((sha) => {
const entry = objects.get(sha);
if (!entry) return Buffer.from(`${sha} missing\n`);
if (args.includes("--batch-check"))
return Buffer.from(`${sha} ${entry.type} ${entry.bytes.length}\n`);
if (entry.type === "blob") blobReads++;
if (entry.type === "tree") treeReads++;
return Buffer.concat([
Buffer.from(`${sha} ${entry.type} ${entry.bytes.length}\n`),
entry.bytes,
Buffer.from("\n"),
]);
});
if (corruptNextBatch) {
chunks.unshift(Buffer.from("invalid header\n"));
corruptNextBatch = false;
}
if (args.includes("--batch-check")) stdout = Buffer.concat(chunks).toString("utf8");
else onStdoutChunk?.(Buffer.concat(chunks));
break;
}
}
onStdoutChunk?.(Buffer.from(stdout));
return Effect.gen(function* () {
if (args[0] === "clone" || args[0] === "clone-snapshot") {
yield* fs
.makeDirectory(`${args.at(-1)}/.git/objects`, { recursive: true })
.pipe(Effect.orDie);
}
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
};
});
}),
}),
);
return {
files,
head,
layer,
commit: () => {
revision++;
return head();
},
counts: () => ({ treeReads, blobReads, validations }),
corruptBatch: () => {
corruptNextBatch = true;
},
};
};
const configLayer = (baseDirectory: string, repoUrl: string) =>
Layer.succeed(MemoryConfig.MemoryConfig, {
baseDirectory,
Expand Down
50 changes: 40 additions & 10 deletions apps/server/src/kin/memory/MemoryWriter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ it.live.each([
"credentials",
"read-during-record",
"deferral-card-remind",
"deferral-card-monday",
"deferral-plain-remind",
"deferral-card-other-item",
"H3-packed-ref",
Expand Down Expand Up @@ -280,22 +281,32 @@ it.live.each([
itemId: scenario === "owner-other-item-keep" ? "other-item" : "def-001",
action: scenario === "owner-drop-keep" ? "drop" : "keep",
}
: scenario === "deferral-card-remind" ||
scenario === "deferral-card-other-item"
: scenario === "deferral-card-monday"
? {
saidBy: "fixture-owner",
trust: "owner",
source: "fixture-owner-message",
kind: "deferral_card",
itemId:
scenario === "deferral-card-other-item" ? "other-item" : "def-001",
action: "remind",
itemId: "def-001",
action: "monday",
due: "2026-11-16T09:00:00.000+05:30",
}
: {
saidBy: "fixture-owner",
trust: "owner",
source: "fixture-owner-message",
},
: scenario === "deferral-card-remind" ||
scenario === "deferral-card-other-item"
? {
saidBy: "fixture-owner",
trust: "owner",
source: "fixture-owner-message",
kind: "deferral_card",
itemId:
scenario === "deferral-card-other-item" ? "other-item" : "def-001",
action: "remind",
}
: {
saidBy: "fixture-owner",
trust: "owner",
source: "fixture-owner-message",
},
],
[
"member",
Expand Down Expand Up @@ -653,6 +664,25 @@ it.live.each([
expect(result._tag === "Failure" && result.failure._tag).toBe("MemoryConflict");
return;
}
if (scenario === "deferral-card-monday") {
const stage = (fields: Record<string, unknown>) =>
writer
.stage(orgId, "wake1", {
path: "deferrals/def-001.md",
content: fixtureItem(fields),
sourceEventId: "owner",
})
.pipe(Effect.result);
for (const forged of [
{ due: "2026-11-17T09:00:00.000+05:30" },
{ due: "2026-11-16T09:00:00.000+05:30", on_due: "remind" },
]) {
const result = yield* stage(forged);
expect(result._tag === "Failure" && result.failure._tag).toBe("MemoryConflict");
}
expect((yield* stage({ due: "2026-11-16T09:00:00.000+05:30" }))._tag).toBe("Success");
return;
}
if (scenario === "deferral-card-remind") {
const stage = (onDue: string) =>
writer
Expand Down
15 changes: 15 additions & 0 deletions apps/server/src/kin/memory/MemoryWriter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ export interface WakeupContext extends JournalContext {
readonly action: "keep" | "update" | "drop";
}
| { readonly kind: "deferral_card"; readonly itemId: string; readonly action: "remind" }
| {
readonly kind: "deferral_card";
readonly itemId: string;
readonly action: "monday";
readonly due: string;
}
)
>;
}
Expand Down Expand Up @@ -644,11 +650,20 @@ const make = Effect.gen(function* () {
mutable.add("review_by");
if (
source.kind === "deferral_card" &&
source.action === "remind" &&
source.itemId === item.id &&
item.kind === "deferral" &&
fm.on_due === "remind"
)
mutable.add("on_due");
if (
source.kind === "deferral_card" &&
source.action === "monday" &&
source.itemId === item.id &&
item.kind === "deferral" &&
fm.due === source.due
)
mutable.add("due");
const existing = new Map(Object.entries(item));
if (
[...new Set([...existing.keys(), ...proposed.keys()])].some(
Expand Down
Loading