From ebc1e63ab9e16b17c5abc56a76076ea1939537d5 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Mon, 23 Nov 2026 07:32:44 +0530 Subject: [PATCH 1/2] fix(kin): land an L0 lead's shadow notes on the default branch once A lead that ran at L0 before leads worked on the default branch kept its notes on kin/shadow/, and nothing landed them, so it started from an empty index. The memory sync at start-up now lands, once per live lead, the items its shadow branch changed that the default branch lacks, through the writer's owner commit (secret scan, index rebuild). Where both changed an item the default branch's stays and the shadow branch keeps its own. A kin_memory_heads marker row records the landed shadow head, so later shadow writes stay off the default branch. Refs #12 Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/lead/WakeupRunner.test.ts | 3 + apps/server/src/kin/lead/layer.test.ts | 1 + apps/server/src/kin/lead/layer.ts | 13 ++ .../src/kin/memory/MemoryWriter.test.ts | 191 ++++++++++++++++++ apps/server/src/kin/memory/MemoryWriter.ts | 85 ++++++++ 5 files changed, 293 insertions(+) diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index aa45ae82ce7cc..c52715c613ff1 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -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"), @@ -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"), @@ -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"), diff --git a/apps/server/src/kin/lead/layer.test.ts b/apps/server/src/kin/lead/layer.test.ts index da2a363dba0d5..320134bb1a598 100644 --- a/apps/server/src/kin/lead/layer.test.ts +++ b/apps/server/src/kin/lead/layer.test.ts @@ -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( diff --git a/apps/server/src/kin/lead/layer.ts b/apps/server/src/kin/lead/layer.ts index 2c474e99341b2..db527f27e2376 100644 --- a/apps/server/src/kin/lead/layer.ts +++ b/apps/server/src/kin/lead/layer.ts @@ -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), + }, + ), + ), + ), + ), ), ), ), diff --git a/apps/server/src/kin/memory/MemoryWriter.test.ts b/apps/server/src/kin/memory/MemoryWriter.test.ts index 647ccbe10a16e..f67d3a633c1df 100644 --- a/apps/server/src/kin/memory/MemoryWriter.test.ts +++ b/apps/server/src/kin/memory/MemoryWriter.test.ts @@ -9,6 +9,7 @@ import { KinMemoryItemId, KinOrgId, type MemoryItemHead, + type VcsError, VcsProcessSpawnError, } from "@t3tools/contracts"; import * as ConfigProvider from "effect/ConfigProvider"; @@ -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 = ( + run: (input: { + readonly setLevel: (level: "L0" | "L2") => void; + readonly bare: (args: ReadonlyArray) => Effect.Effect; + 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) => + 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", + ], + ); + }), + ), +); diff --git a/apps/server/src/kin/memory/MemoryWriter.ts b/apps/server/src/kin/memory/MemoryWriter.ts index b69d902d53b5d..4df403191c8c1 100644 --- a/apps/server/src/kin/memory/MemoryWriter.ts +++ b/apps/server/src/kin/memory/MemoryWriter.ts @@ -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; + /** + * 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; } >()("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 = [ @@ -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 = + base === "" ? new Map() : yield* filesAt(orgId, writer, base); + const files = new Map(); + const kept: Array = []; + const ending: Array = []; + 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( From aa937fa42677578545ffab1e07afe04c4cccf703 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Mon, 23 Nov 2026 07:34:11 +0530 Subject: [PATCH 2/2] chore(kin): say what changes for people with the shadow-notes landing People-change: A lead that ran at L0 before #155 now finds the notes it wrote then in its memory and index; the owner sees them in Memory, and a note that clashed with a newer one on main gets a recovery notice naming the file. Co-Authored-By: Claude Opus 5.5