Skip to content
Open
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: 3 additions & 0 deletions apps/server/src/kin/lead/WakeupRunner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,7 @@ describe("WakeupRunner", () => {
deleteDreamBranch: () => Effect.die("unused"),
reconcileSharing: () => Effect.void,
stripQuotes: () => Effect.void,
landShadows: () => Effect.void,
undoChange: () => Effect.die("unused"),
relabel: () => Effect.die("unused"),
retire: () => Effect.die("unused"),
Expand Down Expand Up @@ -749,6 +750,7 @@ describe("WakeupRunner", () => {
deleteDreamBranch: () => Effect.die("unused"),
reconcileSharing: () => Effect.void,
stripQuotes: () => Effect.void,
landShadows: () => Effect.void,
undoChange: () => Effect.die("unused"),
relabel: () => Effect.die("unused"),
retire: () => Effect.die("unused"),
Expand Down Expand Up @@ -877,6 +879,7 @@ describe("WakeupRunner", () => {
deleteDreamBranch: () => Effect.die("unused"),
reconcileSharing: () => Effect.void,
stripQuotes: () => Effect.void,
landShadows: () => Effect.void,
undoChange: () => Effect.die("unused"),
relabel: () => Effect.die("unused"),
retire: () => Effect.die("unused"),
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/kin/lead/layer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ it.effect("a cleared chat and each memory sync sweep deleted messages' quotes",
const writer = Layer.mock(Writer.MemoryWriter)({
reconcileSharing: () => Effect.void,
stripQuotes: (org) => Deferred.succeed(org === clearedOrg ? cleared : synced, undefined),
landShadows: () => Effect.void,
});
const hub = Layer.mock(ChatHub.KinChatHub)({
subscribeAll: Effect.succeed(
Expand Down
13 changes: 13 additions & 0 deletions apps/server/src/kin/lead/layer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,19 @@ const memorySync = Effect.fn("KinMemory.syncDue")(function* (
}),
),
Effect.andThen(stripQuotes(writer.value, orgId)),
Effect.andThen(
writer.value.landShadows(orgId).pipe(
Effect.catchCause((cause) =>
Effect.logWarning(
"Kin could not land shadow memory on the default branch",
{
orgId,
cause: Cause.pretty(cause),
},
),
),
),
),
),
),
),
Expand Down
191 changes: 191 additions & 0 deletions apps/server/src/kin/memory/MemoryWriter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
KinMemoryItemId,
KinOrgId,
type MemoryItemHead,
type VcsError,
VcsProcessSpawnError,
} from "@t3tools/contracts";
import * as ConfigProvider from "effect/ConfigProvider";
Expand Down Expand Up @@ -1953,3 +1954,193 @@ it.effect(
Effect.scoped,
),
);

// A lead that wrote at L0 before leads worked on the default branch kept its notes on its shadow
// branch, and nothing landed them.
const landingFixture = <E>(
run: (input: {
readonly setLevel: (level: "L0" | "L2") => void;
readonly bare: (args: ReadonlyArray<string>) => Effect.Effect<string, VcsError>;
readonly notices: ReadonlyArray<{ readonly branch: string; readonly reason: string }>;
}) => Effect.Effect<
void,
E,
Memory.Memory | Writer.MemoryWriter | SqlClient.SqlClient | FileSystem.FileSystem
>,
) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const vcs = yield* Vcs.VcsProcess;
const root = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());
const source = `${root}/seed`;
const remote = `${root}/remote.git`;
const git = (cwd: string, args: ReadonlyArray<string>) =>
vcs
.run({ operation: "test.writer", command: "git", cwd, args })
.pipe(Effect.map((r) => r.stdout.trim()));
yield* fs.makeDirectory(`${source}/people`, { recursive: true });
yield* fs.writeFileString(`${source}/rules.md`, "Invented rules\n");
yield* fs.writeFileString(`${source}/INDEX.md`, "# Memory index\n");
yield* git(source, ["init", "-b", "main"]);
yield* git(source, ["add", "--", "."]);
yield* git(source, [
"-c",
"user.name=Fixture Bot",
"-c",
"user.email=fixture@example.invalid",
"commit",
"-m",
"fixture",
]);
yield* git(root, ["clone", "--bare", "--", source, remote]);
let level: "L0" | "L2" = "L0";
const notices: Array<{ branch: string; reason: string }> = [];
const config = Layer.succeed(MemoryConfig, {
baseDirectory: root,
directMainPush: true,
repositories: [{ orgId, repoUrl: remote, path: "state" }],
});
const layer = Writer.layer.pipe(
Layer.provideMerge(
Memory.layer.pipe(
Layer.provide(config),
Layer.provide(Layer.succeed(Memory.MemorySyncHooks, { syncItems: () => Effect.void })),
),
),
Layer.provideMerge(Repository.layer),
Layer.provide(
Layer.succeed(Memory.MemoryRecoveryHooks, {
notify: (notice) => Effect.sync(() => void notices.push(notice)),
}),
),
Layer.provide(config),
Layer.provide(Layer.succeed(Writer.MemoryWriterHooks, { notify: () => Effect.void })),
Layer.provide(
Layer.succeed(Writer.MemoryWriterAuthority, {
resolve: (_org: KinOrgId, wakeupId: string) =>
Effect.succeed({
orgId,
wakeupId,
agentId,
level,
timeZone: "UTC",
startedAt: "2026-11-08T00:00:00.000Z",
eventIds: [],
sources: new Map(),
}),
}),
),
Layer.provide(Scan.layer),
);
yield* Effect.gen(function* () {
const memory = yield* Memory.Memory;
const sql = yield* SqlClient.SqlClient;
const at = "2026-11-08T00:00:00.000Z";
yield* sql`INSERT INTO kin_orgs VALUES (${orgId}, 'Org', ${at})`;
yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, created_at) VALUES ('owner', ${orgId}, 'owner', 'Owner', ${at})`;
yield* sql`INSERT INTO kin_agents (agent_id, org_id, display_name, role, owner_person_id, created_at) VALUES (${agentId}, ${orgId}, 'Lead', 'lead', 'owner', ${at})`;
yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, last_seq, created_at) VALUES ('owner-chat', ${orgId}, 'team_group', 0, ${at})`;
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, '{}', '[]', 'owner-chat')`;
yield* memory.ensureCheckouts(orgId);
yield* memory.prepareWakeup(orgId);
yield* run({
setLevel: (next) => {
level = next;
},
bare: (args) => git(root, [`--git-dir=${remote}`, ...args]),
notices,
});
}).pipe(Effect.provide(layer));
}).pipe(
Effect.provide(
Layer.mergeAll(
gitLayer,
NodeServices.layer,
Persistence.layer.pipe(Layer.provideMerge(Sqlite.layerMemory)),
),
),
Effect.scoped,
);
const personNote = (id: string, title: string) => ({
path: `people/${id}.md`,
content: fixtureItem({
id,
kind: "person",
title,
due: null,
on_due: undefined,
review_by: null,
links: [`person:${id}`],
}),
});

it.effect("an L0 lead's shadow notes land on the default branch and its index, once", () =>
landingFixture(({ bare, setLevel }) =>
Effect.gen(function* () {
const writer = yield* Writer.MemoryWriter;
const shadow = Memory.shadowBranch(agentId);
const main = () => bare(["rev-parse", "main"]);
// No shadow branch yet: nothing to land.
const untouched = yield* main();
yield* writer.landShadows(orgId);
assert.strictEqual(yield* main(), untouched);

yield* writer.stage(orgId, "wake0", personNote("owner-repos", "The owner's two main repos"));
yield* writer.commitWakeup(orgId, "wake0", "completed");
assert.include(yield* bare(["show", `${shadow}:INDEX.md`]), "owner-repos");
assert.notInclude(yield* bare(["show", "main:INDEX.md"]), "owner-repos");

yield* writer.landShadows(orgId);
const landed = yield* main();
assert.notStrictEqual(landed, untouched);
assert.strictEqual(
yield* bare(["show", "main:people/owner-repos.md"]),
yield* bare(["show", `${shadow}:people/owner-repos.md`]),
);
assert.include(yield* bare(["show", "main:INDEX.md"]), "owner-repos");
assert.notInclude(yield* bare(["ls-tree", "-r", "--name-only", "main"]), "journal/");

// Later shadow writes (a chat the owner didn't place the lead in) stay off the default branch.
yield* writer.stage(orgId, "wake1", personNote("teammate-only", "Said in someone's group"));
yield* writer.commitWakeup(orgId, "wake1", "completed");
yield* writer.landShadows(orgId);
assert.strictEqual(yield* main(), landed);

// A lead now on the default branch reads what it wrote at L0.
setLevel("L2");
yield* writer.stage(orgId, "wake2", personNote("sam", "Sam runs billing"));
const index = yield* bare([
"show",
`${(yield* writer.commitWakeup(orgId, "wake2", "completed")).commit}:INDEX.md`,
]);
assert.include(index, "owner-repos");
}),
),
);

it.effect("a shadow note the default branch also changed keeps the default branch's", () =>
landingFixture(({ bare, setLevel, notices }) =>
Effect.gen(function* () {
const writer = yield* Writer.MemoryWriter;
const shadow = Memory.shadowBranch(agentId);
yield* writer.stage(orgId, "wake0", personNote("sam", "Sam, as the shadow has it"));
yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design"));
yield* writer.commitWakeup(orgId, "wake0", "completed");
setLevel("L2");
yield* writer.stage(orgId, "wake1", personNote("sam", "Sam, as the default branch has it"));
yield* writer.commitWakeup(orgId, "wake1", "completed");

yield* writer.landShadows(orgId);
assert.include(yield* bare(["show", "main:people/sam.md"]), "as the default branch has it");
assert.include(yield* bare(["show", `${shadow}:people/sam.md`]), "as the shadow has it");
assert.include(yield* bare(["show", "main:people/alex.md"]), "Alex leads design");
assert.deepStrictEqual(
notices.filter((notice) => notice.branch === shadow).map((notice) => notice.reason),
[
"Kept the default branch's people/sam.md over this shadow branch's, which still holds its own",
],
);
}),
),
);
85 changes: 85 additions & 0 deletions apps/server/src/kin/memory/MemoryWriter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,8 +306,16 @@ export class MemoryWriter extends Context.Service<
* so it runs after a clear and at every sync, which also finishes one a crash cut short.
*/
readonly stripQuotes: (orgId: KinOrgId) => Effect.Effect<void, Failure>;
/**
* Once per live lead, lands the items its shadow branch holds that the default branch lacks:
* notes written at L0 before leads worked on the default branch. Where both changed an
* item, the default branch's stays and the shadow branch keeps its own.
*/
readonly landShadows: (orgId: KinOrgId) => Effect.Effect<void, Failure>;
}
>()("t3/kin/memory/MemoryWriter") {}
// No table of its own: a `kin_memory_heads` row no branch uses, holding the shadow head landed.
const shadowLanded = (agentId: string) => `kin/shadow-landed/${agentId}`;
const isRepoSlug = Schema.is(RepoSlug);
const dreamBranch = /^dream\/\d{4}-\d{2}-\d{2}$/;
const folders = [
Expand Down Expand Up @@ -1883,6 +1891,83 @@ const make = Effect.gen(function* () {
}),
),
),
landShadows: Effect.fn("MemoryWriter.landShadows")((orgId) =>
locked(
orgId,
Effect.gen(function* () {
const main = config.defaultBranch ?? "main";
const toSql = Effect.mapError(toPersistenceSqlError("MemoryWriter.landShadows"));
const pending = yield* sql<{ agentId: string; branch: string }>`SELECT
l.agent_id AS "agentId", h.branch FROM kin_memory_heads h
JOIN kin_leads l ON l.org_id = h.org_id AND h.branch = 'kin/shadow/' || l.agent_id
JOIN kin_agents a ON a.org_id = l.org_id AND a.agent_id = l.agent_id
AND a.retired_at IS NULL
WHERE h.org_id = ${orgId} AND NOT EXISTS (SELECT 1 FROM kin_memory_heads m
WHERE m.org_id = h.org_id AND m.branch = 'kin/shadow-landed/' || l.agent_id)
ORDER BY l.agent_id`.pipe(toSql);
// Tried again at the next sync once the default branch takes writes.
if (pending.length === 0 || mainWrites === "refused") return;
const { writer } = yield* validate(orgId);
yield* refuseDuringPurge(orgId);
const repo = yield* repoFor(orgId);
if (mainWrites === "pull_request") yield* refuseOffGitHub(orgId);
const same = (a: Buffer | undefined, b: Buffer | undefined) =>
a === undefined ? b === undefined : b !== undefined && a.equals(b);
for (const { agentId, branch } of pending) {
const shadowHead = yield* branchHead(orgId, writer, branch);
const shadowFiles = yield* filesAt(orgId, writer, shadowHead);
const head = yield* branchHead(orgId, writer, main);
const headFiles = yield* filesAt(orgId, writer, head);
const base = yield* git(orgId, writer, ["merge-base", head, shadowHead]).pipe(
Effect.orElseSucceed(() => ""),
);
const baseFiles: ReadonlyMap<string, Buffer> =
base === "" ? new Map() : yield* filesAt(orgId, writer, base);
const files = new Map<string, string>();
const kept: Array<string> = [];
const ending: Array<string> = [];
for (const [path, bytes] of shadowFiles) {
if (!folders.some((folder) => path.startsWith(`${folder}/`))) continue;
const now = headFiles.get(path);
if (same(baseFiles.get(path), bytes) || same(now, bytes)) continue;
if (now !== undefined && !same(now, baseFiles.get(path))) {
kept.push(path);
continue;
}
const text = bytes.toString("utf8");
const parsed = yield* parseFrontMatter(orgId, path, text).pipe(Effect.option);
if (Option.isNone(parsed)) continue;
if (retired(parsed.value.frontMatter)) ending.push(parsed.value.frontMatter.id);
files.set(path, text);
}
const mark = sql`INSERT INTO kin_memory_heads (org_id, branch, head)
VALUES (${orgId}, ${shadowLanded(agentId)}, ${shadowHead})
ON CONFLICT DO NOTHING`.pipe(toSql, Effect.asVoid);
if (kept.length > 0)
yield* recovery.notify({
orgId,
branch,
reason: `Kept the default branch's ${kept.join(", ")} over this shadow branch's, which still holds its own`,
});
if (files.size === 0) {
yield* mark;
continue;
}
yield* endSharing(orgId, ending);
yield* ownerCommit(orgId, {
writer,
repoUrl: repo.repoUrl,
branch: main,
head,
headFiles,
files,
message: `kin(${agentId}): land notes kept at L0\n\nKin-Shadow-Landed: ${shadowHead}\n`,
landed: () => mark,
});
}
}),
),
),
});
});
export const layer = Layer.effect(MemoryWriter, make).pipe(
Expand Down