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 01/13] 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 02/13] 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 From c4d34c19a07fc383a412469f37b3cb4c7fd21364 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Wed, 25 Nov 2026 18:57:55 +0530 Subject: [PATCH 03/13] fix(kin): land only what a shadow held when #155 cut over The first landing took each shadow branch's tip, so notes a lead wrote at L0 after #155 (from chats its owner didn't place it in) landed on the default branch too. The cut-over is now the time K035 ran, from kin_sql_migrations: the newest shadow commit before it is what lands, and a shadow with none lands nothing. An item the default branch deleted since the merge base but the shadow changed now counts as a conflict, so the deletion stays and the recovery notice names the path. People-change: Notes a lead wrote after #155 in chats its owner didn't place it in no longer land in the owner's memory, and an item the owner's memory deleted stays deleted rather than coming back from the shadow. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/memory/MemoryWriter.test.ts | 121 +++++++++++++++--- apps/server/src/kin/memory/MemoryWriter.ts | 33 +++-- 2 files changed, 129 insertions(+), 25 deletions(-) diff --git a/apps/server/src/kin/memory/MemoryWriter.test.ts b/apps/server/src/kin/memory/MemoryWriter.test.ts index f67d3a633c1df..2fbdf979dcb5b 100644 --- a/apps/server/src/kin/memory/MemoryWriter.test.ts +++ b/apps/server/src/kin/memory/MemoryWriter.test.ts @@ -2042,6 +2042,9 @@ const landingFixture = ( 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')`; + // When K035 ran: leads stopped working on their shadow branch then. + yield* sql`UPDATE kin_sql_migrations SET created_at = '2026-11-10 12:42:41' + WHERE migration_id = 35`; yield* memory.ensureCheckouts(orgId); yield* memory.prepareWakeup(orgId); yield* run({ @@ -2062,6 +2065,21 @@ const landingFixture = ( ), Effect.scoped, ); +// Commits made inside are dated before the cut-over, as an L0 lead's were. +const beforeCutOver = (effect: Effect.Effect) => + Effect.acquireUseRelease( + Effect.sync(() => { + const previous = process.env.GIT_COMMITTER_DATE; + process.env.GIT_COMMITTER_DATE = "2026-11-01T00:00:00Z"; + return previous; + }), + () => effect, + (previous) => + Effect.sync(() => { + if (previous === undefined) delete process.env.GIT_COMMITTER_DATE; + else process.env.GIT_COMMITTER_DATE = previous; + }), + ); const personNote = (id: string, title: string) => ({ path: `people/${id}.md`, content: fixtureItem({ @@ -2087,7 +2105,7 @@ it.effect("an L0 lead's shadow notes land on the default branch and its index, o 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"); + yield* beforeCutOver(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"); @@ -2119,28 +2137,97 @@ it.effect("an L0 lead's shadow notes land on the default branch and its index, o ), ); -it.effect("a shadow note the default branch also changed keeps the default branch's", () => - landingFixture(({ bare, setLevel, notices }) => +it.effect("a shadow note written after the cut-over stays off the default branch", () => + landingFixture(({ bare }) => 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.stage(orgId, "wake0", personNote("owner-repos", "The owner's two main repos")); + yield* beforeCutOver(writer.commitWakeup(orgId, "wake0", "completed")); + // After the cut-over, an L0 write comes from a chat the owner didn't place the lead in. + yield* writer.stage(orgId, "wake1", personNote("teammate-only", "Said in someone's group")); 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", - ], - ); + assert.include(yield* bare(["show", "main:people/owner-repos.md"]), "two main repos"); + const tree = yield* bare(["ls-tree", "-r", "--name-only", "main"]); + assert.notInclude(tree, "teammate-only"); + assert.notInclude(yield* bare(["show", "main:INDEX.md"]), "teammate-only"); + assert.include(yield* bare(["show", `${shadow}:people/teammate-only.md`]), "someone's group"); }), ), ); + +it.effect( + "a shadow note the default branch also changed or deleted keeps the default branch's", + () => + landingFixture(({ bare, setLevel, notices }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const memory = yield* Memory.Memory; + const vcs = yield* Vcs.VcsProcess; + const shadow = Memory.shadowBranch(agentId); + setLevel("L2"); + const gone = personNote("gone", "Gone soon"); + yield* writer.stage(orgId, "wake0", gone); + yield* writer.commitWakeup(orgId, "wake0", "completed"); + setLevel("L0"); + yield* writer.stage(orgId, "wake1", personNote("sam", "Sam, as the shadow has it")); + yield* writer.stage(orgId, "wake1", personNote("alex", "Alex leads design")); + yield* writer.stage(orgId, "wake1", { + ...gone, + content: gone.content.replace('status: "open"', 'status: "done"'), + }); + yield* beforeCutOver(writer.commitWakeup(orgId, "wake1", "completed")); + setLevel("L2"); + yield* writer.stage(orgId, "wake2", personNote("sam", "Sam, as the default branch has it")); + yield* writer.commitWakeup(orgId, "wake2", "completed"); + // A purge-like deletion on the default branch. + const { writer: checkout } = yield* memory.ensureCheckouts(orgId); + const index = `${checkout}/.git/test-delete-index`; + const git = (args: ReadonlyArray) => + vcs + .run({ + operation: "test.writer", + command: "git", + cwd: checkout, + args, + env: { + GIT_INDEX_FILE: index, + GIT_AUTHOR_NAME: "Fixture Bot", + GIT_AUTHOR_EMAIL: "fixture@example.invalid", + GIT_COMMITTER_NAME: "Fixture Bot", + GIT_COMMITTER_EMAIL: "fixture@example.invalid", + }, + }) + .pipe(Effect.map((r) => r.stdout.trim())); + const before = yield* git(["rev-parse", "refs/heads/main"]); + yield* git(["read-tree", before]); + yield* git(["update-index", "--force-remove", "people/gone.md"]); + const deleted = yield* git([ + "commit-tree", + yield* git(["write-tree"]), + "-p", + before, + "-m", + "purge gone", + ]); + const remote = yield* bare(["rev-parse", "--absolute-git-dir"]); + yield* git(["push", "--", remote, `${deleted}:refs/heads/main`]); + yield* git(["update-ref", "refs/heads/main", deleted, before]); + yield* memory.record(orgId, "main", before, deleted); + + 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.notInclude(yield* bare(["ls-tree", "-r", "--name-only", "main"]), "people/gone.md"); + assert.deepStrictEqual( + notices.filter((notice) => notice.branch === shadow).map((notice) => notice.reason), + [ + "Kept the default branch's people/gone.md, 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 4df403191c8c1..4ad7b68e4f01c 100644 --- a/apps/server/src/kin/memory/MemoryWriter.ts +++ b/apps/server/src/kin/memory/MemoryWriter.ts @@ -307,9 +307,9 @@ export class MemoryWriter extends Context.Service< */ 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. + * Once per live lead, lands the items its shadow branch held when leads began working on the + * default branch and that the default branch lacks: notes written at L0 before then. Where + * both changed an item, or the default branch deleted it, the default branch's stays. */ readonly landShadows: (orgId: KinOrgId) => Effect.Effect; } @@ -1911,10 +1911,29 @@ const make = Effect.gen(function* () { yield* refuseDuringPurge(orgId); const repo = yield* repoFor(orgId); if (mainWrites === "pull_request") yield* refuseOffGitHub(orgId); + // Leads stopped working on their shadow branch when K035 ran; a shadow write since then + // came from a chat the owner didn't place the lead in, so it stays off the default branch. + const [cutOver] = yield* sql<{ at: string }>`SELECT created_at AS "at" + FROM kin_sql_migrations WHERE migration_id = 35`.pipe(toSql); + const cutOverSeconds = Date.parse(`${cutOver?.at.replace(" ", "T")}Z`) / 1000; + if (!Number.isFinite(cutOverSeconds)) return; 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 tip = yield* branchHead(orgId, writer, branch); + const shadowHead = yield* git(orgId, writer, [ + "rev-list", + "-1", + `--before=@${cutOverSeconds}`, + tip, + ]); + const mark = sql`INSERT INTO kin_memory_heads (org_id, branch, head) + VALUES (${orgId}, ${shadowLanded(agentId)}, ${shadowHead || tip}) + ON CONFLICT DO NOTHING`.pipe(toSql, Effect.asVoid); + if (shadowHead === "") { + yield* mark; + continue; + } const shadowFiles = yield* filesAt(orgId, writer, shadowHead); const head = yield* branchHead(orgId, writer, main); const headFiles = yield* filesAt(orgId, writer, head); @@ -1930,7 +1949,8 @@ const make = Effect.gen(function* () { 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))) { + // Changed on the default branch too, deletion included: its version stays. + if (!same(now, baseFiles.get(path))) { kept.push(path); continue; } @@ -1940,9 +1960,6 @@ const make = Effect.gen(function* () { 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, From 96e0a7800bef041317000bb6c53b4c3717953cf2 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Wed, 25 Nov 2026 19:10:54 +0530 Subject: [PATCH 04/13] test(kin): date pre-cut-over shadow commits without reading process.env in Effect code People-change: none Co-Authored-By: Claude Opus 5.5 --- .../src/kin/memory/MemoryWriter.test.ts | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/apps/server/src/kin/memory/MemoryWriter.test.ts b/apps/server/src/kin/memory/MemoryWriter.test.ts index 2fbdf979dcb5b..13020e158e0d8 100644 --- a/apps/server/src/kin/memory/MemoryWriter.test.ts +++ b/apps/server/src/kin/memory/MemoryWriter.test.ts @@ -3,6 +3,7 @@ import { memoryGit } from "./git.ts"; import * as NodeZlib from "node:zlib"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, expect, it } from "@effect/vitest"; +import { vi } from "vite-plus/test"; import { KinAgentId, KinChatId, @@ -1965,7 +1966,11 @@ const landingFixture = ( }) => Effect.Effect< void, E, - Memory.Memory | Writer.MemoryWriter | SqlClient.SqlClient | FileSystem.FileSystem + | Memory.Memory + | Writer.MemoryWriter + | SqlClient.SqlClient + | FileSystem.FileSystem + | Vcs.VcsProcess >, ) => Effect.gen(function* () { @@ -2068,17 +2073,9 @@ const landingFixture = ( // Commits made inside are dated before the cut-over, as an L0 lead's were. const beforeCutOver = (effect: Effect.Effect) => Effect.acquireUseRelease( - Effect.sync(() => { - const previous = process.env.GIT_COMMITTER_DATE; - process.env.GIT_COMMITTER_DATE = "2026-11-01T00:00:00Z"; - return previous; - }), + Effect.sync(() => vi.stubEnv("GIT_COMMITTER_DATE", "2026-11-01T00:00:00Z")), () => effect, - (previous) => - Effect.sync(() => { - if (previous === undefined) delete process.env.GIT_COMMITTER_DATE; - else process.env.GIT_COMMITTER_DATE = previous; - }), + () => Effect.sync(() => vi.unstubAllEnvs()), ); const personNote = (id: string, title: string) => ({ path: `people/${id}.md`, From 6662263fb9b5489a219ef6903c0d1037ad6e1577 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Wed, 25 Nov 2026 20:30:50 +0530 Subject: [PATCH 05/13] fix(kin): land each lead's shadow notes on its own and tell the owner what stayed behind One lead that failed to land stopped every lead after it on every sync. Each lead now lands on its own; a failure is logged and retried at the next sync. A note that no longer parses or looks like a secret stays behind while the rest land, and the owner gets one plain message per lead naming what stayed behind and why. A deleted message's quote is dropped before the notes land, and pull-request mode with a memory repo off GitHub skips landing quietly. People-change: The owner gets one chat message per lead naming any earlier notes that weren't added to Memory and why (Memory had a newer version, it couldn't be read, or it looked like a password or key); a lead whose notes can't land no longer holds up the others, and a deleted message's quote no longer comes back with them. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/memory/MemoryWriter.test.ts | 230 +++++++++++++++--- apps/server/src/kin/memory/MemoryWriter.ts | 157 +++++++----- 2 files changed, 287 insertions(+), 100 deletions(-) diff --git a/apps/server/src/kin/memory/MemoryWriter.test.ts b/apps/server/src/kin/memory/MemoryWriter.test.ts index 13020e158e0d8..685ea41a9c29a 100644 --- a/apps/server/src/kin/memory/MemoryWriter.test.ts +++ b/apps/server/src/kin/memory/MemoryWriter.test.ts @@ -25,6 +25,7 @@ import * as Memory from "./Memory.ts"; import { MemoryConfig } from "./MemoryConfig.ts"; import * as Writer from "./MemoryWriter.ts"; import * as Scan from "./secretScan.ts"; +import * as PullRequests from "./MemoryPullRequests.ts"; import { journalEntry } from "./journal.ts"; import { FIXTURE_QUOTE, FIXTURE_SAID, fixtureItem } from "./__fixtures__/items.ts"; import { authorise, fingerprint, reaches, storedLabels, suggest } from "./sensitivity.ts"; @@ -1962,7 +1963,11 @@ 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 }>; + readonly notices: ReadonlyArray<{ + readonly branch: string; + readonly reason: string; + readonly owner?: string; + }>; }) => Effect.Effect< void, E, @@ -1972,6 +1977,7 @@ const landingFixture = ( | FileSystem.FileSystem | Vcs.VcsProcess >, + options: { readonly offGitHubPullRequests?: boolean } = {}, ) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -1999,7 +2005,7 @@ const landingFixture = ( ]); yield* git(root, ["clone", "--bare", "--", source, remote]); let level: "L0" | "L2" = "L0"; - const notices: Array<{ branch: string; reason: string }> = []; + const notices: Array<{ branch: string; reason: string; owner?: string }> = []; const config = Layer.succeed(MemoryConfig, { baseDirectory: root, directMainPush: true, @@ -2036,6 +2042,11 @@ const landingFixture = ( }), ), Layer.provide(Scan.layer), + Layer.provide( + options.offGitHubPullRequests === true + ? Layer.mock(PullRequests.MemoryPullRequests)({}) + : Layer.empty, + ), ); yield* Effect.gen(function* () { const memory = yield* Memory.Memory; @@ -2089,6 +2100,58 @@ const personNote = (id: string, title: string) => ({ links: [`person:${id}`], }), }); +// Commits onto a recorded branch with no wake-up, as a purge does or as an older Kin could have. +const commitDirectly = ( + bare: (args: ReadonlyArray) => Effect.Effect, + branch: string, + change: { readonly add?: Record; readonly remove?: ReadonlyArray }, + date?: string, +) => + Effect.gen(function* () { + const memory = yield* Memory.Memory; + const vcs = yield* Vcs.VcsProcess; + const fs = yield* FileSystem.FileSystem; + const { writer: checkout } = yield* memory.ensureCheckouts(orgId); + const git = (args: ReadonlyArray) => + vcs + .run({ + operation: "test.writer", + command: "git", + cwd: checkout, + args, + env: { + GIT_INDEX_FILE: `${checkout}/.git/test-direct-index`, + GIT_AUTHOR_NAME: "Fixture Bot", + GIT_AUTHOR_EMAIL: "fixture@example.invalid", + GIT_COMMITTER_NAME: "Fixture Bot", + GIT_COMMITTER_EMAIL: "fixture@example.invalid", + ...(date === undefined ? {} : { GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date }), + }, + }) + .pipe(Effect.map((r) => r.stdout.trim())); + const before = yield* git(["rev-parse", `refs/heads/${branch}`]); + yield* git(["read-tree", before]); + for (const path of change.remove ?? []) yield* git(["update-index", "--force-remove", path]); + for (const [path, content] of Object.entries(change.add ?? {})) { + const blob = `${checkout}/.git/test-direct-blob`; + yield* fs.writeFileString(blob, content); + const sha = yield* git(["hash-object", "-w", "--", blob]); + yield* git(["update-index", "--add", "--cacheinfo", `100644,${sha},${path}`]); + } + const commit = yield* git([ + "commit-tree", + yield* git(["write-tree"]), + "-p", + before, + "-m", + "direct", + ]); + const remote = yield* bare(["rev-parse", "--absolute-git-dir"]); + yield* git(["push", "--", remote, `${commit}:refs/heads/${branch}`]); + yield* git(["update-ref", `refs/heads/${branch}`, commit, before]); + yield* memory.record(orgId, branch, before, commit); + }); +const preCutOver = "2026-11-01T00:00:00Z"; it.effect("an L0 lead's shadow notes land on the default branch and its index, once", () => landingFixture(({ bare, setLevel }) => @@ -2161,8 +2224,6 @@ it.effect( landingFixture(({ bare, setLevel, notices }) => Effect.gen(function* () { const writer = yield* Writer.MemoryWriter; - const memory = yield* Memory.Memory; - const vcs = yield* Vcs.VcsProcess; const shadow = Memory.shadowBranch(agentId); setLevel("L2"); const gone = personNote("gone", "Gone soon"); @@ -2180,39 +2241,7 @@ it.effect( yield* writer.stage(orgId, "wake2", personNote("sam", "Sam, as the default branch has it")); yield* writer.commitWakeup(orgId, "wake2", "completed"); // A purge-like deletion on the default branch. - const { writer: checkout } = yield* memory.ensureCheckouts(orgId); - const index = `${checkout}/.git/test-delete-index`; - const git = (args: ReadonlyArray) => - vcs - .run({ - operation: "test.writer", - command: "git", - cwd: checkout, - args, - env: { - GIT_INDEX_FILE: index, - GIT_AUTHOR_NAME: "Fixture Bot", - GIT_AUTHOR_EMAIL: "fixture@example.invalid", - GIT_COMMITTER_NAME: "Fixture Bot", - GIT_COMMITTER_EMAIL: "fixture@example.invalid", - }, - }) - .pipe(Effect.map((r) => r.stdout.trim())); - const before = yield* git(["rev-parse", "refs/heads/main"]); - yield* git(["read-tree", before]); - yield* git(["update-index", "--force-remove", "people/gone.md"]); - const deleted = yield* git([ - "commit-tree", - yield* git(["write-tree"]), - "-p", - before, - "-m", - "purge gone", - ]); - const remote = yield* bare(["rev-parse", "--absolute-git-dir"]); - yield* git(["push", "--", remote, `${deleted}:refs/heads/main`]); - yield* git(["update-ref", "refs/heads/main", deleted, before]); - yield* memory.record(orgId, "main", before, deleted); + yield* commitDirectly(bare, "main", { remove: ["people/gone.md"] }); yield* writer.landShadows(orgId); assert.include(yield* bare(["show", "main:people/sam.md"]), "as the default branch has it"); @@ -2220,11 +2249,134 @@ it.effect( assert.include(yield* bare(["show", "main:people/alex.md"]), "Alex leads design"); assert.notInclude(yield* bare(["ls-tree", "-r", "--name-only", "main"]), "people/gone.md"); assert.deepStrictEqual( - notices.filter((notice) => notice.branch === shadow).map((notice) => notice.reason), + notices.filter((notice) => notice.branch === shadow).map((notice) => notice.owner), [ - "Kept the default branch's people/gone.md, people/sam.md over this shadow branch's, which still holds its own", + "Some of Lead's earlier notes weren't added to Memory:\n- people/gone.md: Memory already had a newer version, so that one stays.\n- people/sam.md: Memory already had a newer version, so that one stays.", ], ); }), ), ); + +it.effect("one lead that cannot land leaves the next lead's notes landing", () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const sql = yield* SqlClient.SqlClient; + const at = "2026-11-08T00:00:00.000Z"; + // Sorts first, and its recorded shadow branch is missing from the checkout. + yield* sql`INSERT INTO kin_agents (agent_id, org_id, display_name, role, owner_person_id, created_at) VALUES ('a-lead', ${orgId}, 'Ada', 'lead', 'owner', ${at})`; + yield* sql`INSERT INTO kin_leads (agent_id, org_id, name, level, level_since, models_json, worker_projects_json, owner_chat_id) + VALUES ('a-lead', ${orgId}, 'Ada', 'L0', 0, '{}', '[]', 'owner-chat')`; + yield* sql`INSERT INTO kin_memory_heads (org_id, branch, head) + VALUES (${orgId}, 'kin/shadow/a-lead', ${yield* bare(["rev-parse", "main"])})`; + yield* writer.stage(orgId, "wake0", personNote("owner-repos", "The owner's two main repos")); + yield* beforeCutOver(writer.commitWakeup(orgId, "wake0", "completed")); + + yield* writer.landShadows(orgId); + assert.include(yield* bare(["show", "main:people/owner-repos.md"]), "two main repos"); + const marked = yield* sql<{ branch: string }>`SELECT branch FROM kin_memory_heads + WHERE org_id = ${orgId} AND branch LIKE 'kin/shadow-landed/%' ORDER BY branch`; + assert.deepStrictEqual( + marked.map((row) => row.branch), + [`kin/shadow-landed/${agentId}`], + ); + }), + ), +); + +it.effect("the owner is told which shadow notes stayed behind and why, once", () => + landingFixture(({ bare, notices }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const shadow = Memory.shadowBranch(agentId); + const token = ["gh", "p_"].join("") + "aB3dE6gH9jK2mN5pQ8sT1vW4yZ7cF0iL3oR6"; + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* beforeCutOver(writer.commitWakeup(orgId, "wake0", "completed")); + const key = personNote("key", "The deploy key"); + yield* commitDirectly( + bare, + shadow, + { + add: { + "people/broken.md": "Not a note any more\n", + [key.path]: key.content.replace("Invented fixture body.", `Deploy with ${token}`), + }, + }, + preCutOver, + ); + + yield* writer.landShadows(orgId); + assert.include(yield* bare(["show", "main:people/alex.md"]), "Alex leads design"); + const tree = yield* bare(["ls-tree", "-r", "--name-only", "main"]); + assert.notInclude(tree, "people/broken.md"); + assert.notInclude(tree, "people/key.md"); + const told = notices.filter((notice) => notice.branch === shadow); + assert.deepStrictEqual( + told.map((notice) => notice.owner), + [ + "Some of Lead's earlier notes weren't added to Memory:\n- people/broken.md: it couldn't be read.\n- people/key.md: it looked like it held a password or key.", + ], + ); + assert.notInclude(JSON.stringify(notices), "aB3dE6gH9jK2mN5pQ8sT1vW4yZ7cF0iL3oR6"); + + const landed = yield* bare(["rev-parse", "main"]); + yield* writer.landShadows(orgId); + assert.strictEqual(yield* bare(["rev-parse", "main"]), landed); + assert.lengthOf( + notices.filter((notice) => notice.branch === shadow), + 1, + ); + }), + ), +); + +it.effect("a shadow note lands without the quote of a message deleted since", () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const quoted = fixtureItem({ + id: "sam", + kind: "person", + title: "Sam runs billing", + due: null, + on_due: undefined, + review_by: null, + links: ["person:sam"], + source: "kin:chat:owner-chat:message:deleted-message", + quote: FIXTURE_QUOTE, + }); + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* beforeCutOver(writer.commitWakeup(orgId, "wake0", "completed")); + yield* commitDirectly( + bare, + Memory.shadowBranch(agentId), + { add: { "people/sam.md": quoted } }, + preCutOver, + ); + + yield* writer.landShadows(orgId); + const sam = yield* bare(["show", "main:people/sam.md"]); + assert.include(sam, "Sam runs billing"); + assert.notInclude(sam, FIXTURE_QUOTE); + }), + ), +); + +it.effect("pull-request mode with a memory repo off GitHub skips landing quietly", () => + landingFixture( + ({ bare, notices }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* beforeCutOver(writer.commitWakeup(orgId, "wake0", "completed")); + const before = yield* bare(["rev-parse", "main"]); + const count = notices.length; + + yield* writer.landShadows(orgId); + assert.strictEqual(yield* bare(["rev-parse", "main"]), before); + assert.lengthOf(notices, count); + }), + { offGitHubPullRequests: true }, + ), +); diff --git a/apps/server/src/kin/memory/MemoryWriter.ts b/apps/server/src/kin/memory/MemoryWriter.ts index 4ad7b68e4f01c..2335d0cf4c62d 100644 --- a/apps/server/src/kin/memory/MemoryWriter.ts +++ b/apps/server/src/kin/memory/MemoryWriter.ts @@ -316,6 +316,12 @@ export class MemoryWriter extends Context.Service< >()("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}`; +// Why a shadow note stayed off the default branch, in the owner's words. +const heldWhy = { + newer: "Memory already had a newer version, so that one stays.", + unreadable: "it couldn't be read.", + secret: "it looked like it held a password or key.", +}; const isRepoSlug = Schema.is(RepoSlug); const dreamBranch = /^dream\/\d{4}-\d{2}-\d{2}$/; const folders = [ @@ -1897,8 +1903,8 @@ const make = Effect.gen(function* () { 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 + const pending = yield* sql<{ agentId: string; name: string; branch: string }>`SELECT + l.agent_id AS "agentId", l.name, 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 @@ -1907,10 +1913,14 @@ const make = Effect.gen(function* () { 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; + if ( + mainWrites === "pull_request" && + (yield* refuseOffGitHub(orgId).pipe(Effect.result))._tag === "Failure" + ) + return; const { writer } = yield* validate(orgId); yield* refuseDuringPurge(orgId); const repo = yield* repoFor(orgId); - if (mainWrites === "pull_request") yield* refuseOffGitHub(orgId); // Leads stopped working on their shadow branch when K035 ran; a shadow write since then // came from a chat the owner didn't place the lead in, so it stays off the default branch. const [cutOver] = yield* sql<{ at: string }>`SELECT created_at AS "at" @@ -1919,69 +1929,94 @@ const make = Effect.gen(function* () { if (!Number.isFinite(cutOverSeconds)) return; const same = (a: Buffer | undefined, b: Buffer | undefined) => a === undefined ? b === undefined : b !== undefined && a.equals(b); - for (const { agentId, branch } of pending) { - const tip = yield* branchHead(orgId, writer, branch); - const shadowHead = yield* git(orgId, writer, [ - "rev-list", - "-1", - `--before=@${cutOverSeconds}`, - tip, - ]); - const mark = sql`INSERT INTO kin_memory_heads (org_id, branch, head) - VALUES (${orgId}, ${shadowLanded(agentId)}, ${shadowHead || tip}) - ON CONFLICT DO NOTHING`.pipe(toSql, Effect.asVoid); - if (shadowHead === "") { - yield* mark; - continue; - } - 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; - // Changed on the default branch too, deletion included: its version stays. - if (!same(now, baseFiles.get(path))) { - kept.push(path); - continue; + // A lead that fails is logged and left unmarked, so the next sync retries it alone. + for (const { agentId, name, branch } of pending) + yield* Effect.gen(function* () { + const tip = yield* branchHead(orgId, writer, branch); + const shadowHead = yield* git(orgId, writer, [ + "rev-list", + "-1", + `--before=@${cutOverSeconds}`, + tip, + ]); + const mark = sql`INSERT INTO kin_memory_heads (org_id, branch, head) + VALUES (${orgId}, ${shadowLanded(agentId)}, ${shadowHead || tip}) + ON CONFLICT DO NOTHING`.pipe(toSql, Effect.asVoid); + if (shadowHead === "") return yield* mark; + 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 held: Array<{ path: string | undefined; why: keyof typeof heldWhy }> = []; + 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; + // Changed on the default branch too, deletion included: its version stays. + if (!same(now, baseFiles.get(path))) held.push({ path, why: "newer" }); + else files.set(path, bytes.toString("utf8")); + } + const unquoted = yield* deletedQuotes(orgId, files).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + toSql, + ); + for (const [path, text] of unquoted) files.set(path, text); + const ending: Array = []; + for (const [path, text] of files) { + const parsed = yield* parseFrontMatter(orgId, path, text).pipe(Effect.option); + const findings = yield* scanner.scan({ + orgId, + files: [{ path, content: Buffer.from(text) }], + }); + if (Option.isNone(parsed) || findings.length > 0) { + files.delete(path); + // A secret in the file's name keeps the name out of the owner's chat too. + const named = !findings.some((finding) => finding.path !== path); + held.push({ + path: named ? path : undefined, + why: Option.isNone(parsed) ? "unreadable" : "secret", + }); + } else if (retired(parsed.value.frontMatter)) + ending.push(parsed.value.frontMatter.id); } - 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); - } - if (kept.length > 0) + if (files.size === 0) yield* mark; + else { + 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, + }); + } + if (held.length === 0) return; + const lines = held.map(({ path, why }) => `- ${path ?? "One note"}: ${heldWhy[why]}`); yield* recovery.notify({ orgId, branch, - reason: `Kept the default branch's ${kept.join(", ")} over this shadow branch's, which still holds its own`, + reason: `Left on the shadow branch: ${held.map(({ path, why }) => `${path ?? "[redacted]"} (${why})`).join(", ")}`, + owner: `Some of ${name}'s earlier notes weren't added to Memory:\n${lines.join("\n")}`, }); - 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, - }); - } + }).pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("Kin could not land a lead's shadow notes", { + orgId, + branch, + cause, + }), + ), + ); }), ), ), From 220745ffcc45189d747192cb93b1af9b43956582 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Fri, 27 Nov 2026 16:38:00 +0530 Subject: [PATCH 06/13] fix(kin): land only shadow notes whose origin and base are proven, and keep the owner's notice The one-time landing writes permanent default-branch history, so what it can't verify now stays behind: - The K035 cut-off is strictly earlier: `rev-list --before` takes its own second, so a commit in K035's second no longer lands. - Each note's stored provenance must prove it: this lead's own wake-up or event from before K035 ran here, or a direct chat of only the owner and this lead. A member's word, a shared item, or a chat, wake-up or event this database doesn't know (another host's) stays behind. - No single merge base (none, several, or an error) refuses the lead and leaves it unmarked, so a replaced default branch can't get removed notes back. A note whose id another note already has stays behind. - Quotes stay out of this import: a clear has no lock shared with the writer, so one could land between the check and the push. - The owner's line is a `kin_held_posts` row written in the transaction that records the marker and the new head, keyed per company and lead, so a restart can't lose it; `deliverHeld` posts it on its own, after quiet hours, as `kin-held:shadow-landed::`. - Every file name shown to the owner or logged is secret-scanned first, and the conflict sentences say what happened. People-change: The owner's message about a lead's earlier notes now survives a restart, comes as its own message per lead after quiet hours, never names a file whose name looks like a key, and says "Memory had a different version, so Kin kept it.", "This note was removed from Memory, so Kin left it out.", "It clashes with another note in Memory, so Kin left it out." or "Kin couldn't confirm where it came from, so it left it out."; notes from a member, a group chat or another host, notes at K035's own second, and quotes no longer land, and nothing lands when Memory's history was replaced. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/memory/MemoryWriter.test.ts | 417 +++++++++++++++++- apps/server/src/kin/memory/MemoryWriter.ts | 202 +++++++-- apps/server/src/kin/memory/quoteAccess.ts | 2 +- 3 files changed, 551 insertions(+), 70 deletions(-) diff --git a/apps/server/src/kin/memory/MemoryWriter.test.ts b/apps/server/src/kin/memory/MemoryWriter.test.ts index bd7bc65098873..14230c27dfb20 100644 --- a/apps/server/src/kin/memory/MemoryWriter.test.ts +++ b/apps/server/src/kin/memory/MemoryWriter.test.ts @@ -18,6 +18,7 @@ import * as ConfigProvider from "effect/ConfigProvider"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; import * as Sqlite from "../../persistence/Sqlite.ts"; import * as Persistence from "../persistence/KinPersistence.ts"; import * as Repository from "../chat/KinChatRepository.ts"; @@ -28,6 +29,7 @@ import * as Writer from "./MemoryWriter.ts"; import * as Scan from "./secretScan.ts"; import * as PullRequests from "./MemoryPullRequests.ts"; import { journalEntry } from "./journal.ts"; +import { deliverHeld } from "../triggers/heldDelivery.ts"; import { FIXTURE_QUOTE, FIXTURE_SAID, fixtureItem } from "./__fixtures__/items.ts"; import { authorise, @@ -1985,11 +1987,14 @@ const landingFixture = ( readonly reason: string; readonly owner?: string; }>; + /** Runs `effect` once, inside the next secret scan: in the middle of a landing. */ + readonly duringScan: (effect: Effect.Effect) => void; }) => Effect.Effect< void, E, | Memory.Memory | Writer.MemoryWriter + | Repository.KinChatRepository | SqlClient.SqlClient | FileSystem.FileSystem | Vcs.VcsProcess @@ -2023,6 +2028,25 @@ const landingFixture = ( yield* git(root, ["clone", "--bare", "--", source, remote]); let level: "L0" | "L2" = "L0"; const notices: Array<{ branch: string; reason: string; owner?: string }> = []; + let duringScan: Effect.Effect | undefined; + const scan = Layer.effect( + Scan.KinSecretScan, + Effect.gen(function* () { + const real = yield* Scan.KinSecretScan; + const sql = yield* SqlClient.SqlClient; + return Scan.KinSecretScan.of({ + scan: (input) => + Effect.suspend(() => { + const once = duringScan; + duringScan = undefined; + return once ?? Effect.void; + }).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + Effect.andThen(real.scan(input)), + ), + }); + }), + ).pipe(Layer.provide(Scan.layer)); const config = Layer.succeed(MemoryConfig, { baseDirectory: root, directMainPush: true, @@ -2058,7 +2082,7 @@ const landingFixture = ( }), }), ), - Layer.provide(Scan.layer), + Layer.provide(scan), Layer.provide( options.offGitHubPullRequests === true ? Layer.mock(PullRequests.MemoryPullRequests)({}) @@ -2072,7 +2096,10 @@ const landingFixture = ( 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})`; + // The owner's direct chat with the lead, the one chat a lead was in before K035. + yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, direct_key, last_seq, created_at) VALUES ('owner-chat', ${orgId}, 'direct', 'owner-lead', 0, ${at})`; + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at) VALUES ('owner-in-owner-chat', ${orgId}, 'owner-chat', 'person', 'owner', 'owner', ${at})`; + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, agent_id, role, joined_at) VALUES ('lead-in-owner-chat', ${orgId}, 'owner-chat', 'agent', ${agentId}, 'member', ${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')`; // When K035 ran: leads stopped working on their shadow branch then. @@ -2086,6 +2113,9 @@ const landingFixture = ( }, bare: (args) => git(root, [`--git-dir=${remote}`, ...args]), notices, + duringScan: (effect) => { + duringScan = effect; + }, }); }).pipe(Effect.provide(layer)); }).pipe( @@ -2105,6 +2135,14 @@ const beforeCutOver = (effect: Effect.Effect) => () => effect, () => Effect.sync(() => vi.unstubAllEnvs()), ); +// A wake-up of the lead's own that ran before the cut-over, as its stored row shows, and its commit. +const wokeBeforeCutOver = (writer: Writer.MemoryWriter["Service"], wakeupId: string) => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, status, event_ids) + VALUES (${wakeupId}, ${orgId}, ${agentId}, 'fixture', ${Date.parse(preCutOver)}, 'completed', '[]')`; + return yield* beforeCutOver(writer.commitWakeup(orgId, wakeupId, "completed")); + }); const personNote = (id: string, title: string) => ({ path: `people/${id}.md`, content: fixtureItem({ @@ -2121,7 +2159,12 @@ const personNote = (id: string, title: string) => ({ const commitDirectly = ( bare: (args: ReadonlyArray) => Effect.Effect, branch: string, - change: { readonly add?: Record; readonly remove?: ReadonlyArray }, + change: { + readonly add?: Record; + readonly remove?: ReadonlyArray; + /** A history of its own, as a replaced or recovered branch has. */ + readonly orphan?: boolean; + }, date?: string, ) => Effect.gen(function* () { @@ -2158,17 +2201,30 @@ const commitDirectly = ( const commit = yield* git([ "commit-tree", yield* git(["write-tree"]), - "-p", - before, + ...(change.orphan === true ? [] : ["-p", before]), "-m", "direct", ]); const remote = yield* bare(["rev-parse", "--absolute-git-dir"]); - yield* git(["push", "--", remote, `${commit}:refs/heads/${branch}`]); + yield* git(["push", "--", remote, `+${commit}:refs/heads/${branch}`]); yield* git(["update-ref", `refs/heads/${branch}`, commit, before]); yield* memory.record(orgId, branch, before, commit); }); const preCutOver = "2026-11-01T00:00:00Z"; +// What the owner will be told, one held line per lead (`deliverHeld` posts it). +const toldOwner = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + return yield* sql<{ holdId: string; chatId: string; kind: string; body: string }>`SELECT + hold_id AS "holdId", chat_id AS "chatId", kind, body FROM kin_held_posts + WHERE kind LIKE 'kin-memory:shadow-landed:%' ORDER BY kind`; +}); +const landedMarks = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const rows = yield* sql<{ branch: string; head: string }>`SELECT branch, head + FROM kin_memory_heads WHERE org_id = ${orgId} AND branch LIKE 'kin/shadow-landed/%' + ORDER BY branch`; + return rows.map((row) => row.branch); +}); it.effect("an L0 lead's shadow notes land on the default branch and its index, once", () => landingFixture(({ bare, setLevel }) => @@ -2182,7 +2238,7 @@ it.effect("an L0 lead's shadow notes land on the default branch and its index, o assert.strictEqual(yield* main(), untouched); yield* writer.stage(orgId, "wake0", personNote("owner-repos", "The owner's two main repos")); - yield* beforeCutOver(writer.commitWakeup(orgId, "wake0", "completed")); + yield* wokeBeforeCutOver(writer, "wake0"); assert.include(yield* bare(["show", `${shadow}:INDEX.md`]), "owner-repos"); assert.notInclude(yield* bare(["show", "main:INDEX.md"]), "owner-repos"); @@ -2220,7 +2276,7 @@ it.effect("a shadow note written after the cut-over stays off the default branch const writer = yield* Writer.MemoryWriter; const shadow = Memory.shadowBranch(agentId); yield* writer.stage(orgId, "wake0", personNote("owner-repos", "The owner's two main repos")); - yield* beforeCutOver(writer.commitWakeup(orgId, "wake0", "completed")); + yield* wokeBeforeCutOver(writer, "wake0"); // After the cut-over, an L0 write comes from a chat the owner didn't place the lead in. yield* writer.stage(orgId, "wake1", personNote("teammate-only", "Said in someone's group")); yield* writer.commitWakeup(orgId, "wake1", "completed"); @@ -2238,7 +2294,7 @@ it.effect("a shadow note written after the cut-over stays off the default branch it.effect( "a shadow note the default branch also changed or deleted keeps the default branch's", () => - landingFixture(({ bare, setLevel, notices }) => + landingFixture(({ bare, setLevel }) => Effect.gen(function* () { const writer = yield* Writer.MemoryWriter; const shadow = Memory.shadowBranch(agentId); @@ -2253,7 +2309,7 @@ it.effect( ...gone, content: gone.content.replace('status: "open"', 'status: "done"'), }); - yield* beforeCutOver(writer.commitWakeup(orgId, "wake1", "completed")); + yield* wokeBeforeCutOver(writer, "wake1"); setLevel("L2"); yield* writer.stage(orgId, "wake2", personNote("sam", "Sam, as the default branch has it")); yield* writer.commitWakeup(orgId, "wake2", "completed"); @@ -2266,9 +2322,9 @@ it.effect( assert.include(yield* bare(["show", "main:people/alex.md"]), "Alex leads design"); assert.notInclude(yield* bare(["ls-tree", "-r", "--name-only", "main"]), "people/gone.md"); assert.deepStrictEqual( - notices.filter((notice) => notice.branch === shadow).map((notice) => notice.owner), + (yield* toldOwner).map((row) => row.body), [ - "Some of Lead's earlier notes weren't added to Memory:\n- people/gone.md: Memory already had a newer version, so that one stays.\n- people/sam.md: Memory already had a newer version, so that one stays.", + "Some of Lead's earlier notes weren't added to Memory:\n- people/gone.md: This note was removed from Memory, so Kin left it out.\n- people/sam.md: Memory had a different version, so Kin kept it.", ], ); }), @@ -2288,7 +2344,7 @@ it.effect("one lead that cannot land leaves the next lead's notes landing", () = yield* sql`INSERT INTO kin_memory_heads (org_id, branch, head) VALUES (${orgId}, 'kin/shadow/a-lead', ${yield* bare(["rev-parse", "main"])})`; yield* writer.stage(orgId, "wake0", personNote("owner-repos", "The owner's two main repos")); - yield* beforeCutOver(writer.commitWakeup(orgId, "wake0", "completed")); + yield* wokeBeforeCutOver(writer, "wake0"); yield* writer.landShadows(orgId); assert.include(yield* bare(["show", "main:people/owner-repos.md"]), "two main repos"); @@ -2309,7 +2365,7 @@ it.effect("the owner is told which shadow notes stayed behind and why, once", () const shadow = Memory.shadowBranch(agentId); const token = ["gh", "p_"].join("") + "aB3dE6gH9jK2mN5pQ8sT1vW4yZ7cF0iL3oR6"; yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); - yield* beforeCutOver(writer.commitWakeup(orgId, "wake0", "completed")); + yield* wokeBeforeCutOver(writer, "wake0"); const key = personNote("key", "The deploy key"); yield* commitDirectly( bare, @@ -2328,11 +2384,10 @@ it.effect("the owner is told which shadow notes stayed behind and why, once", () const tree = yield* bare(["ls-tree", "-r", "--name-only", "main"]); assert.notInclude(tree, "people/broken.md"); assert.notInclude(tree, "people/key.md"); - const told = notices.filter((notice) => notice.branch === shadow); assert.deepStrictEqual( - told.map((notice) => notice.owner), + (yield* toldOwner).map((row) => row.body), [ - "Some of Lead's earlier notes weren't added to Memory:\n- people/broken.md: it couldn't be read.\n- people/key.md: it looked like it held a password or key.", + "Some of Lead's earlier notes weren't added to Memory:\n- people/broken.md: It couldn't be read.\n- people/key.md: It looked like it held a password or key.", ], ); assert.notInclude(JSON.stringify(notices), "aB3dE6gH9jK2mN5pQ8sT1vW4yZ7cF0iL3oR6"); @@ -2340,9 +2395,34 @@ it.effect("the owner is told which shadow notes stayed behind and why, once", () const landed = yield* bare(["rev-parse", "main"]); yield* writer.landShadows(orgId); assert.strictEqual(yield* bare(["rev-parse", "main"]), landed); - assert.lengthOf( - notices.filter((notice) => notice.branch === shadow), - 1, + assert.lengthOf(yield* toldOwner, 1); + }), + ), +); + +it.effect("a held note whose name looks like a key is not named to the owner or in the log", () => + landingFixture(({ bare, notices }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const shadow = Memory.shadowBranch(agentId); + const token = ["gh", "p_"].join("") + "aB3dE6gH9jK2mN5pQ8sT1vW4yZ7cF0iL3oR6"; + const legacy = `people/${token}.md`; + // A file from before notes had front matter: no index lists it, so no commit is refused. + yield* commitDirectly(bare, "main", { add: { [legacy]: "Legacy text\n" } }); + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + yield* commitDirectly(bare, shadow, { add: { [legacy]: "The shadow's text\n" } }, preCutOver); + yield* commitDirectly(bare, "main", { add: { [legacy]: "Memory's text\n" } }); + + yield* writer.landShadows(orgId); + assert.notInclude(JSON.stringify(notices), token); + assert.include(yield* bare(["show", "main:people/alex.md"]), "Alex leads design"); + assert.strictEqual(yield* bare(["show", `main:${legacy}`]), "Memory's text"); + assert.deepStrictEqual( + (yield* toldOwner).map((row) => row.body), + [ + "Some of Lead's earlier notes weren't added to Memory:\n- One note: Memory had a different version, so Kin kept it.", + ], ); }), ), @@ -2364,7 +2444,7 @@ it.effect("a shadow note lands without the quote of a message deleted since", () quote: FIXTURE_QUOTE, }); yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); - yield* beforeCutOver(writer.commitWakeup(orgId, "wake0", "completed")); + yield* wokeBeforeCutOver(writer, "wake0"); yield* commitDirectly( bare, Memory.shadowBranch(agentId), @@ -2380,18 +2460,311 @@ it.effect("a shadow note lands without the quote of a message deleted since", () ), ); +it.effect("a chat cleared while a shadow lands leaves no quote of it on the default branch", () => + landingFixture(({ bare, duringScan }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const sql = yield* SqlClient.SqlClient; + const chats = yield* Repository.KinChatRepository; + yield* sql`INSERT INTO kin_messages (message_id, org_id, chat_id, seq, author_kind, author_person_id, + author_member_id, author_role, kind, body, mentions_json, status, created_at) + VALUES ('m-said', ${orgId}, 'owner-chat', 1, 'human', 'owner', 'owner-in-owner-chat', 'owner', + 'text', ${FIXTURE_SAID}, '[]', 'posted', '2026-10-30T00:00:00.000Z')`; + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + yield* commitDirectly( + bare, + Memory.shadowBranch(agentId), + { + add: { + "people/sam.md": fixtureItem({ + id: "sam", + kind: "person", + title: "Sam runs billing", + due: null, + on_due: undefined, + review_by: null, + links: ["person:sam"], + source: "kin:chat:owner-chat:message:m-said", + quote: FIXTURE_QUOTE, + }), + }, + }, + preCutOver, + ); + // The owner clears the chat after the landing began, before it commits. + duringScan( + chats + .clearChat({ + orgId, + chatId: KinChatId.make("owner-chat"), + clearedAt: "2026-11-12T00:00:00.000Z", + clearedAtMs: 0, + }) + .pipe(Effect.asVoid, Effect.orDie), + ); + + yield* writer.landShadows(orgId); + assert.include(yield* bare(["show", "main:people/sam.md"]), "Sam runs billing"); + assert.lengthOf( + yield* sql`SELECT 1 FROM kin_messages WHERE org_id = ${orgId} AND chat_id = 'owner-chat'`, + 0, + ); + assert.notInclude(yield* bare(["log", "-p", "main"]), FIXTURE_QUOTE); + }), + ), +); + +it.effect("a shadow commit at the cut-over's own second stays off the default branch", () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + // K035 ran at 12:42:41; this commit's second is the same one. + yield* commitDirectly( + bare, + Memory.shadowBranch(agentId), + { add: { "people/same-second.md": personNote("same-second", "Said that second").content } }, + "2026-11-10T12:42:41Z", + ); + + yield* writer.landShadows(orgId); + const tree = yield* bare(["ls-tree", "-r", "--name-only", "main"]); + assert.include(tree, "people/alex.md"); + assert.notInclude(tree, "people/same-second.md"); + }), + ), +); + +it.effect("a shadow note not from the owner in their own chat with the lead stays behind", () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const sql = yield* SqlClient.SqlClient; + const at = "2026-11-08T00:00:00.000Z"; + yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, created_at) VALUES ('sam', ${orgId}, 'sam', 'Sam', ${at})`; + yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, last_seq, created_at) VALUES ('group-chat', ${orgId}, 'team_group', 0, ${at})`; + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at) VALUES ('owner-in-group', ${orgId}, 'group-chat', 'person', 'owner', 'owner', ${at})`; + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at) VALUES ('sam-in-group', ${orgId}, 'group-chat', 'person', 'sam', 'member', ${at})`; + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, agent_id, role, joined_at) VALUES ('lead-in-group', ${orgId}, 'group-chat', 'agent', ${agentId}, 'member', ${at})`; + const note = (id: string, fields: Record) => + fixtureItem({ + id, + kind: "person", + title: `About ${id}`, + due: null, + on_due: undefined, + review_by: null, + links: [`person:${id}`], + ...fields, + }); + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + yield* commitDirectly( + bare, + Memory.shadowBranch(agentId), + { + add: { + "people/owners.md": note("owners", { source: "kin:chat:owner-chat:message:m1" }), + "people/members.md": note("members", { + source: "kin:chat:owner-chat:message:m2", + said_by: "sam", + trust: "member", + }), + "people/grouped.md": note("grouped", { source: "kin:chat:group-chat:message:m3" }), + "people/elsewhere.md": note("elsewhere", { + source: "kin:chat:chat-on-another-host:message:m4", + }), + "people/woken.md": note("woken", { + source: "wakeup:not-run-here", + said_by: agentId, + trust: "agent", + }), + }, + }, + preCutOver, + ); + + yield* writer.landShadows(orgId); + const tree = yield* bare(["ls-tree", "-r", "--name-only", "main"]); + assert.include(tree, "people/owners.md"); + for (const left of ["members", "grouped", "elsewhere", "woken"]) + assert.notInclude(tree, `people/${left}.md`); + assert.deepStrictEqual( + (yield* toldOwner).map((row) => row.body), + [ + "Some of Lead's earlier notes weren't added to Memory:\n- people/elsewhere.md: Kin couldn't confirm where it came from, so it left it out.\n- people/grouped.md: Kin couldn't confirm where it came from, so it left it out.\n- people/members.md: Kin couldn't confirm where it came from, so it left it out.\n- people/woken.md: Kin couldn't confirm where it came from, so it left it out.", + ], + ); + }), + ), +); + +it.effect("a shadow with no single base shared with the default branch lands nothing", () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const shadow = Memory.shadowBranch(agentId); + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + // The default branch was replaced since: what it removed on purpose must not come back. + yield* commitDirectly(bare, "main", { orphan: true }); + const before = yield* bare(["rev-parse", "main"]); + + yield* writer.landShadows(orgId); + assert.strictEqual(yield* bare(["rev-parse", "main"]), before); + assert.notInclude(yield* bare(["ls-tree", "-r", "--name-only", "main"]), "people/alex.md"); + assert.include(yield* bare(["show", `${shadow}:people/alex.md`]), "Alex leads design"); + assert.deepStrictEqual(yield* landedMarks, []); + }), + ), +); + +it.effect("a shadow note with the id of another note on the default branch stays behind", () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const memory = yield* Memory.Memory; + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + yield* commitDirectly(bare, "main", { + add: { + "people/onboarding.md": personNote("onboarding", "Onboarding, as a person").content, + }, + }); + yield* commitDirectly( + bare, + Memory.shadowBranch(agentId), + { + add: { + "claims/onboarding.md": fixtureItem({ + id: "onboarding", + kind: "claim", + title: "Onboarding, as a claim", + due: null, + on_due: undefined, + review_by: null, + links: ["person:onboarding"], + source: "kin:chat:owner-chat:message:m1", + }), + }, + }, + preCutOver, + ); + + yield* writer.landShadows(orgId); + const tree = yield* bare(["ls-tree", "-r", "--name-only", "main"]); + assert.include(tree, "people/alex.md"); + assert.notInclude(tree, "claims/onboarding.md"); + yield* memory.syncCheckout(orgId); + assert.strictEqual( + (yield* memory.readItem(orgId, KinMemoryItemId.make("onboarding"))).head.title, + "Onboarding, as a person", + ); + assert.deepStrictEqual( + (yield* toldOwner).map((row) => row.body), + [ + "Some of Lead's earlier notes weren't added to Memory:\n- claims/onboarding.md: It clashes with another note in Memory, so Kin left it out.", + ], + ); + }), + ), +); + +it.effect("each lead's note of what stayed behind survives a restart and posts on its own", () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const memory = yield* Memory.Memory; + const sql = yield* SqlClient.SqlClient; + const vcs = yield* Vcs.VcsProcess; + const at = "2026-11-08T00:00:00.000Z"; + yield* TestClock.setTime(Date.parse("2026-11-12T12:00:00.000Z")); + yield* sql`INSERT INTO kin_agents (agent_id, org_id, display_name, role, owner_person_id, created_at) VALUES ('b-lead', ${orgId}, 'Bea', 'lead', 'owner', ${at})`; + yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, direct_key, last_seq, created_at) VALUES ('bea-chat', ${orgId}, 'direct', 'owner-bea', 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 ('b-lead', ${orgId}, 'Bea', 'L0', 0, '{}', '[]', 'bea-chat')`; + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + // Bea's shadow branch, from the default branch as each lead's began. + const { writer: checkout } = yield* memory.ensureCheckouts(orgId); + const main = yield* bare(["rev-parse", "main"]); + yield* vcs.run({ + operation: "test.writer", + command: "git", + cwd: checkout, + args: ["update-ref", "refs/heads/kin/shadow/b-lead", main], + }); + yield* bare(["update-ref", "refs/heads/kin/shadow/b-lead", main]); + yield* sql`INSERT INTO kin_memory_heads (org_id, branch, head) + VALUES (${orgId}, 'kin/shadow/b-lead', ${main})`; + for (const branch of [Memory.shadowBranch(agentId), "kin/shadow/b-lead"]) + yield* commitDirectly( + bare, + branch, + { add: { "people/broken.md": "Not a note\n" } }, + preCutOver, + ); + + yield* writer.landShadows(orgId); + assert.deepStrictEqual(yield* landedMarks, [ + "kin/shadow-landed/b-lead", + `kin/shadow-landed/${agentId}`, + ]); + // A restart here, before anything posted: the lines wait in what was stored with the marks. + const posted: Array<{ messageId: string; chatId: string; body: string }> = []; + const chat = (fail: boolean) => ({ + dismissArrival: () => Effect.die("No arrival note"), + notice: (input: { + readonly messageId: string; + readonly chatId: string; + readonly body: string; + }) => + fail + ? Effect.die("The server stopped") + : Effect.sync(() => posted.push(input)).pipe(Effect.as({} as never)), + }); + yield* Effect.exit(deliverHeld(orgId, chat(true))); + assert.lengthOf(posted, 0); + yield* writer.landShadows(orgId); + yield* deliverHeld(orgId, chat(false)); + yield* deliverHeld(orgId, chat(false)); + assert.deepStrictEqual( + posted.map(({ messageId, chatId, body }) => ({ messageId, chatId, body })), + [ + { + messageId: `kin-held:shadow-landed:${orgId}:b-lead`, + chatId: "bea-chat", + body: "Some of Bea's earlier notes weren't added to Memory:\n- people/broken.md: It couldn't be read.", + }, + { + messageId: `kin-held:shadow-landed:${orgId}:${agentId}`, + chatId: "owner-chat", + body: "Some of Lead's earlier notes weren't added to Memory:\n- people/broken.md: It couldn't be read.", + }, + ], + ); + }), + ), +); + it.effect("pull-request mode with a memory repo off GitHub skips landing quietly", () => landingFixture( ({ bare, notices }) => Effect.gen(function* () { const writer = yield* Writer.MemoryWriter; yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); - yield* beforeCutOver(writer.commitWakeup(orgId, "wake0", "completed")); + yield* wokeBeforeCutOver(writer, "wake0"); + const memory = yield* Memory.Memory; const before = yield* bare(["rev-parse", "main"]); + const anchored = yield* memory.anchor(orgId, "main"); const count = notices.length; yield* writer.landShadows(orgId); assert.strictEqual(yield* bare(["rev-parse", "main"]), before); + assert.strictEqual(yield* memory.anchor(orgId, "main"), anchored); + assert.deepStrictEqual(yield* landedMarks, []); assert.lengthOf(notices, count); }), { offGitHubPullRequests: true }, diff --git a/apps/server/src/kin/memory/MemoryWriter.ts b/apps/server/src/kin/memory/MemoryWriter.ts index 8483d040de4c2..d1ab05818c94f 100644 --- a/apps/server/src/kin/memory/MemoryWriter.ts +++ b/apps/server/src/kin/memory/MemoryWriter.ts @@ -57,7 +57,7 @@ import { journalEntry, MemoryJournalError, type JournalContext } from "./journal import { QUOTE_MISSING, quoteRefusal } from "./keeping.ts"; import { kinShapeFailure } from "./lint.ts"; import { KinSecretScan, KinSecretScanError } from "./secretScan.ts"; -import { deletedQuotes } from "./quoteAccess.ts"; +import { CHAT_SOURCE, deletedQuotes, withoutQuote } from "./quoteAccess.ts"; import { retireLabels } from "./sensitivity.ts"; import * as MemoryLander from "./MemoryLander.ts"; import { MemoryPullRequests } from "./MemoryPullRequests.ts"; @@ -312,19 +312,25 @@ export class MemoryWriter extends Context.Service< readonly stripQuotes: (orgId: KinOrgId) => Effect.Effect; /** * Once per live lead, lands the items its shadow branch held when leads began working on the - * default branch and that the default branch lacks: notes written at L0 before then. Where - * both changed an item, or the default branch deleted it, the default branch's stays. + * default branch and that the default branch lacks: notes written at L0 before then whose + * stored origin proves it (`provenOrigin`). Where both changed an item, or the default + * branch deleted it, the default branch's stays. Quotes stay behind. */ 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}`; +// The held line (`deliverHeld`) telling the owner what of a lead's shadow stayed behind. +const shadowNoticeKind = (agentId: string) => `kin-memory:shadow-landed:${agentId}`; // Why a shadow note stayed off the default branch, in the owner's words. const heldWhy = { - newer: "Memory already had a newer version, so that one stays.", - unreadable: "it couldn't be read.", - secret: "it looked like it held a password or key.", + different: "Memory had a different version, so Kin kept it.", + removed: "This note was removed from Memory, so Kin left it out.", + unreadable: "It couldn't be read.", + secret: "It looked like it held a password or key.", + unverified: "Kin couldn't confirm where it came from, so it left it out.", + clash: "It clashes with another note in Memory, so Kin left it out.", }; const isRepoSlug = Schema.is(RepoSlug); const dreamBranch = /^dream\/\d{4}-\d{2}-\d{2}$/; @@ -1943,8 +1949,14 @@ const make = Effect.gen(function* () { Effect.gen(function* () { const main = config.defaultBranch ?? "main"; const toSql = Effect.mapError(toPersistenceSqlError("MemoryWriter.landShadows")); - const pending = yield* sql<{ agentId: string; name: string; branch: string }>`SELECT - l.agent_id AS "agentId", l.name, h.branch FROM kin_memory_heads h + const pending = yield* sql<{ + agentId: string; + name: string; + branch: string; + owner: string; + ownerChat: string; + }>`SELECT l.agent_id AS "agentId", l.name, h.branch, a.owner_person_id AS owner, + l.owner_chat_id AS "ownerChat" 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 @@ -1969,14 +1981,61 @@ const make = Effect.gen(function* () { if (!Number.isFinite(cutOverSeconds)) return; const same = (a: Buffer | undefined, b: Buffer | undefined) => a === undefined ? b === undefined : b !== undefined && a.equals(b); + const parsedAt = (path: string, text: string) => + parseFrontMatter(orgId, path, text).pipe( + Effect.map(({ frontMatter }) => frontMatter), + Effect.option, + ); + // History can't show which host or chat a shadow write came from, so each note's stored + // provenance must: this lead's own wake-up or event from before K035 ran here, or a + // direct chat of only the owner and this lead. Never a member's word. + const provenOrigin = Effect.fn("MemoryWriter.landShadows.provenOrigin")(function* ( + agentId: string, + owner: string, + item: MemoryItemFrontMatter, + ) { + if (item.trust === "member" || item.shared_from !== undefined) return false; + const cutOverMs = cutOverSeconds * 1000; + const wakeup = /^wakeup:(.+)$/.exec(item.source)?.[1]; + const event = /^kin:event:(.+)$/.exec(item.source)?.[1]; + const cited = CHAT_SOURCE.exec(item.source)?.[1]; + if (wakeup === undefined && event === undefined && cited === undefined) return false; + if (wakeup !== undefined) { + const [ran] = yield* sql`SELECT 1 FROM kin_wakeups WHERE org_id = ${orgId} + AND wakeup_id = ${wakeup} AND agent_id = ${agentId} + AND started_at < ${cutOverMs}`.pipe(toSql); + if (ran === undefined) return false; + } + if (event !== undefined) { + const [queued] = yield* sql`SELECT 1 FROM kin_events WHERE org_id = ${orgId} + AND event_id = ${event} AND agent_id = ${agentId} + AND queued_at < ${cutOverMs}`.pipe(toSql); + if (queued === undefined) return false; + } + const chats = [...new Set([item.chat, cited].filter((chat) => chat !== undefined))]; + if (chats.length === 0) return true; + const direct = yield* sql<{ chatId: string }>`SELECT c.chat_id AS "chatId" + FROM kin_chats c WHERE c.org_id = ${orgId} AND c.kind = 'direct' + AND c.chat_id IN ${sql.in(chats)} + AND EXISTS (SELECT 1 FROM kin_chat_members m WHERE m.org_id = c.org_id + AND m.chat_id = c.chat_id AND m.agent_id = ${agentId}) + AND EXISTS (SELECT 1 FROM kin_chat_members m WHERE m.org_id = c.org_id + AND m.chat_id = c.chat_id AND m.person_id = ${owner}) + AND NOT EXISTS (SELECT 1 FROM kin_chat_members m WHERE m.org_id = c.org_id + AND m.chat_id = c.chat_id AND m.principal_kind = 'person' + AND m.person_id <> ${owner}) + ORDER BY c.chat_id`.pipe(toSql); + return direct.length === chats.length; + }); // A lead that fails is logged and left unmarked, so the next sync retries it alone. - for (const { agentId, name, branch } of pending) + for (const { agentId, name, branch, owner, ownerChat } of pending) yield* Effect.gen(function* () { const tip = yield* branchHead(orgId, writer, branch); + // `--before` takes its own second, and a commit that second may be after K035 ran. const shadowHead = yield* git(orgId, writer, [ "rev-list", "-1", - `--before=@${cutOverSeconds}`, + `--before=@${Math.ceil(cutOverSeconds) - 1}`, tip, ]); const mark = sql`INSERT INTO kin_memory_heads (org_id, branch, head) @@ -1986,45 +2045,96 @@ const make = Effect.gen(function* () { 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); + // Without one base both share, a note the default branch removed reads as new. + const bases = (yield* git(orgId, writer, ["merge-base", "--all", head, shadowHead])) + .split("\n") + .filter((line) => line !== ""); + if (bases.length !== 1) + return yield* new MemorySyncConflict({ + orgId, + operation: "landShadows", + reason: "The shadow branch and the default branch share no single base", + }); + const baseFiles = yield* filesAt(orgId, writer, bases[0]!); const files = new Map(); - const held: Array<{ path: string | undefined; why: keyof typeof heldWhy }> = []; + const held: Array<{ path: string; why: keyof typeof heldWhy }> = []; 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; + const was = baseFiles.get(path); + if (same(was, bytes) || same(now, bytes)) continue; // Changed on the default branch too, deletion included: its version stays. - if (!same(now, baseFiles.get(path))) held.push({ path, why: "newer" }); - else files.set(path, bytes.toString("utf8")); + if (!same(now, was)) + held.push({ path, why: now === undefined ? "removed" : "different" }); + // A quote can't be checked against a clear that runs while this lands. + else files.set(path, withoutQuote(bytes.toString("utf8"))); } - const unquoted = yield* deletedQuotes(orgId, files).pipe( - Effect.provideService(SqlClient.SqlClient, sql), - toSql, - ); - for (const [path, text] of unquoted) files.set(path, text); - const ending: Array = []; + const items = new Map(); for (const [path, text] of files) { - const parsed = yield* parseFrontMatter(orgId, path, text).pipe(Effect.option); + const item = yield* parsedAt(path, text); + if (Option.isNone(item)) held.push({ path, why: "unreadable" }); + else if ( + (yield* scanner.scan({ orgId, files: [{ path, content: Buffer.from(text) }] })) + .length > 0 + ) + held.push({ path, why: "secret" }); + else if (!(yield* provenOrigin(agentId, owner, item.value))) + held.push({ path, why: "unverified" }); + else { + items.set(path, item.value); + continue; + } + files.delete(path); + } + // Two notes with one id fail every read of it (`MemoryDuplicateId`). + const paths = new Map>(); + const claim = (id: string, path: string) => + paths.set(id, [...(paths.get(id) ?? []), path]); + for (const [path, bytes] of headFiles) + if (!files.has(path) && folders.some((folder) => path.startsWith(`${folder}/`))) { + const item = yield* parsedAt(path, bytes.toString("utf8")); + if (Option.isSome(item)) claim(item.value.id, path); + } + for (const [path, item] of items) claim(item.id, path); + const ending: Array = []; + for (const [path, item] of items) + if ((paths.get(item.id)?.length ?? 0) > 1) { + files.delete(path); + held.push({ path, why: "clash" }); + } else if (retired(item)) ending.push(item.id); + // A name the scan flags stays out of the owner's chat and the log. + const shown: Array<{ path: string | undefined; why: keyof typeof heldWhy }> = []; + for (const { path, why } of held.toSorted((a, b) => a.path.localeCompare(b.path))) { const findings = yield* scanner.scan({ orgId, - files: [{ path, content: Buffer.from(text) }], + files: [{ path, content: new Uint8Array() }], }); - if (Option.isNone(parsed) || findings.length > 0) { - files.delete(path); - // A secret in the file's name keeps the name out of the owner's chat too. - const named = !findings.some((finding) => finding.path !== path); - held.push({ - path: named ? path : undefined, - why: Option.isNone(parsed) ? "unreadable" : "secret", - }); - } else if (retired(parsed.value.frontMatter)) - ending.push(parsed.value.frontMatter.id); + shown.push({ path: findings.length > 0 ? undefined : path, why }); } - if (files.size === 0) yield* mark; + const lines = shown.map( + ({ path, why }) => `- ${path ?? "One note"}: ${heldWhy[why]}`, + ); + // Kept with the marker, so a restart can't lose it; `deliverHeld` posts it once, + // on its own, under an id of its own, after any quiet hours. + const at = yield* Clock.currentTimeMillis; + const told = + shown.length === 0 + ? Effect.void + : sql`INSERT INTO kin_held_posts (hold_id, org_id, chat_id, person_id, kind, + body, audience, held_at, deliver_at) + VALUES (${`shadow-landed:${orgId}:${agentId}`}, ${orgId}, ${ownerChat}, + ${owner}, ${shadowNoticeKind(agentId)}, + ${`Some of ${name}'s earlier notes weren't added to Memory:\n${lines.join("\n")}`}, + 'owner', ${at}, ${at}) + ON CONFLICT DO NOTHING`.pipe(toSql, Effect.asVoid); + const landed = mark.pipe(Effect.andThen(told)); + if (files.size === 0) + yield* sql.withTransaction(landed).pipe( + Effect.catchTags({ + SqlError: (cause) => + Effect.fail(toPersistenceSqlError("MemoryWriter.landShadows")(cause)), + }), + ); else { yield* endSharing(orgId, ending); yield* ownerCommit(orgId, { @@ -2035,17 +2145,15 @@ const make = Effect.gen(function* () { headFiles, files, message: `kin(${agentId}): land notes kept at L0\n\nKin-Shadow-Landed: ${shadowHead}\n`, - landed: () => mark, + landed: () => landed, }); } - if (held.length === 0) return; - const lines = held.map(({ path, why }) => `- ${path ?? "One note"}: ${heldWhy[why]}`); - yield* recovery.notify({ - orgId, - branch, - reason: `Left on the shadow branch: ${held.map(({ path, why }) => `${path ?? "[redacted]"} (${why})`).join(", ")}`, - owner: `Some of ${name}'s earlier notes weren't added to Memory:\n${lines.join("\n")}`, - }); + if (shown.length > 0) + yield* recovery.notify({ + orgId, + branch, + reason: `Left on the shadow branch: ${shown.map(({ path, why }) => `${path ?? "[redacted]"} (${why})`).join(", ")}`, + }); }).pipe( Effect.catchCauseIf( (cause) => !Cause.hasInterruptsOnly(cause), diff --git a/apps/server/src/kin/memory/quoteAccess.ts b/apps/server/src/kin/memory/quoteAccess.ts index 8593b0d0a5b9b..5a010814efe7e 100644 --- a/apps/server/src/kin/memory/quoteAccess.ts +++ b/apps/server/src/kin/memory/quoteAccess.ts @@ -97,7 +97,7 @@ const quotedFront = (text: string) => { }; /** The item's text with no `quote` in its front matter, every other field as it was. */ -const withoutQuote = (text: string) => { +export const withoutQuote = (text: string) => { const quoted = quotedFront(text); if (quoted === undefined) return text; quoted.doc.delete("quote"); From 7d8a3a617d99179cb789173fa1b3272fdf2d7434 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Fri, 27 Nov 2026 17:35:33 +0530 Subject: [PATCH 07/13] fix(kin): bound chat-cited shadow notes by their message's time, and end sharing only once landed A note citing the owner's chat now lands only when that message is stored and was said before K035 ran; a message that's gone (a cleared chat's included, since clearing deletes the rows and their times) leaves the note behind as unverified. Ending what retired notes were shared as now runs in the transaction that marks the lead landed, so a failed commit leaves it untouched. People-change: The owner's message about a lead's earlier notes now survives a restart, comes as its own message per lead after quiet hours, never names a file whose name looks like a key, and says "Memory had a different version, so Kin kept it.", "This note was removed from Memory, so Kin left it out.", "It clashes with another note in Memory, so Kin left it out." or "Kin couldn't confirm where it came from, so it left it out."; notes from a member, a group chat or another host, notes at K035's own second, notes citing a chat message said after K035 ran or no longer kept (a cleared chat's included), and quotes no longer land, and nothing lands when Memory's history was replaced. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/memory/MemoryWriter.test.ts | 142 +++++++++++++++++- apps/server/src/kin/memory/MemoryWriter.ts | 14 +- 2 files changed, 146 insertions(+), 10 deletions(-) diff --git a/apps/server/src/kin/memory/MemoryWriter.test.ts b/apps/server/src/kin/memory/MemoryWriter.test.ts index 14230c27dfb20..a7732963e9d87 100644 --- a/apps/server/src/kin/memory/MemoryWriter.test.ts +++ b/apps/server/src/kin/memory/MemoryWriter.test.ts @@ -1987,8 +1987,11 @@ const landingFixture = ( readonly reason: string; readonly owner?: string; }>; - /** Runs `effect` once, inside the next secret scan: in the middle of a landing. */ - readonly duringScan: (effect: Effect.Effect) => void; + /** Runs `effect` once, inside the next secret scan `when` picks: in the middle of a landing. */ + readonly duringScan: ( + effect: Effect.Effect, + when?: (paths: ReadonlyArray) => boolean, + ) => void; }) => Effect.Effect< void, E, @@ -2028,7 +2031,12 @@ const landingFixture = ( yield* git(root, ["clone", "--bare", "--", source, remote]); let level: "L0" | "L2" = "L0"; const notices: Array<{ branch: string; reason: string; owner?: string }> = []; - let duringScan: Effect.Effect | undefined; + let duringScan: + | { + readonly effect: Effect.Effect; + readonly when: (paths: ReadonlyArray) => boolean; + } + | undefined; const scan = Layer.effect( Scan.KinSecretScan, Effect.gen(function* () { @@ -2038,8 +2046,10 @@ const landingFixture = ( scan: (input) => Effect.suspend(() => { const once = duringScan; + if (once === undefined || !once.when(input.files.map((file) => file.path))) + return Effect.void; duringScan = undefined; - return once ?? Effect.void; + return once.effect; }).pipe( Effect.provideService(SqlClient.SqlClient, sql), Effect.andThen(real.scan(input)), @@ -2113,8 +2123,8 @@ const landingFixture = ( }, bare: (args) => git(root, [`--git-dir=${remote}`, ...args]), notices, - duringScan: (effect) => { - duringScan = effect; + duringScan: (effect, when = () => true) => { + duringScan = { effect, when }; }, }); }).pipe(Effect.provide(layer)); @@ -2211,6 +2221,16 @@ const commitDirectly = ( yield* memory.record(orgId, branch, before, commit); }); const preCutOver = "2026-11-01T00:00:00Z"; +// The owner's message in their chat with the lead, as stored when it was said. +let saidSeq = 100; +const said = (messageId: string, createdAt: string, status = "posted") => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO kin_messages (message_id, org_id, chat_id, seq, author_kind, + author_person_id, author_member_id, author_role, kind, body, mentions_json, status, created_at) + VALUES (${messageId}, ${orgId}, 'owner-chat', ${saidSeq++}, 'human', 'owner', + 'owner-in-owner-chat', 'owner', 'text', ${FIXTURE_SAID}, '[]', ${status}, ${createdAt})`; + }); // What the owner will be told, one held line per lead (`deliverHeld` posts it). const toldOwner = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; @@ -2443,6 +2463,7 @@ it.effect("a shadow note lands without the quote of a message deleted since", () source: "kin:chat:owner-chat:message:deleted-message", quote: FIXTURE_QUOTE, }); + yield* said("deleted-message", "2026-10-30T00:00:00.000Z", "deleted"); yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); yield* wokeBeforeCutOver(writer, "wake0"); yield* commitDirectly( @@ -2492,7 +2513,7 @@ it.effect("a chat cleared while a shadow lands leaves no quote of it on the defa }, preCutOver, ); - // The owner clears the chat after the landing began, before it commits. + // The owner clears the chat after its notes were checked, as the commit is scanned. duringScan( chats .clearChat({ @@ -2502,6 +2523,7 @@ it.effect("a chat cleared while a shadow lands leaves no quote of it on the defa clearedAtMs: 0, }) .pipe(Effect.asVoid, Effect.orDie), + (paths) => paths.includes("INDEX.md"), ); yield* writer.landShadows(orgId); @@ -2559,6 +2581,7 @@ it.effect("a shadow note not from the owner in their own chat with the lead stay links: [`person:${id}`], ...fields, }); + yield* said("m1", "2026-10-30T00:00:00.000Z"); yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); yield* wokeBeforeCutOver(writer, "wake0"); yield* commitDirectly( @@ -2601,6 +2624,110 @@ it.effect("a shadow note not from the owner in their own chat with the lead stay ), ); +// Review of 220745f: a commit's date can be set by whoever wrote it, so a chat-cited note is bound +// by its message's stored time. +it.effect("a chat-cited shadow note lands only when its message was said before the cut-over", () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const cites = (id: string, message: string) => + fixtureItem({ + id, + kind: "person", + title: `About ${id}`, + due: null, + on_due: undefined, + review_by: null, + links: [`person:${id}`], + source: `kin:chat:owner-chat:message:${message}`, + }); + yield* said("m-before", "2026-10-30T00:00:00.000Z"); + // K035 ran at 12:42:41; this was said later that second. + yield* said("m-after", "2026-11-10T12:42:41.500Z"); + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + yield* commitDirectly( + bare, + Memory.shadowBranch(agentId), + { + add: { + "people/before.md": cites("before", "m-before"), + "people/after.md": cites("after", "m-after"), + "people/missing.md": cites("missing", "m-missing"), + }, + }, + preCutOver, + ); + + yield* writer.landShadows(orgId); + const tree = yield* bare(["ls-tree", "-r", "--name-only", "main"]); + assert.include(tree, "people/before.md"); + assert.notInclude(tree, "people/after.md"); + assert.notInclude(tree, "people/missing.md"); + assert.deepStrictEqual( + (yield* toldOwner).map((row) => row.body), + [ + "Some of Lead's earlier notes weren't added to Memory:\n- people/after.md: Kin couldn't confirm where it came from, so it left it out.\n- people/missing.md: Kin couldn't confirm where it came from, so it left it out.", + ], + ); + }), + ), +); + +it.effect("a landing whose commit fails leaves what a retired note was shared as", () => + landingFixture(({ bare, setLevel }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const memory = yield* Memory.Memory; + const known = personNote("known", "Known to the team"); + setLevel("L2"); + yield* writer.stage(orgId, "wake0", known); + yield* wokeBeforeCutOver(writer, "wake0"); + const id = KinMemoryItemId.make("known"); + yield* authorise( + orgId, + id, + fingerprint(yield* memory.readItemQuietly(orgId, id)), + "owner_setting", + ); + setLevel("L0"); + yield* writer.stage(orgId, "wake1", { + path: known.path, + content: fixtureItem({ + id: "known", + kind: "person", + title: "Known to the team", + due: null, + on_due: undefined, + review_by: null, + links: ["person:known"], + invalid_at: "2026-10-31T00:00:00.000Z", + }), + }); + yield* wokeBeforeCutOver(writer, "wake1"); + // Someone else moved the default branch on, so the landing's push is rejected. + const moved = yield* bare([ + "-c", + "user.name=Fixture Bot", + "-c", + "user.email=fixture@example.invalid", + "commit-tree", + "main^{tree}", + "-p", + "main", + "-m", + "elsewhere", + ]); + yield* bare(["update-ref", "refs/heads/main", moved]); + + yield* writer.landShadows(orgId); + assert.strictEqual(yield* bare(["rev-parse", "main"]), moved); + assert.deepStrictEqual(yield* landedMarks, []); + assert.isTrue((yield* storedLabels(orgId)).shared.has(id)); + }), + ), +); + it.effect("a shadow with no single base shared with the default branch lands nothing", () => landingFixture(({ bare }) => Effect.gen(function* () { @@ -2626,6 +2753,7 @@ it.effect("a shadow note with the id of another note on the default branch stays Effect.gen(function* () { const writer = yield* Writer.MemoryWriter; const memory = yield* Memory.Memory; + yield* said("m1", "2026-10-30T00:00:00.000Z"); yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); yield* wokeBeforeCutOver(writer, "wake0"); yield* commitDirectly(bare, "main", { diff --git a/apps/server/src/kin/memory/MemoryWriter.ts b/apps/server/src/kin/memory/MemoryWriter.ts index d1ab05818c94f..8b91f6bbd972b 100644 --- a/apps/server/src/kin/memory/MemoryWriter.ts +++ b/apps/server/src/kin/memory/MemoryWriter.ts @@ -1998,7 +1998,7 @@ const make = Effect.gen(function* () { const cutOverMs = cutOverSeconds * 1000; const wakeup = /^wakeup:(.+)$/.exec(item.source)?.[1]; const event = /^kin:event:(.+)$/.exec(item.source)?.[1]; - const cited = CHAT_SOURCE.exec(item.source)?.[1]; + const [, cited, message] = CHAT_SOURCE.exec(item.source) ?? []; if (wakeup === undefined && event === undefined && cited === undefined) return false; if (wakeup !== undefined) { const [ran] = yield* sql`SELECT 1 FROM kin_wakeups WHERE org_id = ${orgId} @@ -2012,6 +2012,14 @@ const make = Effect.gen(function* () { AND queued_at < ${cutOverMs}`.pipe(toSql); if (queued === undefined) return false; } + // The message's own time bounds the note, not its commit's; a cleared chat's are gone. + if (message !== undefined) { + const [said] = yield* sql<{ at: string }>`SELECT created_at AS "at" FROM kin_messages + WHERE org_id = ${orgId} AND chat_id = ${cited} AND message_id = ${message}`.pipe( + toSql, + ); + if (said === undefined || !(Date.parse(said.at) < cutOverMs)) return false; + } const chats = [...new Set([item.chat, cited].filter((chat) => chat !== undefined))]; if (chats.length === 0) return true; const direct = yield* sql<{ chatId: string }>`SELECT c.chat_id AS "chatId" @@ -2136,7 +2144,6 @@ const make = Effect.gen(function* () { }), ); else { - yield* endSharing(orgId, ending); yield* ownerCommit(orgId, { writer, repoUrl: repo.repoUrl, @@ -2145,7 +2152,8 @@ const make = Effect.gen(function* () { headFiles, files, message: `kin(${agentId}): land notes kept at L0\n\nKin-Shadow-Landed: ${shadowHead}\n`, - landed: () => landed, + // With the mark, so a commit that fails leaves sharing as it was for the retry. + landed: () => endSharing(orgId, ending).pipe(Effect.andThen(landed)), }); } if (shown.length > 0) From bf06cf465ecba1882e0c6b8c69e87ea0a0c59ed1 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Fri, 27 Nov 2026 17:59:10 +0530 Subject: [PATCH 08/13] fix(kin): read a message's stored time as UTC in either form The cut-over and a cited message's time now go through one parse. SQLite's zoneless YYYY-MM-DD HH:MM:SS is read as UTC, not as the server's local time. People-change: The owner's message about a lead's earlier notes now survives a restart, comes as its own message per lead after quiet hours, never names a file whose name looks like a key, and says "Memory had a different version, so Kin kept it.", "This note was removed from Memory, so Kin left it out.", "It clashes with another note in Memory, so Kin left it out." or "Kin couldn't confirm where it came from, so it left it out."; notes from a member, a group chat or another host, notes at K035's own second, notes citing a chat message said after K035 ran or no longer kept (a cleared chat's included), and quotes no longer land, and nothing lands when Memory's history was replaced. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/memory/MemoryWriter.test.ts | 9 ++++++++- apps/server/src/kin/memory/MemoryWriter.ts | 9 +++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/apps/server/src/kin/memory/MemoryWriter.test.ts b/apps/server/src/kin/memory/MemoryWriter.test.ts index a7732963e9d87..ee91be38c928b 100644 --- a/apps/server/src/kin/memory/MemoryWriter.test.ts +++ b/apps/server/src/kin/memory/MemoryWriter.test.ts @@ -2644,6 +2644,9 @@ it.effect("a chat-cited shadow note lands only when its message was said before yield* said("m-before", "2026-10-30T00:00:00.000Z"); // K035 ran at 12:42:41; this was said later that second. yield* said("m-after", "2026-11-10T12:42:41.500Z"); + // SQLite's zoneless form is UTC, not the server's local time. + yield* said("m-plain-before", "2026-10-30 00:00:00"); + yield* said("m-plain-after", "2026-11-10 14:00:00"); yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); yield* wokeBeforeCutOver(writer, "wake0"); yield* commitDirectly( @@ -2654,6 +2657,8 @@ it.effect("a chat-cited shadow note lands only when its message was said before "people/before.md": cites("before", "m-before"), "people/after.md": cites("after", "m-after"), "people/missing.md": cites("missing", "m-missing"), + "people/plain-before.md": cites("plain-before", "m-plain-before"), + "people/plain-after.md": cites("plain-after", "m-plain-after"), }, }, preCutOver, @@ -2664,10 +2669,12 @@ it.effect("a chat-cited shadow note lands only when its message was said before assert.include(tree, "people/before.md"); assert.notInclude(tree, "people/after.md"); assert.notInclude(tree, "people/missing.md"); + assert.include(tree, "people/plain-before.md"); + assert.notInclude(tree, "people/plain-after.md"); assert.deepStrictEqual( (yield* toldOwner).map((row) => row.body), [ - "Some of Lead's earlier notes weren't added to Memory:\n- people/after.md: Kin couldn't confirm where it came from, so it left it out.\n- people/missing.md: Kin couldn't confirm where it came from, so it left it out.", + "Some of Lead's earlier notes weren't added to Memory:\n- people/after.md: Kin couldn't confirm where it came from, so it left it out.\n- people/missing.md: Kin couldn't confirm where it came from, so it left it out.\n- people/plain-after.md: Kin couldn't confirm where it came from, so it left it out.", ], ); }), diff --git a/apps/server/src/kin/memory/MemoryWriter.ts b/apps/server/src/kin/memory/MemoryWriter.ts index 8b91f6bbd972b..11f1f0cb7ee57 100644 --- a/apps/server/src/kin/memory/MemoryWriter.ts +++ b/apps/server/src/kin/memory/MemoryWriter.ts @@ -70,6 +70,11 @@ import { export const RESTART_JOURNAL_LINE = "Kin restarted during this turn; what was noted before the restart may not have been saved."; + +/** A stored time as UTC ms: ISO with a zone, or SQLite's zoneless `YYYY-MM-DD HH:MM:SS`, which is UTC. */ +const utcMs = (at: string) => + Date.parse(/(?:[zZ]|[+-]\d\d:?\d\d)$/.test(at) ? at : `${at.replace(" ", "T")}Z`); + const FINISHED_KEPT = 1_000; const RESTART_OWNER_NOTICE = "Kin restarted while an agent was working, so something it said it saved may not have been kept. If it matters, tell it again."; @@ -1977,7 +1982,7 @@ const make = Effect.gen(function* () { // came from a chat the owner didn't place the lead in, so it stays off the default branch. const [cutOver] = yield* sql<{ at: string }>`SELECT created_at AS "at" FROM kin_sql_migrations WHERE migration_id = 35`.pipe(toSql); - const cutOverSeconds = Date.parse(`${cutOver?.at.replace(" ", "T")}Z`) / 1000; + const cutOverSeconds = (cutOver === undefined ? Number.NaN : utcMs(cutOver.at)) / 1000; if (!Number.isFinite(cutOverSeconds)) return; const same = (a: Buffer | undefined, b: Buffer | undefined) => a === undefined ? b === undefined : b !== undefined && a.equals(b); @@ -2018,7 +2023,7 @@ const make = Effect.gen(function* () { WHERE org_id = ${orgId} AND chat_id = ${cited} AND message_id = ${message}`.pipe( toSql, ); - if (said === undefined || !(Date.parse(said.at) < cutOverMs)) return false; + if (said === undefined || !(utcMs(said.at) < cutOverMs)) return false; } const chats = [...new Set([item.chat, cited].filter((chat) => chat !== undefined))]; if (chats.length === 0) return true; From 17813d50739453a3fe91ffa420a5fcc8bc11def2 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sat, 28 Nov 2026 07:21:12 +0530 Subject: [PATCH 09/13] fix(kin): check a shadow landing's ids as Memory reads them, and reconcile one the remote already took Ids are now checked against the tree that would land, with the default branch's notes parsed as Memory.load reads them, and checked again whenever holding a note back puts the default branch's note back at its path. Before a lead is landed again, Kin looks for an earlier landing of the same shadow head on the default branch: one the remote accepted while the transaction that marks it failed. When that landing carries only this shadow's notes, Kin marks it, lands nothing a person removed since, and tells the owner what that landing actually left behind. The landed marker now goes through Memory.anchor, which owns kin_memory_heads, so the refresh guard holds unchanged. People-change: The owner's message about a lead's earlier notes no longer names a note that did land, a note removed from Memory after it landed stays removed, and an earlier note that would share another note's id, including an older note's, stays behind. Co-Authored-By: Claude Opus 5.5 --- .../src/kin/memory/MemoryWriter.test.ts | 196 ++++++++++++++- apps/server/src/kin/memory/MemoryWriter.ts | 233 +++++++++++++----- 2 files changed, 360 insertions(+), 69 deletions(-) diff --git a/apps/server/src/kin/memory/MemoryWriter.test.ts b/apps/server/src/kin/memory/MemoryWriter.test.ts index ee91be38c928b..fcb65754f75db 100644 --- a/apps/server/src/kin/memory/MemoryWriter.test.ts +++ b/apps/server/src/kin/memory/MemoryWriter.test.ts @@ -2174,6 +2174,8 @@ const commitDirectly = ( readonly remove?: ReadonlyArray; /** A history of its own, as a replaced or recovered branch has. */ readonly orphan?: boolean; + /** The commit's parents in place of the branch's head, as a merge has. */ + readonly parents?: ReadonlyArray; }, date?: string, ) => @@ -2211,7 +2213,9 @@ const commitDirectly = ( const commit = yield* git([ "commit-tree", yield* git(["write-tree"]), - ...(change.orphan === true ? [] : ["-p", before]), + ...(change.orphan === true + ? [] + : (change.parents ?? [before]).flatMap((parent) => ["-p", parent])), "-m", "direct", ]); @@ -2541,13 +2545,28 @@ it.effect("a shadow commit at the cut-over's own second stays off the default br landingFixture(({ bare }) => Effect.gen(function* () { const writer = yield* Writer.MemoryWriter; + yield* said("m-early", "2026-10-30T00:00:00.000Z"); yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); yield* wokeBeforeCutOver(writer, "wake0"); - // K035 ran at 12:42:41; this commit's second is the same one. + // K035 ran at 12:42:41; this commit's second is the same one. Its note cites the owner's + // message from before then, so only the cut-off holds it. yield* commitDirectly( bare, Memory.shadowBranch(agentId), - { add: { "people/same-second.md": personNote("same-second", "Said that second").content } }, + { + add: { + "people/same-second.md": fixtureItem({ + id: "same-second", + kind: "person", + title: "Said that second", + due: null, + on_due: undefined, + review_by: null, + links: ["person:same-second"], + source: "kin:chat:owner-chat:message:m-early", + }), + }, + }, "2026-11-10T12:42:41Z", ); @@ -2905,3 +2924,174 @@ it.effect("pull-request mode with a memory repo off GitHub skips landing quietly { offGitHubPullRequests: true }, ), ); + +// A shadow note citing the owner's message `m1` in their chat with the lead. +const cited = (id: string, title: string, extra: Record = {}) => + fixtureItem({ + id, + kind: "person", + title, + due: null, + on_due: undefined, + review_by: null, + links: [`person:${id}`], + source: "kin:chat:owner-chat:message:m1", + ...extra, + }); + +it.effect("a shadow note whose id only a held-back note would free stays behind too", () => + landingFixture(({ bare, setLevel }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const memory = yield* Memory.Memory; + yield* said("m1", "2026-10-30T00:00:00.000Z"); + setLevel("L2"); + yield* writer.stage(orgId, "wake0", personNote("a", "A, as Memory has it")); + yield* writer.stage(orgId, "wake0", personNote("b", "B, as Memory has it")); + yield* writer.commitWakeup(orgId, "wake0", "completed"); + setLevel("L0"); + yield* writer.stage(orgId, "wake1", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake1"); + // `people/a.md` now holds `b`, which clashes, so Memory's `a` stays and `people/c.md` clashes. + yield* commitDirectly( + bare, + Memory.shadowBranch(agentId), + { + add: { + "people/a.md": cited("b", "B, as the shadow has it"), + "people/c.md": cited("a", "A, moved by the shadow"), + }, + }, + preCutOver, + ); + + yield* writer.landShadows(orgId); + const tree = yield* bare(["ls-tree", "-r", "--name-only", "main"]); + assert.include(tree, "people/alex.md"); + assert.notInclude(tree, "people/c.md"); + yield* memory.syncCheckout(orgId); + for (const [id, title] of [ + ["a", "A, as Memory has it"], + ["b", "B, as Memory has it"], + ] as const) + assert.strictEqual( + (yield* memory.readItem(orgId, KinMemoryItemId.make(id))).head.title, + title, + ); + assert.deepStrictEqual( + (yield* toldOwner).map((row) => row.body), + [ + "Some of Lead's earlier notes weren't added to Memory:\n- people/a.md: It clashes with another note in Memory, so Kin left it out.\n- people/c.md: It clashes with another note in Memory, so Kin left it out.", + ], + ); + }), + ), +); + +it.effect( + "a shadow note with the id of a note only the reader's lenient parse loads stays behind", + () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const memory = yield* Memory.Memory; + yield* said("m1", "2026-10-30T00:00:00.000Z"); + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + // An older note whose quote isn't text: reads drop the quote and still load it. + yield* commitDirectly(bare, "main", { + add: { + "people/legacy.md": cited("legacy", "Legacy, as Memory has it", { quote: [1, 2] }), + }, + }); + yield* commitDirectly( + bare, + Memory.shadowBranch(agentId), + { add: { "people/legacy-copy.md": cited("legacy", "Legacy, as the shadow has it") } }, + preCutOver, + ); + + yield* writer.landShadows(orgId); + const tree = yield* bare(["ls-tree", "-r", "--name-only", "main"]); + assert.include(tree, "people/alex.md"); + assert.notInclude(tree, "people/legacy-copy.md"); + yield* memory.syncCheckout(orgId); + assert.strictEqual( + (yield* memory.readItem(orgId, KinMemoryItemId.make("legacy"))).head.title, + "Legacy, as Memory has it", + ); + }), + ), +); + +it.effect("a retry after a landing the remote took marks it and brings back nothing removed", () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const memory = yield* Memory.Memory; + const sql = yield* SqlClient.SqlClient; + yield* said("m1", "2026-10-30T00:00:00.000Z"); + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + yield* commitDirectly( + bare, + Memory.shadowBranch(agentId), + { + add: { + "people/sam.md": cited("sam", "Sam runs billing", { quote: FIXTURE_QUOTE }), + "people/broken.md": "Not a note\n", + }, + }, + preCutOver, + ); + // The remote takes the landing, then the transaction that marks it fails. + yield* sql.unsafe(`CREATE TRIGGER no_mark BEFORE INSERT ON kin_memory_heads + WHEN NEW.branch LIKE 'kin/shadow-landed/%' BEGIN SELECT RAISE(ABORT, 'no mark'); END`); + yield* writer.landShadows(orgId); + assert.include(yield* bare(["show", "main:people/alex.md"]), "Alex leads design"); + assert.notInclude(yield* bare(["show", "main:people/sam.md"]), FIXTURE_QUOTE); + assert.deepStrictEqual(yield* landedMarks, []); + assert.deepStrictEqual(yield* toldOwner, []); + yield* sql.unsafe("DROP TRIGGER no_mark"); + yield* memory.syncCheckout(orgId); + // Before the retry, someone removes a landed note from Memory. + yield* commitDirectly(bare, "main", { remove: ["people/alex.md"] }); + const removed = yield* bare(["rev-parse", "main"]); + + yield* writer.landShadows(orgId); + assert.strictEqual(yield* bare(["rev-parse", "main"]), removed); + assert.deepStrictEqual(yield* landedMarks, [`kin/shadow-landed/${agentId}`]); + assert.deepStrictEqual( + (yield* toldOwner).map((row) => row.body), + [ + "Some of Lead's earlier notes weren't added to Memory:\n- people/broken.md: It couldn't be read.", + ], + ); + }), + ), +); + +it.effect("a shadow whose history crosses the default branch's twice lands nothing", () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const shadow = Memory.shadowBranch(agentId); + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + // Each branch merges the other's tip in turn: a criss-cross, with two best bases. + yield* commitDirectly(bare, shadow, { add: { "rules.md": "Shadow rules\n" } }, preCutOver); + yield* commitDirectly(bare, "main", { add: { "rules.md": "Default rules\n" } }); + const fromShadow = yield* bare(["rev-parse", shadow]); + const fromMain = yield* bare(["rev-parse", "main"]); + yield* commitDirectly(bare, shadow, { parents: [fromShadow, fromMain] }, preCutOver); + yield* commitDirectly(bare, "main", { parents: [fromMain, fromShadow] }); + assert.lengthOf((yield* bare(["merge-base", "--all", "main", shadow])).split("\n"), 2); + const before = yield* bare(["rev-parse", "main"]); + + yield* writer.landShadows(orgId); + assert.strictEqual(yield* bare(["rev-parse", "main"]), before); + assert.notInclude(yield* bare(["ls-tree", "-r", "--name-only", "main"]), "people/alex.md"); + assert.deepStrictEqual(yield* landedMarks, []); + }), + ), +); diff --git a/apps/server/src/kin/memory/MemoryWriter.ts b/apps/server/src/kin/memory/MemoryWriter.ts index afc0a256474a8..e61d41204ead4 100644 --- a/apps/server/src/kin/memory/MemoryWriter.ts +++ b/apps/server/src/kin/memory/MemoryWriter.ts @@ -324,7 +324,8 @@ export class MemoryWriter extends Context.Service< 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. +// Through `Memory.anchor`, the table's owner: a `kin_memory_heads` row no branch uses, holding the +// shadow head landed. const shadowLanded = (agentId: string) => `kin/shadow-landed/${agentId}`; // The held line (`deliverHeld`) telling the owner what of a lead's shadow stayed behind. const shadowNoticeKind = (agentId: string) => `kin-memory:shadow-landed:${agentId}`; @@ -2047,6 +2048,144 @@ const make = Effect.gen(function* () { ORDER BY c.chat_id`.pipe(toSql); return direct.length === chats.length; }); + // What landing `shadowHead` onto `head` takes and leaves: the same answer for one head. + const planLanding = Effect.fn("MemoryWriter.landShadows.plan")(function* ( + agentId: string, + owner: string, + shadowHead: string, + shadowFiles: ReadonlyMap, + head: string, + ) { + const headFiles = yield* filesAt(orgId, writer, head); + // Without one base both share, a note the default branch removed reads as new. + const bases = (yield* git(orgId, writer, ["merge-base", "--all", head, shadowHead])) + .split("\n") + .filter((line) => line !== ""); + if (bases.length !== 1) + return yield* new MemorySyncConflict({ + orgId, + operation: "landShadows", + reason: "The shadow branch and the default branch share no single base", + }); + const baseFiles = yield* filesAt(orgId, writer, bases[0]!); + const files = new Map(); + const held: Array<{ path: string; why: keyof typeof heldWhy }> = []; + for (const [path, bytes] of shadowFiles) { + if (!folders.some((folder) => path.startsWith(`${folder}/`))) continue; + const now = headFiles.get(path); + const was = baseFiles.get(path); + if (same(was, bytes) || same(now, bytes)) continue; + // Changed on the default branch too, deletion included: its version stays. + if (!same(now, was)) + held.push({ path, why: now === undefined ? "removed" : "different" }); + // A quote can't be checked against a clear that runs while this lands. + else files.set(path, withoutQuote(bytes.toString("utf8"))); + } + const items = new Map(); + for (const [path, text] of files) { + const item = yield* parsedAt(path, text); + if (Option.isNone(item)) held.push({ path, why: "unreadable" }); + else if ( + (yield* scanner.scan({ orgId, files: [{ path, content: Buffer.from(text) }] })) + .length > 0 + ) + held.push({ path, why: "secret" }); + else if (!(yield* provenOrigin(agentId, owner, item.value))) + held.push({ path, why: "unverified" }); + else { + items.set(path, item.value); + continue; + } + files.delete(path); + } + // Two notes with one id fail every read of it (`MemoryDuplicateId`), so the tree that + // would land is checked with ids as `Memory.load` reads them; holding a note back puts + // the default branch's at its path again, so it repeats until nothing clashes. + const reserved = new Map(); + for (const [path, bytes] of headFiles) + if (folders.some((folder) => path.startsWith(`${folder}/`))) { + const item = yield* parseFrontMatter( + orgId, + path, + bytes.toString("utf8"), + false, + true, + ).pipe(Effect.option); + if (Option.isSome(item)) reserved.set(path, item.value.frontMatter.id); + } + for (;;) { + const count = new Map(); + const claim = (id: string) => count.set(id, (count.get(id) ?? 0) + 1); + for (const [path, id] of reserved) if (!files.has(path)) claim(id); + for (const item of items.values()) claim(item.id); + const clashing = [...items].filter(([, item]) => count.get(item.id)! > 1); + if (clashing.length === 0) break; + for (const [path] of clashing) { + files.delete(path); + items.delete(path); + held.push({ path, why: "clash" }); + } + } + return { headFiles, files, items, held }; + }); + const landingMessage = (agentId: string, shadowHead: string) => + `kin(${agentId}): land notes kept at L0\n\nKin-Shadow-Landed: ${shadowHead}\n`; + // A landing the remote took while the transaction marking it failed is on the default + // branch once sync adopts it. Found by its message and checked to carry only this + // shadow's notes, so the retry marks it instead of landing again what was removed since. + const earlierLanding = Effect.fn("MemoryWriter.landShadows.earlier")(function* ( + agentId: string, + shadowHead: string, + shadowFiles: ReadonlyMap, + head: string, + ) { + const candidates = (yield* git(orgId, writer, [ + "log", + "--format=%H", + "--fixed-strings", + `--grep=Kin-Shadow-Landed: ${shadowHead}`, + head, + ])) + .split("\n") + .filter((line) => line !== ""); + for (const commit of candidates) { + const message = yield* git(orgId, writer, ["show", "-s", "--format=%B", commit]); + if (message.trim() !== landingMessage(agentId, shadowHead).trim()) continue; + const [, ...parents] = (yield* git(orgId, writer, [ + "rev-list", + "--parents", + "-n", + "1", + commit, + ])).split(" "); + const landedFiles = yield* filesAt(orgId, writer, commit); + const parentFiles = + parents.length === 1 ? yield* filesAt(orgId, writer, parents[0]!) : undefined; + const landed = new Set(); + const matches = + parentFiles !== undefined && + [...new Set([...parentFiles.keys(), ...landedFiles.keys()])].every((path) => { + const bytes = landedFiles.get(path); + if (path === "INDEX.md" || same(parentFiles.get(path), bytes)) return true; + const kept = shadowFiles.get(path); + landed.add(path); + return ( + folders.some((folder) => path.startsWith(`${folder}/`)) && + bytes !== undefined && + kept !== undefined && + bytes.equals(Buffer.from(withoutQuote(kept.toString("utf8")))) + ); + }); + if (!matches) + return yield* new MemorySyncConflict({ + orgId, + operation: "landShadows", + reason: "An earlier landing of this shadow branch holds more than its notes", + }); + return { parent: parents[0]!, landed }; + } + return undefined; + }); // A lead that fails is logged and left unmarked, so the next sync retries it alone. for (const { agentId, name, branch, owner, ownerChat } of pending) yield* Effect.gen(function* () { @@ -2058,70 +2197,30 @@ const make = Effect.gen(function* () { `--before=@${Math.ceil(cutOverSeconds) - 1}`, tip, ]); - const mark = sql`INSERT INTO kin_memory_heads (org_id, branch, head) - VALUES (${orgId}, ${shadowLanded(agentId)}, ${shadowHead || tip}) - ON CONFLICT DO NOTHING`.pipe(toSql, Effect.asVoid); + const mark = memory + .anchor(orgId, shadowLanded(agentId), shadowHead || tip) + .pipe(Effect.asVoid); if (shadowHead === "") return yield* mark; const shadowFiles = yield* filesAt(orgId, writer, shadowHead); const head = yield* branchHead(orgId, writer, main); - const headFiles = yield* filesAt(orgId, writer, head); - // Without one base both share, a note the default branch removed reads as new. - const bases = (yield* git(orgId, writer, ["merge-base", "--all", head, shadowHead])) - .split("\n") - .filter((line) => line !== ""); - if (bases.length !== 1) - return yield* new MemorySyncConflict({ - orgId, - operation: "landShadows", - reason: "The shadow branch and the default branch share no single base", - }); - const baseFiles = yield* filesAt(orgId, writer, bases[0]!); - const files = new Map(); - const held: Array<{ path: string; why: keyof typeof heldWhy }> = []; - for (const [path, bytes] of shadowFiles) { - if (!folders.some((folder) => path.startsWith(`${folder}/`))) continue; - const now = headFiles.get(path); - const was = baseFiles.get(path); - if (same(was, bytes) || same(now, bytes)) continue; - // Changed on the default branch too, deletion included: its version stays. - if (!same(now, was)) - held.push({ path, why: now === undefined ? "removed" : "different" }); - // A quote can't be checked against a clear that runs while this lands. - else files.set(path, withoutQuote(bytes.toString("utf8"))); - } - const items = new Map(); - for (const [path, text] of files) { - const item = yield* parsedAt(path, text); - if (Option.isNone(item)) held.push({ path, why: "unreadable" }); - else if ( - (yield* scanner.scan({ orgId, files: [{ path, content: Buffer.from(text) }] })) - .length > 0 - ) - held.push({ path, why: "secret" }); - else if (!(yield* provenOrigin(agentId, owner, item.value))) - held.push({ path, why: "unverified" }); - else { - items.set(path, item.value); - continue; - } - files.delete(path); - } - // Two notes with one id fail every read of it (`MemoryDuplicateId`). - const paths = new Map>(); - const claim = (id: string, path: string) => - paths.set(id, [...(paths.get(id) ?? []), path]); - for (const [path, bytes] of headFiles) - if (!files.has(path) && folders.some((folder) => path.startsWith(`${folder}/`))) { - const item = yield* parsedAt(path, bytes.toString("utf8")); - if (Option.isSome(item)) claim(item.value.id, path); - } - for (const [path, item] of items) claim(item.id, path); - const ending: Array = []; - for (const [path, item] of items) - if ((paths.get(item.id)?.length ?? 0) > 1) { - files.delete(path); - held.push({ path, why: "clash" }); - } else if (retired(item)) ending.push(item.id); + const earlier = yield* earlierLanding(agentId, shadowHead, shadowFiles, head); + // Replayed against the head it landed on, so the owner hears what that landing left. + const plan = yield* planLanding( + agentId, + owner, + shadowHead, + shadowFiles, + earlier?.parent ?? head, + ); + const held = + earlier === undefined + ? plan.held + : [ + ...plan.held.filter(({ path }) => !earlier.landed.has(path)), + ...[...plan.files.keys()] + .filter((path) => !earlier.landed.has(path)) + .map((path) => ({ path, why: "unverified" as const })), + ]; // A name the scan flags stays out of the owner's chat and the log. const shown: Array<{ path: string | undefined; why: keyof typeof heldWhy }> = []; for (const { path, why } of held.toSorted((a, b) => a.path.localeCompare(b.path))) { @@ -2148,7 +2247,8 @@ const make = Effect.gen(function* () { 'owner', ${at}, ${at}) ON CONFLICT DO NOTHING`.pipe(toSql, Effect.asVoid); const landed = mark.pipe(Effect.andThen(told)); - if (files.size === 0) + // An earlier landing's retired notes end their sharing as `reconcileSharing` sweeps. + if (earlier !== undefined || plan.files.size === 0) yield* sql.withTransaction(landed).pipe( Effect.catchTags({ SqlError: (cause) => @@ -2156,14 +2256,15 @@ const make = Effect.gen(function* () { }), ); else { + const ending = [...plan.items.values()].filter(retired).map((item) => item.id); 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`, + headFiles: plan.headFiles, + files: plan.files, + message: landingMessage(agentId, shadowHead), // With the mark, so a commit that fails leaves sharing as it was for the retry. landed: () => endSharing(orgId, ending).pipe(Effect.andThen(landed)), }); From 15f4d48027d98c5480c8331c2dc4f405a74667e2 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sat, 28 Nov 2026 11:15:53 +0530 Subject: [PATCH 10/13] fix(kin): record a shadow landing before its push and confirm that exact commit A retry after a push whose mark failed used to find the earlier landing by its commit message and infer the rest from the current tree. A look-alike message could mark a lead with nothing landed, a retry before a fetch could mark it wrongly, and a note held for a clash came back as "couldn't confirm". Each landing is now recorded in kin_shadow_landings (K240) before its commit can reach the remote: the exact commit plus the held notes and their reasons. A retry fetches the default branch first and decides nothing if it can't; if that commit is on it, the lead is marked and the saved notice is sent, and otherwise the landing is planned again. The message search is gone. Ids are reserved only for files Memory's reader admits (path, mode, item), for the notes already there and for the tree that would land. People-change: A note held back for clashing with another note is still named as a clash after its chat is cleared, a file Memory doesn't read no longer holds back a lead's earlier note with the same id, and a lead's earlier notes are no longer counted as added because of a look-alike commit or before Kin can reach the memory repo. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/memory/Memory.ts | 39 ++- .../src/kin/memory/MemoryWriter.test.ts | 168 ++++++++-- apps/server/src/kin/memory/MemoryWriter.ts | 288 +++++++++--------- apps/server/src/kin/people/leaver.test.ts | 2 + .../src/kin/persistence/KinMigrations.test.ts | 14 +- .../src/kin/persistence/KinMigrations.ts | 2 + .../migrations/K240_ShadowLandings.ts | 16 + 7 files changed, 362 insertions(+), 167 deletions(-) create mode 100644 apps/server/src/kin/persistence/migrations/K240_ShadowLandings.ts diff --git a/apps/server/src/kin/memory/Memory.ts b/apps/server/src/kin/memory/Memory.ts index a02ce8ec99cf8..32b9144acb26e 100644 --- a/apps/server/src/kin/memory/Memory.ts +++ b/apps/server/src/kin/memory/Memory.ts @@ -357,6 +357,35 @@ const decodeHead = Schema.decodeEffect(MemoryItemHead); export const folders: ReadonlyArray = itemFolders; export const maxBlobBytes = 256 * 1024; + +/** Whether `load` reads a tree entry as a memory item, by its path and mode alone. */ +const isItemEntry = (relative: string, mode: string) => + ["100644", "100755"].includes(mode) && + relative.endsWith(".md") && + itemFolders.some((folder) => relative.startsWith(`${folder}/`)); +const itemFolder = (kind: string) => (kind === "person" ? "people" : `${kind}s`); +/** The id `load` reads `bytes` at `relative` under, by its own rule; none when it skips the file. */ +export const admittedId = Effect.fnUntraced(function* ( + orgId: KinOrgId, + relative: string, + mode: string, + bytes: Uint8Array, +) { + if (!isItemEntry(relative, mode) || bytes.length > maxBlobBytes) return undefined; + const text = yield* Effect.try({ + try: () => new TextDecoder("utf-8", { fatal: true }).decode(bytes), + catch: () => "not UTF-8", + }).pipe(Effect.option); + if (text._tag === "None") return undefined; + const parsed = yield* parseFrontMatter(orgId, relative, text.value, false, true).pipe( + Effect.option, + ); + if (parsed._tag === "None") return undefined; + const { frontMatter } = parsed.value; + if (!relative.startsWith(`${itemFolder(frontMatter.kind)}/`)) return undefined; + const head = yield* decodeHead({ ...frontMatter, orgId, path: relative }).pipe(Effect.option); + return head._tag === "Some" ? head.value.id : undefined; +}); // Well under memoryGit's 64 MiB output cap, so a large journal reads in a few `cat-file` runs. const checkoutBatchBytes = 16 * 1024 * 1024; @@ -843,10 +872,8 @@ const make = Effect.gen(function* () { const entries = verifiedEntries .filter( ({ relative, mode }) => - ["100644", "100755"].includes(mode) && - relative.endsWith(".md") && - (itemFolders.some((folder) => relative.startsWith(`${folder}/`)) || - ["rules.md", "INDEX.md"].includes(relative)), + isItemEntry(relative, mode) || + (["100644", "100755"].includes(mode) && ["rules.md", "INDEX.md"].includes(relative)), ) .map((entry) => ({ ...entry, size: sizes.get(entry.sha) ?? Infinity })); const pending = [ @@ -928,9 +955,7 @@ const make = Effect.gen(function* () { } const parsed = parsedBlobs.get(sha); if (!parsed) return; - const expectedFolder = - parsed.frontMatter.kind === "person" ? "people" : `${parsed.frontMatter.kind}s`; - if (!relative.startsWith(`${expectedFolder}/`)) { + if (!relative.startsWith(`${itemFolder(parsed.frontMatter.kind)}/`)) { if (!mismatchWarnings.has(sha)) { mismatchWarnings.add(sha); return yield* new MemoryItemError({ diff --git a/apps/server/src/kin/memory/MemoryWriter.test.ts b/apps/server/src/kin/memory/MemoryWriter.test.ts index fcb65754f75db..e53af51ab9c90 100644 --- a/apps/server/src/kin/memory/MemoryWriter.test.ts +++ b/apps/server/src/kin/memory/MemoryWriter.test.ts @@ -2176,6 +2176,7 @@ const commitDirectly = ( readonly orphan?: boolean; /** The commit's parents in place of the branch's head, as a merge has. */ readonly parents?: ReadonlyArray; + readonly message?: string; }, date?: string, ) => @@ -2217,7 +2218,7 @@ const commitDirectly = ( ? [] : (change.parents ?? [before]).flatMap((parent) => ["-p", parent])), "-m", - "direct", + change.message ?? "direct", ]); const remote = yield* bare(["rev-parse", "--absolute-git-dir"]); yield* git(["push", "--", remote, `+${commit}:refs/heads/${branch}`]); @@ -2244,11 +2245,23 @@ const toldOwner = Effect.gen(function* () { }); const landedMarks = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; - const rows = yield* sql<{ branch: string; head: string }>`SELECT branch, head - FROM kin_memory_heads WHERE org_id = ${orgId} AND branch LIKE 'kin/shadow-landed/%' - ORDER BY branch`; - return rows.map((row) => row.branch); + const rows = yield* sql<{ agentId: string }>`SELECT agent_id AS "agentId" + FROM kin_shadow_landings WHERE org_id = ${orgId} AND landed_at IS NOT NULL + ORDER BY agent_id`; + return rows.map((row) => row.agentId); }); +// While on, the remote takes a landing and then the transaction that marks it fails. +const marksFail = (on: boolean) => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + for (const event of ["INSERT", "UPDATE"]) + yield* sql.unsafe( + on + ? `CREATE TRIGGER no_mark_${event} BEFORE ${event} ON kin_shadow_landings + WHEN NEW.landed_at IS NOT NULL BEGIN SELECT RAISE(ABORT, 'no mark'); END` + : `DROP TRIGGER no_mark_${event}`, + ); + }); it.effect("an L0 lead's shadow notes land on the default branch and its index, once", () => landingFixture(({ bare, setLevel }) => @@ -2372,12 +2385,7 @@ it.effect("one lead that cannot land leaves the next lead's notes landing", () = yield* writer.landShadows(orgId); assert.include(yield* bare(["show", "main:people/owner-repos.md"]), "two main repos"); - const marked = yield* sql<{ branch: string }>`SELECT branch FROM kin_memory_heads - WHERE org_id = ${orgId} AND branch LIKE 'kin/shadow-landed/%' ORDER BY branch`; - assert.deepStrictEqual( - marked.map((row) => row.branch), - [`kin/shadow-landed/${agentId}`], - ); + assert.deepStrictEqual(yield* landedMarks, [agentId]); }), ), ); @@ -2862,10 +2870,7 @@ it.effect("each lead's note of what stayed behind survives a restart and posts o ); yield* writer.landShadows(orgId); - assert.deepStrictEqual(yield* landedMarks, [ - "kin/shadow-landed/b-lead", - `kin/shadow-landed/${agentId}`, - ]); + assert.deepStrictEqual(yield* landedMarks, ["b-lead", agentId]); // A restart here, before anything posted: the lines wait in what was stored with the marks. const posted: Array<{ messageId: string; chatId: string; body: string }> = []; const chat = (fail: boolean) => ({ @@ -3029,7 +3034,6 @@ it.effect("a retry after a landing the remote took marks it and brings back noth Effect.gen(function* () { const writer = yield* Writer.MemoryWriter; const memory = yield* Memory.Memory; - const sql = yield* SqlClient.SqlClient; yield* said("m1", "2026-10-30T00:00:00.000Z"); yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); yield* wokeBeforeCutOver(writer, "wake0"); @@ -3044,15 +3048,13 @@ it.effect("a retry after a landing the remote took marks it and brings back noth }, preCutOver, ); - // The remote takes the landing, then the transaction that marks it fails. - yield* sql.unsafe(`CREATE TRIGGER no_mark BEFORE INSERT ON kin_memory_heads - WHEN NEW.branch LIKE 'kin/shadow-landed/%' BEGIN SELECT RAISE(ABORT, 'no mark'); END`); + yield* marksFail(true); yield* writer.landShadows(orgId); assert.include(yield* bare(["show", "main:people/alex.md"]), "Alex leads design"); assert.notInclude(yield* bare(["show", "main:people/sam.md"]), FIXTURE_QUOTE); assert.deepStrictEqual(yield* landedMarks, []); assert.deepStrictEqual(yield* toldOwner, []); - yield* sql.unsafe("DROP TRIGGER no_mark"); + yield* marksFail(false); yield* memory.syncCheckout(orgId); // Before the retry, someone removes a landed note from Memory. yield* commitDirectly(bare, "main", { remove: ["people/alex.md"] }); @@ -3060,7 +3062,7 @@ it.effect("a retry after a landing the remote took marks it and brings back noth yield* writer.landShadows(orgId); assert.strictEqual(yield* bare(["rev-parse", "main"]), removed); - assert.deepStrictEqual(yield* landedMarks, [`kin/shadow-landed/${agentId}`]); + assert.deepStrictEqual(yield* landedMarks, [agentId]); assert.deepStrictEqual( (yield* toldOwner).map((row) => row.body), [ @@ -3095,3 +3097,127 @@ it.effect("a shadow whose history crosses the default branch's twice lands nothi }), ), ); + +it.effect("a retry after a landing the remote took decides nothing until it can fetch", () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const sql = yield* SqlClient.SqlClient; + const fs = yield* FileSystem.FileSystem; + yield* said("m1", "2026-10-30T00:00:00.000Z"); + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + // The shadow's only note is cited from the owner's chat. + yield* commitDirectly( + bare, + Memory.shadowBranch(agentId), + { remove: ["people/alex.md"], add: { "people/sam.md": cited("sam", "Sam runs billing") } }, + preCutOver, + ); + yield* marksFail(true); + yield* writer.landShadows(orgId); + yield* marksFail(false); + assert.include(yield* bare(["show", "main:people/sam.md"]), "Sam runs billing"); + const landed = yield* bare(["rev-parse", "main"]); + // A note's source is cleared, and the remote can't be reached for the retry. + yield* sql`DELETE FROM kin_messages WHERE message_id = 'm1'`; + const remote = yield* bare(["rev-parse", "--absolute-git-dir"]); + yield* fs.rename(remote, `${remote}.away`); + yield* writer.landShadows(orgId); + assert.deepStrictEqual(yield* landedMarks, []); + assert.deepStrictEqual(yield* toldOwner, []); + + yield* fs.rename(`${remote}.away`, remote); + yield* writer.landShadows(orgId); + assert.strictEqual(yield* bare(["rev-parse", "main"]), landed); + assert.deepStrictEqual(yield* landedMarks, [agentId]); + assert.deepStrictEqual(yield* toldOwner, []); + }), + ), +); + +it.effect("a commit that only copies a landing's message marks nothing", () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const shadow = Memory.shadowBranch(agentId); + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + const shadowHead = yield* bare(["rev-parse", shadow]); + yield* commitDirectly(bare, "main", { + add: { "rules.md": "Other rules\n" }, + message: `kin(${agentId}): land notes kept at L0\n\nKin-Shadow-Landed: ${shadowHead}\n`, + }); + + yield* writer.landShadows(orgId); + assert.include( + (yield* bare(["ls-tree", "-r", "--name-only", "main"])).split("\n"), + "people/alex.md", + ); + assert.deepStrictEqual(yield* landedMarks, [agentId]); + }), + ), +); + +it.effect("a note held for a clash is still told as a clash after its source is cleared", () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const memory = yield* Memory.Memory; + const sql = yield* SqlClient.SqlClient; + yield* said("m1", "2026-10-30T00:00:00.000Z"); + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + yield* commitDirectly(bare, "main", { + add: { "people/onboarding.md": personNote("onboarding", "Onboarding").content }, + }); + yield* commitDirectly( + bare, + Memory.shadowBranch(agentId), + { add: { "people/onboarding-copy.md": cited("onboarding", "Onboarding, again") } }, + preCutOver, + ); + yield* marksFail(true); + yield* writer.landShadows(orgId); + yield* marksFail(false); + assert.include(yield* bare(["show", "main:people/alex.md"]), "Alex leads design"); + yield* memory.syncCheckout(orgId); + yield* sql`DELETE FROM kin_messages WHERE message_id = 'm1'`; + + yield* writer.landShadows(orgId); + assert.deepStrictEqual(yield* landedMarks, [agentId]); + assert.deepStrictEqual( + (yield* toldOwner).map((row) => row.body), + [ + "Some of Lead's earlier notes weren't added to Memory:\n- people/onboarding-copy.md: It clashes with another note in Memory, so Kin left it out.", + ], + ); + }), + ), +); + +it.effect("a file Memory doesn't read, with a note's id, doesn't hold that note back", () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const memory = yield* Memory.Memory; + yield* writer.stage(orgId, "wake0", personNote("sam", "Sam runs billing")); + yield* wokeBeforeCutOver(writer, "wake0"); + yield* commitDirectly(bare, "main", { + add: { "people/sam.md.bak": personNote("sam", "Sam, an old copy").content }, + }); + + yield* writer.landShadows(orgId); + assert.include( + (yield* bare(["ls-tree", "-r", "--name-only", "main"])).split("\n"), + "people/sam.md", + ); + yield* memory.syncCheckout(orgId); + assert.strictEqual( + (yield* memory.readItem(orgId, KinMemoryItemId.make("sam"))).head.title, + "Sam runs billing", + ); + assert.deepStrictEqual(yield* toldOwner, []); + }), + ), +); diff --git a/apps/server/src/kin/memory/MemoryWriter.ts b/apps/server/src/kin/memory/MemoryWriter.ts index e61d41204ead4..638990b854018 100644 --- a/apps/server/src/kin/memory/MemoryWriter.ts +++ b/apps/server/src/kin/memory/MemoryWriter.ts @@ -35,6 +35,7 @@ import { gitHubApp } from "../github/KinGitHubApp.ts"; import { MemoryConfig } from "./MemoryConfig.ts"; import { memoryIdentity } from "./memoryIdentity.ts"; import { + admittedId, Memory, MemoryCheckoutInvalid, MemoryRecoveryHooks, @@ -324,9 +325,6 @@ export class MemoryWriter extends Context.Service< readonly landShadows: (orgId: KinOrgId) => Effect.Effect; } >()("t3/kin/memory/MemoryWriter") {} -// Through `Memory.anchor`, the table's owner: a `kin_memory_heads` row no branch uses, holding the -// shadow head landed. -const shadowLanded = (agentId: string) => `kin/shadow-landed/${agentId}`; // The held line (`deliverHeld`) telling the owner what of a lead's shadow stayed behind. const shadowNoticeKind = (agentId: string) => `kin-memory:shadow-landed:${agentId}`; // Why a shadow note stayed off the default branch, in the owner's words. @@ -338,6 +336,17 @@ const heldWhy = { unverified: "Kin couldn't confirm where it came from, so it left it out.", clash: "It clashes with another note in Memory, so Kin left it out.", }; +// What a landing kept back, as its owner notice names it (`null`: a name the scan flags). +const HeldNotes = Schema.fromJsonString( + Schema.Array( + Schema.Struct({ + path: Schema.NullOr(Schema.String), + why: Schema.Literals(Object.keys(heldWhy) as Array), + }), + ), +); +const encodeHeld = Schema.encodeEffect(HeldNotes); +const decodeHeld = Schema.decodeEffect(HeldNotes); const isRepoSlug = Schema.is(RepoSlug); const dreamBranch = /^dream\/\d{4}-\d{2}-\d{2}$/; const folders = [ @@ -842,6 +851,8 @@ const make = Effect.gen(function* () { readonly message: string; /** Runs in the transaction that records the new head. */ readonly landed?: (commit: string) => Effect.Effect; + /** Runs once the commit exists, before anything can publish it. */ + readonly pushing?: (commit: string) => Effect.Effect; }, ) { const { writer, branch, head, headFiles } = input; @@ -875,6 +886,7 @@ const make = Effect.gen(function* () { }); if (findings.length) return yield* new MemorySecretBlocked({ orgId, findings }); const commit = yield* writeCommit(orgId, writer, head, headFiles, changes, input.message); + if (input.pushing !== undefined) yield* input.pushing(commit); if (onMain && mainWrites === "pull_request") { yield* git(orgId, writer, ["update-ref", `refs/heads/${branch}`, commit, head]); yield* record(commit); @@ -1968,13 +1980,16 @@ const make = Effect.gen(function* () { branch: string; owner: string; ownerChat: string; + pushed: string | null; + held: string | null; }>`SELECT l.agent_id AS "agentId", l.name, h.branch, a.owner_person_id AS owner, - l.owner_chat_id AS "ownerChat" FROM kin_memory_heads h + l.owner_chat_id AS "ownerChat", s.commit_id AS pushed, s.held_json AS held + 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) + LEFT JOIN kin_shadow_landings s ON s.org_id = l.org_id AND s.agent_id = l.agent_id + WHERE h.org_id = ${orgId} AND s.landed_at IS NULL 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; @@ -2099,26 +2114,30 @@ const make = Effect.gen(function* () { files.delete(path); } // Two notes with one id fail every read of it (`MemoryDuplicateId`), so the tree that - // would land is checked with ids as `Memory.load` reads them; holding a note back puts - // the default branch's at its path again, so it repeats until nothing clashes. + // would land is checked with ids only for files `Memory.load` admits, as it reads + // them; holding a note back puts the default branch's at its path again, so it + // repeats until nothing clashes. const reserved = new Map(); - for (const [path, bytes] of headFiles) - if (folders.some((folder) => path.startsWith(`${folder}/`))) { - const item = yield* parseFrontMatter( - orgId, - path, - bytes.toString("utf8"), - false, - true, - ).pipe(Effect.option); - if (Option.isSome(item)) reserved.set(path, item.value.frontMatter.id); - } + for (const { relative, mode } of yield* treeAt(orgId, writer, head)) { + const bytes = headFiles.get(relative); + const id = + bytes === undefined ? undefined : yield* admittedId(orgId, relative, mode, bytes); + if (id !== undefined) reserved.set(relative, id); + } + // A landed file is committed as a regular file. + const claims = new Map(); + for (const [path, text] of files) { + const id = yield* admittedId(orgId, path, "100644", Buffer.from(text)); + if (id !== undefined) claims.set(path, id); + } for (;;) { const count = new Map(); const claim = (id: string) => count.set(id, (count.get(id) ?? 0) + 1); for (const [path, id] of reserved) if (!files.has(path)) claim(id); - for (const item of items.values()) claim(item.id); - const clashing = [...items].filter(([, item]) => count.get(item.id)! > 1); + for (const [path, id] of claims) if (items.has(path)) claim(id); + const clashing = [...claims].filter( + ([path, id]) => items.has(path) && count.get(id)! > 1, + ); if (clashing.length === 0) break; for (const [path] of clashing) { files.delete(path); @@ -2128,67 +2147,109 @@ const make = Effect.gen(function* () { } return { headFiles, files, items, held }; }); - const landingMessage = (agentId: string, shadowHead: string) => - `kin(${agentId}): land notes kept at L0\n\nKin-Shadow-Landed: ${shadowHead}\n`; - // A landing the remote took while the transaction marking it failed is on the default - // branch once sync adopts it. Found by its message and checked to carry only this - // shadow's notes, so the retry marks it instead of landing again what was removed since. - const earlierLanding = Effect.fn("MemoryWriter.landShadows.earlier")(function* ( - agentId: string, - shadowHead: string, - shadowFiles: ReadonlyMap, - head: string, + // The landing's state is written before its commit can reach the remote, so a retry + // after a push whose mark failed checks for that exact commit; the default branch is + // fetched first, and nothing is decided when it can't be. + const onRemoteMain = Effect.fn("MemoryWriter.landShadows.onRemoteMain")(function* ( + commit: string, ) { - const candidates = (yield* git(orgId, writer, [ - "log", - "--format=%H", - "--fixed-strings", - `--grep=Kin-Shadow-Landed: ${shadowHead}`, - head, - ])) - .split("\n") - .filter((line) => line !== ""); - for (const commit of candidates) { - const message = yield* git(orgId, writer, ["show", "-s", "--format=%B", commit]); - if (message.trim() !== landingMessage(agentId, shadowHead).trim()) continue; - const [, ...parents] = (yield* git(orgId, writer, [ - "rev-list", - "--parents", - "-n", - "1", - commit, - ])).split(" "); - const landedFiles = yield* filesAt(orgId, writer, commit); - const parentFiles = - parents.length === 1 ? yield* filesAt(orgId, writer, parents[0]!) : undefined; - const landed = new Set(); - const matches = - parentFiles !== undefined && - [...new Set([...parentFiles.keys(), ...landedFiles.keys()])].every((path) => { - const bytes = landedFiles.get(path); - if (path === "INDEX.md" || same(parentFiles.get(path), bytes)) return true; - const kept = shadowFiles.get(path); - landed.add(path); - return ( - folders.some((folder) => path.startsWith(`${folder}/`)) && - bytes !== undefined && - kept !== undefined && - bytes.equals(Buffer.from(withoutQuote(kept.toString("utf8")))) - ); - }); - if (!matches) - return yield* new MemorySyncConflict({ - orgId, - operation: "landShadows", - reason: "An earlier landing of this shadow branch holds more than its notes", - }); - return { parent: parents[0]!, landed }; - } - return undefined; + const advertised = yield* git(orgId, writer, [ + "ls-remote", + "--", + repo.repoUrl, + `refs/heads/${main}`, + ]); + const [sha, ref] = advertised.split(/\s+/); + if ( + !sha || + !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(sha) || + ref !== `refs/heads/${main}` + ) + return yield* new MemoryCheckoutInvalid({ + orgId, + operation: "landShadows", + reason: "Invalid remote advertisement", + }); + yield* git(orgId, writer, ["fetch", "--", repo.repoUrl, sha]); + // A wrong "no" (the commit gone from this checkout, say) only plans again, and that + // push can't replace a default branch that holds the commit. + return yield* git(orgId, writer, ["merge-base", "--is-ancestor", commit, sha]).pipe( + Effect.as(true), + Effect.catchTags({ MemoryError: () => Effect.succeed(false) }), + ); }); // A lead that fails is logged and left unmarked, so the next sync retries it alone. - for (const { agentId, name, branch, owner, ownerChat } of pending) + for (const { agentId, name, branch, owner, ownerChat, pushed, held: saved } of pending) yield* Effect.gen(function* () { + const at = yield* Clock.currentTimeMillis; + const record = ( + commit: string | null, + shown: ReadonlyArray<{ path: string | null; why: keyof typeof heldWhy }>, + landedAt: number | null, + ) => + encodeHeld(shown).pipe( + Effect.mapError( + (cause) => new MemoryError({ orgId, operation: "landShadows", cause }), + ), + Effect.flatMap((held) => + sql`INSERT INTO kin_shadow_landings (org_id, agent_id, commit_id, held_json, + landed_at) + VALUES (${orgId}, ${agentId}, ${commit}, ${held}, ${landedAt}) + ON CONFLICT (org_id, agent_id) DO UPDATE SET commit_id = excluded.commit_id, + held_json = excluded.held_json, landed_at = excluded.landed_at`.pipe(toSql), + ), + Effect.asVoid, + ); + // Kept with the mark, so a restart can't lose it; `deliverHeld` posts it once, on + // its own, under an id of its own, after any quiet hours. + const landed = ( + commit: string | null, + shown: ReadonlyArray<{ path: string | null; why: keyof typeof heldWhy }>, + ) => + record(commit, shown, at).pipe( + Effect.andThen( + shown.length === 0 + ? Effect.void + : sql`INSERT INTO kin_held_posts (hold_id, org_id, chat_id, person_id, + kind, body, audience, held_at, deliver_at) + VALUES (${`shadow-landed:${orgId}:${agentId}`}, ${orgId}, ${ownerChat}, + ${owner}, ${shadowNoticeKind(agentId)}, + ${`Some of ${name}'s earlier notes weren't added to Memory:\n${shown.map(({ path, why }) => `- ${path ?? "One note"}: ${heldWhy[why]}`).join("\n")}`}, + 'owner', ${at}, ${at}) + ON CONFLICT DO NOTHING`.pipe(toSql, Effect.asVoid), + ), + ); + const landedNow = ( + commit: string | null, + shown: ReadonlyArray<{ path: string | null; why: keyof typeof heldWhy }>, + ) => + sql.withTransaction(landed(commit, shown)).pipe( + Effect.catchTags({ + SqlError: (cause) => + Effect.fail(toPersistenceSqlError("MemoryWriter.landShadows")(cause)), + }), + ); + const logHeld = ( + shown: ReadonlyArray<{ path: string | null; why: keyof typeof heldWhy }>, + ) => + shown.length === 0 + ? Effect.void + : recovery.notify({ + orgId, + branch, + reason: `Left on the shadow branch: ${shown.map(({ path, why }) => `${path ?? "[redacted]"} (${why})`).join(", ")}`, + }); + // Retired notes of a landing the remote took end their sharing as + // `reconcileSharing` sweeps the default branch. + if (pushed !== null && saved !== null && (yield* onRemoteMain(pushed))) { + const shown = yield* decodeHeld(saved).pipe( + Effect.mapError( + (cause) => new MemoryError({ orgId, operation: "landShadows", cause }), + ), + ); + yield* landedNow(pushed, shown); + return yield* logHeld(shown); + } const tip = yield* branchHead(orgId, writer, branch); // `--before` takes its own second, and a commit that second may be after K035 ran. const shadowHead = yield* git(orgId, writer, [ @@ -2197,64 +2258,22 @@ const make = Effect.gen(function* () { `--before=@${Math.ceil(cutOverSeconds) - 1}`, tip, ]); - const mark = memory - .anchor(orgId, shadowLanded(agentId), shadowHead || tip) - .pipe(Effect.asVoid); - if (shadowHead === "") return yield* mark; + if (shadowHead === "") return yield* landedNow(null, []); const shadowFiles = yield* filesAt(orgId, writer, shadowHead); const head = yield* branchHead(orgId, writer, main); - const earlier = yield* earlierLanding(agentId, shadowHead, shadowFiles, head); - // Replayed against the head it landed on, so the owner hears what that landing left. - const plan = yield* planLanding( - agentId, - owner, - shadowHead, - shadowFiles, - earlier?.parent ?? head, - ); - const held = - earlier === undefined - ? plan.held - : [ - ...plan.held.filter(({ path }) => !earlier.landed.has(path)), - ...[...plan.files.keys()] - .filter((path) => !earlier.landed.has(path)) - .map((path) => ({ path, why: "unverified" as const })), - ]; + const plan = yield* planLanding(agentId, owner, shadowHead, shadowFiles, head); // A name the scan flags stays out of the owner's chat and the log. - const shown: Array<{ path: string | undefined; why: keyof typeof heldWhy }> = []; - for (const { path, why } of held.toSorted((a, b) => a.path.localeCompare(b.path))) { + const shown: Array<{ path: string | null; why: keyof typeof heldWhy }> = []; + for (const { path, why } of plan.held.toSorted((a, b) => + a.path.localeCompare(b.path), + )) { const findings = yield* scanner.scan({ orgId, files: [{ path, content: new Uint8Array() }], }); - shown.push({ path: findings.length > 0 ? undefined : path, why }); + shown.push({ path: findings.length > 0 ? null : path, why }); } - const lines = shown.map( - ({ path, why }) => `- ${path ?? "One note"}: ${heldWhy[why]}`, - ); - // Kept with the marker, so a restart can't lose it; `deliverHeld` posts it once, - // on its own, under an id of its own, after any quiet hours. - const at = yield* Clock.currentTimeMillis; - const told = - shown.length === 0 - ? Effect.void - : sql`INSERT INTO kin_held_posts (hold_id, org_id, chat_id, person_id, kind, - body, audience, held_at, deliver_at) - VALUES (${`shadow-landed:${orgId}:${agentId}`}, ${orgId}, ${ownerChat}, - ${owner}, ${shadowNoticeKind(agentId)}, - ${`Some of ${name}'s earlier notes weren't added to Memory:\n${lines.join("\n")}`}, - 'owner', ${at}, ${at}) - ON CONFLICT DO NOTHING`.pipe(toSql, Effect.asVoid); - const landed = mark.pipe(Effect.andThen(told)); - // An earlier landing's retired notes end their sharing as `reconcileSharing` sweeps. - if (earlier !== undefined || plan.files.size === 0) - yield* sql.withTransaction(landed).pipe( - Effect.catchTags({ - SqlError: (cause) => - Effect.fail(toPersistenceSqlError("MemoryWriter.landShadows")(cause)), - }), - ); + if (plan.files.size === 0) yield* landedNow(null, shown); else { const ending = [...plan.items.values()].filter(retired).map((item) => item.id); yield* ownerCommit(orgId, { @@ -2264,17 +2283,14 @@ const make = Effect.gen(function* () { head, headFiles: plan.headFiles, files: plan.files, - message: landingMessage(agentId, shadowHead), + message: `kin(${agentId}): land notes kept at L0`, + pushing: (commit) => record(commit, shown, null), // With the mark, so a commit that fails leaves sharing as it was for the retry. - landed: () => endSharing(orgId, ending).pipe(Effect.andThen(landed)), + landed: (commit) => + endSharing(orgId, ending).pipe(Effect.andThen(landed(commit, shown))), }); } - if (shown.length > 0) - yield* recovery.notify({ - orgId, - branch, - reason: `Left on the shadow branch: ${shown.map(({ path, why }) => `${path ?? "[redacted]"} (${why})`).join(", ")}`, - }); + yield* logHeld(shown); }).pipe( Effect.catchCauseIf( (cause) => !Cause.hasInterruptsOnly(cause), diff --git a/apps/server/src/kin/people/leaver.test.ts b/apps/server/src/kin/people/leaver.test.ts index e7558d3684b56..ae43d910c7a21 100644 --- a/apps/server/src/kin/people/leaver.test.ts +++ b/apps/server/src/kin/people/leaver.test.ts @@ -953,6 +953,8 @@ const HOLDS_SOMEONE: Record = { kin_schedules: "agent_id said_by", kin_session_bindings: "person_id", kin_shadow_entries: "agent_id", + // A retired lead's landing is history; only live leads land (`MemoryWriter.landShadows`). + kin_shadow_landings: "agent_id", kin_social_posts: "agent_id confirmed_by", kin_tasks_keys: "person_id", kin_team_agents: "agent_id set_by", diff --git a/apps/server/src/kin/persistence/KinMigrations.test.ts b/apps/server/src/kin/persistence/KinMigrations.test.ts index 7f0e3ebeef627..1d20480ca452c 100644 --- a/apps/server/src/kin/persistence/KinMigrations.test.ts +++ b/apps/server/src/kin/persistence/KinMigrations.test.ts @@ -191,6 +191,7 @@ const tableNames = [ "kin_secret_allow", "kin_session_bindings", "kin_shadow_entries", + "kin_shadow_landings", "kin_social_groups", "kin_social_posts", "kin_statement_password_budget", @@ -2377,6 +2378,7 @@ describe("Kin migrations", () => { [237, "CardTapDeliveries"], [238, "BillSenders"], [239, "BillMail"], + [240, "ShadowLandings"], ]); assert.deepStrictEqual(yield* sql`SELECT * FROM kin_bill_reads`, [ { @@ -2449,7 +2451,10 @@ describe("Kin migrations", () => { VALUES ('org', 'hash', 'attachment', 'chat', 'message', 'bill.pdf', 'file', 'application/pdf', 8, 'batch', 0, 'finance', 'chat', 'widget', 'rhea', 1, 'waiting')`; const before = yield* sql`SELECT * FROM kin_bill_reads`; - assert.deepStrictEqual(yield* runKinMigrations(), [[239, "BillMail"]]); + assert.deepStrictEqual(yield* runKinMigrations(), [ + [239, "BillMail"], + [240, "ShadowLandings"], + ]); assert.deepStrictEqual(yield* sql`SELECT * FROM kin_bill_reads`, [ { ...before[0], mail_from: null, mail_at: null }, ]); @@ -2457,8 +2462,11 @@ describe("Kin migrations", () => { yield* sql`INSERT INTO kin_bill_mail (org_id, connection_id, message_id, address, state, next_at, queued_at) VALUES ('org', 'box', 'message', 'billing@inkspot.example', 'waiting', 2, 2)`; - yield* sql`DELETE FROM kin_sql_migrations WHERE migration_id = 239`; - assert.deepStrictEqual(yield* runKinMigrations(), [[239, "BillMail"]]); + yield* sql`DELETE FROM kin_sql_migrations WHERE migration_id >= 239`; + assert.deepStrictEqual(yield* runKinMigrations(), [ + [239, "BillMail"], + [240, "ShadowLandings"], + ]); assert.deepStrictEqual(yield* sql`SELECT * FROM kin_bill_reads`, [ { ...before[0], mail_from: "billing@inkspot.example", mail_at: 2 }, ]); diff --git a/apps/server/src/kin/persistence/KinMigrations.ts b/apps/server/src/kin/persistence/KinMigrations.ts index 1cf8758a65f71..97b2d4ebe39a8 100644 --- a/apps/server/src/kin/persistence/KinMigrations.ts +++ b/apps/server/src/kin/persistence/KinMigrations.ts @@ -160,6 +160,7 @@ import BillCrops from "./migrations/K236_BillCrops.ts"; import CardTapDeliveries from "./migrations/K237_CardTapDeliveries.ts"; import BillSenders from "./migrations/K238_BillSenders.ts"; import BillMail from "./migrations/K239_BillMail.ts"; +import ShadowLandings from "./migrations/K240_ShadowLandings.ts"; import * as Effect from "effect/Effect"; import * as Migrator from "effect/sql/Migrator"; @@ -401,6 +402,7 @@ const migrations = { "237_CardTapDeliveries": CardTapDeliveries, "238_BillSenders": BillSenders, "239_BillMail": BillMail, + "240_ShadowLandings": ShadowLandings, }; const loader = Migrator.fromRecord(migrations); diff --git a/apps/server/src/kin/persistence/migrations/K240_ShadowLandings.ts b/apps/server/src/kin/persistence/migrations/K240_ShadowLandings.ts new file mode 100644 index 0000000000000..93aace235a7e0 --- /dev/null +++ b/apps/server/src/kin/persistence/migrations/K240_ShadowLandings.ts @@ -0,0 +1,16 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +// One row per lead whose L0 shadow notes `MemoryWriter.landShadows` has tried to land. It is +// written before the push, so a retry checks for that exact commit instead of guessing. +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`CREATE TABLE IF NOT EXISTS kin_shadow_landings ( + org_id TEXT NOT NULL, + agent_id TEXT NOT NULL, + commit_id TEXT, + held_json TEXT NOT NULL, + landed_at INTEGER, + PRIMARY KEY (org_id, agent_id) + )`; +}); From a486f69736cef064058306100ce84b0de20e53f4 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sat, 28 Nov 2026 11:54:30 +0530 Subject: [PATCH 11/13] test(kin): let K241's migration tests run up to whatever migration is last People-change: none Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/persistence/KinMigrations.test.ts | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/apps/server/src/kin/persistence/KinMigrations.test.ts b/apps/server/src/kin/persistence/KinMigrations.test.ts index 44d6f9b6bb19a..285df3d756fa9 100644 --- a/apps/server/src/kin/persistence/KinMigrations.test.ts +++ b/apps/server/src/kin/persistence/KinMigrations.test.ts @@ -2450,7 +2450,7 @@ describe("Kin migrations", () => { const ids = sql<{ org: string; attachment: string; preview: string | null }>` SELECT org_id AS org, attachment_id AS attachment, preview_id AS preview FROM kin_bill_reads ORDER BY org_id, sha256`; - assert.deepStrictEqual(yield* runKinMigrations(), [[241, "BillPreviewIds"]]); + assert.deepStrictEqual(yield* runKinMigrations(), kinMigrationsFrom(241)); assert.deepStrictEqual(yield* ids, [ { org: "org-ambermill", attachment: ambermill, preview: billPhotoPreviewId(ambermill) }, { @@ -2471,7 +2471,7 @@ describe("Kin migrations", () => { yield* sql`UPDATE kin_bill_reads SET preview_id = NULL WHERE org_id = 'org-tidewater'`; const held = yield* sql`SELECT * FROM kin_bill_reads ORDER BY org_id, sha256`; yield* sql`DELETE FROM kin_sql_migrations WHERE migration_id >= 241`; - assert.deepStrictEqual(yield* runKinMigrations(), [[241, "BillPreviewIds"]]); + assert.deepStrictEqual(yield* runKinMigrations(), kinMigrationsFrom(241)); assert.deepStrictEqual( yield* sql`SELECT * FROM kin_bill_reads ORDER BY org_id, sha256`, held, @@ -2570,15 +2570,11 @@ describe("Kin migrations", () => { VALUES ('org', ${hash}, ${id}, 'chat', 'message', ${name}, ${type}, ${mime}, 8, 'batch', 0, 'finance', 'chat', 'widget', 'rhea', 1, 'waiting', 'billing@inkspot.example', 2)`; const before = yield* sql`SELECT * FROM kin_bill_reads ORDER BY sha256`; - assert.deepStrictEqual(yield* runKinMigrations(), [ - [240, "RemovedRuleCards"], - [241, "BillPreviewIds"], - ]); + assert.deepStrictEqual(yield* runKinMigrations(), kinMigrationsFrom(240)); assert.deepStrictEqual(yield* sql`SELECT * FROM kin_bill_reads ORDER BY sha256`, [ { ...before[0], preview_id: billPhotoPreviewId(photo) }, { ...before[1], preview_id: null }, ]); - assert.deepStrictEqual(kinMigrations.at(-1), [241, "BillPreviewIds"]); assert.deepStrictEqual(yield* runKinMigrations(), []); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); From 8e8b6b415b1cdd54bd14afacd7768ac1d25452a9 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Mon, 30 Nov 2026 10:10:03 +0530 Subject: [PATCH 12/13] fix(kin): a pull-request landing records its anchor before the local ref In pull-request mode the default branch's record is its SQLite anchor: branchHead and the lander both read it. The owner commit moved the local ref first, so a failed record left local main ahead of the anchor, and the next sync reset it and planned the landing again. The anchor and any landing mark now move first, the local ref follows (or catches up at the next write), and the lander is always signalled. A landing retry checks its saved commit against the anchor in pull-request mode and against the fetched remote for direct pushes. A shadow note Memory's reader gives no id, such as a person note filed under claims/, now stays behind as unreadable. People-change: none Co-Authored-By: Claude Opus 5.5 --- .../src/kin/memory/MemoryWriter.test.ts | 95 +++++++++++++++++++ apps/server/src/kin/memory/MemoryWriter.ts | 57 +++++++---- 2 files changed, 133 insertions(+), 19 deletions(-) diff --git a/apps/server/src/kin/memory/MemoryWriter.test.ts b/apps/server/src/kin/memory/MemoryWriter.test.ts index 9714d8b6f42d8..41a53c257499b 100644 --- a/apps/server/src/kin/memory/MemoryWriter.test.ts +++ b/apps/server/src/kin/memory/MemoryWriter.test.ts @@ -3269,6 +3269,72 @@ it.effect("pull-request mode with a memory repo off GitHub lands on the local de ), ); +it.effect( + "an interrupted landing in pull-request mode leaves the default branch as recorded and lands next time", + () => + landingFixture( + ({ notices }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const memory = yield* Memory.Memory; + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + const before = yield* memory.anchor(orgId, "main"); + const count = notices.length; + // The transaction that records the new head and the mark fails. + yield* marksFail(true); + yield* writer.landShadows(orgId); + yield* marksFail(false); + assert.strictEqual(yield* memory.anchor(orgId, "main"), before); + assert.strictEqual(yield* localMain, before); + assert.deepStrictEqual(yield* landedMarks, []); + + // The next sync: quotes are swept on every branch first, then the landing retries. + yield* writer.stripQuotes(orgId); + yield* writer.landShadows(orgId); + const landed = yield* memory.anchor(orgId, "main"); + assert.notStrictEqual(landed, before); + assert.strictEqual(yield* localMain, landed); + assert.deepStrictEqual(yield* landedMarks, [agentId]); + assert.deepStrictEqual(notices.slice(count), []); + }), + { offGitHubPullRequests: true }, + ), +); + +it.effect( + "a pull-request landing whose local ref can't move is still recorded for the lander", + () => + landingFixture( + () => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + const memory = yield* Memory.Memory; + const fs = yield* FileSystem.FileSystem; + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + const before = yield* memory.anchor(orgId, "main"); + const { writer: checkout } = yield* memory.ensureCheckouts(orgId); + const lock = `${checkout}/.git/refs/heads/main.lock`; + yield* fs.writeFileString(lock, ""); + yield* writer.landShadows(orgId); + yield* fs.remove(lock); + // The anchor, which the lander lands from, holds the landing and its mark. + const landed = yield* memory.anchor(orgId, "main"); + assert.notStrictEqual(landed, before); + assert.deepStrictEqual(yield* landedMarks, [agentId]); + assert.strictEqual(yield* localMain, before); + + // The next write's `branchHead` brings the local ref up to the anchor. + yield* writer.stripQuotes(orgId); + assert.strictEqual(yield* localMain, landed); + yield* writer.landShadows(orgId); + assert.strictEqual(yield* memory.anchor(orgId, "main"), landed); + }), + { offGitHubPullRequests: true }, + ), +); + // A shadow note citing the owner's message `m1` in their chat with the lead. const cited = (id: string, title: string, extra: Record = {}) => fixtureItem({ @@ -3283,6 +3349,35 @@ const cited = (id: string, title: string, extra: Record = {}) = ...extra, }); +it.effect("a shadow note in a folder its kind doesn't belong in stays behind as unreadable", () => + landingFixture(({ bare }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + yield* said("m1", "2026-10-30T00:00:00.000Z"); + yield* writer.stage(orgId, "wake0", personNote("alex", "Alex leads design")); + yield* wokeBeforeCutOver(writer, "wake0"); + // Its source is traced, so only where it's filed keeps it off the default branch. + yield* commitDirectly( + bare, + Memory.shadowBranch(agentId), + { add: { "claims/x.md": cited("x", "X, filed as a claim") } }, + preCutOver, + ); + + yield* writer.landShadows(orgId); + const tree = (yield* bare(["ls-tree", "-r", "--name-only", "main"])).split("\n"); + assert.include(tree, "people/alex.md"); + assert.notInclude(tree, "claims/x.md"); + assert.deepStrictEqual( + (yield* toldOwner).map((row) => row.body), + [ + "Some of Lead's earlier notes weren't added to Memory:\n- claims/x.md: It couldn't be read.", + ], + ); + }), + ), +); + it.effect("a shadow note whose id only a held-back note would free stays behind too", () => landingFixture(({ bare, setLevel }) => Effect.gen(function* () { diff --git a/apps/server/src/kin/memory/MemoryWriter.ts b/apps/server/src/kin/memory/MemoryWriter.ts index b5a7fe9574034..b63a9e6935778 100644 --- a/apps/server/src/kin/memory/MemoryWriter.ts +++ b/apps/server/src/kin/memory/MemoryWriter.ts @@ -937,9 +937,25 @@ const make = Effect.gen(function* () { const commit = yield* writeCommit(orgId, writer, head, headFiles, changes, input.message); if (input.pushing !== undefined) yield* input.pushing(commit); if (onMain && mainWrites === "pull_request") { - yield* git(orgId, writer, ["update-ref", `refs/heads/${branch}`, commit, head]); - yield* record(commit); - yield* lander.signal(orgId); + // The anchor is the default branch's record here (`branchHead` and the lander read it), so it + // moves first, with any landing mark; a local ref that then fails to follow catches up at + // the next `branchHead`, and the lander hears of it either way. + yield* record(commit).pipe( + Effect.andThen( + git(orgId, writer, ["update-ref", `refs/heads/${branch}`, commit, head]).pipe( + Effect.catch((error) => + Effect.logWarning( + "The default branch's ref will follow its anchor at the next write", + { + orgId, + errorTag: error._tag, + }, + ), + ), + ), + ), + Effect.ensuring(lander.signal(orgId)), + ); } else { // Push first, so a rejected push leaves the local branch where it was. yield* git(orgId, writer, [ @@ -2230,9 +2246,13 @@ const make = Effect.gen(function* () { else files.set(path, withoutQuote(bytes.toString("utf8"))); } const items = new Map(); + // A landed file is committed as a regular file. + const claims = new Map(); for (const [path, text] of files) { const item = yield* parsedAt(path, text); - if (Option.isNone(item)) held.push({ path, why: "unreadable" }); + // Memory's reader skips a note it gives no id, one in the wrong folder say. + const id = yield* admittedId(orgId, path, "100644", Buffer.from(text)); + if (Option.isNone(item) || id === undefined) held.push({ path, why: "unreadable" }); else if ( (yield* scanner.scan({ orgId, files: [{ path, content: Buffer.from(text) }] })) .length > 0 @@ -2242,6 +2262,7 @@ const make = Effect.gen(function* () { held.push({ path, why: "unverified" }); else { items.set(path, item.value); + claims.set(path, id); continue; } files.delete(path); @@ -2257,12 +2278,6 @@ const make = Effect.gen(function* () { bytes === undefined ? undefined : yield* admittedId(orgId, relative, mode, bytes); if (id !== undefined) reserved.set(relative, id); } - // A landed file is committed as a regular file. - const claims = new Map(); - for (const [path, text] of files) { - const id = yield* admittedId(orgId, path, "100644", Buffer.from(text)); - if (id !== undefined) claims.set(path, id); - } for (;;) { const count = new Map(); const claim = (id: string) => count.set(id, (count.get(id) ?? 0) + 1); @@ -2280,12 +2295,7 @@ const make = Effect.gen(function* () { } return { headFiles, files, items, held }; }); - // The landing's state is written before its commit can reach the remote, so a retry - // after a push whose mark failed checks for that exact commit; the default branch is - // fetched first, and nothing is decided when it can't be. - const onRemoteMain = Effect.fn("MemoryWriter.landShadows.onRemoteMain")(function* ( - commit: string, - ) { + const remoteMain = Effect.gen(function* () { const advertised = yield* git(orgId, writer, [ "ls-remote", "--", @@ -2304,9 +2314,18 @@ const make = Effect.gen(function* () { reason: "Invalid remote advertisement", }); yield* git(orgId, writer, ["fetch", "--", repo.repoUrl, sha]); + return sha; + }); + // The landing's state is written before its commit can reach the default branch's record, + // so a retry after a mark that failed checks for that exact commit there. Pull-request + // mode's record is the anchor, which moves with the mark. A direct push's is the remote, + // fetched first; nothing is decided when it can't be. + const onMain = Effect.fn("MemoryWriter.landShadows.onMain")(function* (commit: string) { + const tip = + mainWrites === "pull_request" ? yield* memory.anchor(orgId, main) : yield* remoteMain; // A wrong "no" (the commit gone from this checkout, say) only plans again, and that - // push can't replace a default branch that holds the commit. - return yield* git(orgId, writer, ["merge-base", "--is-ancestor", commit, sha]).pipe( + // landing can't remove what a default branch holding the commit has. + return yield* git(orgId, writer, ["merge-base", "--is-ancestor", commit, tip]).pipe( Effect.as(true), Effect.catchTags({ MemoryError: () => Effect.succeed(false) }), ); @@ -2374,7 +2393,7 @@ const make = Effect.gen(function* () { }); // Retired notes of a landing the remote took end their sharing as // `reconcileSharing` sweeps the default branch. - if (pushed !== null && saved !== null && (yield* onRemoteMain(pushed))) { + if (pushed !== null && saved !== null && (yield* onMain(pushed))) { const shown = yield* decodeHeld(saved).pipe( Effect.mapError( (cause) => new MemoryError({ orgId, operation: "landShadows", cause }), From 8e1e7a6c777afe5a69a1178b922a647fc201ef07 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Mon, 30 Nov 2026 11:24:26 +0530 Subject: [PATCH 13/13] test(kin): name the copied-landing-message test for what it checks People-change: The owner's message about a lead's earlier notes now survives a restart, comes as its own message per lead after quiet hours, never names a file whose name looks like a key, and says "Memory had a different version, so Kin kept it.", "This note was removed from Memory, so Kin left it out.", "It clashes with another note in Memory, so Kin left it out." or "Kin couldn't confirm where it came from, so it left it out."; notes from a member, a group chat or another host, notes at K035's own second, notes citing a chat message said after K035 ran or no longer kept (a cleared chat's included), and quotes no longer land, and nothing lands when Memory's history was replaced. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/memory/MemoryWriter.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/kin/memory/MemoryWriter.test.ts b/apps/server/src/kin/memory/MemoryWriter.test.ts index 41a53c257499b..f72747b16bc09 100644 --- a/apps/server/src/kin/memory/MemoryWriter.test.ts +++ b/apps/server/src/kin/memory/MemoryWriter.test.ts @@ -3570,7 +3570,7 @@ it.effect("a retry after a landing the remote took decides nothing until it can ), ); -it.effect("a commit that only copies a landing's message marks nothing", () => +it.effect("a commit that only copies a landing's message doesn't count as a landing", () => landingFixture(({ bare }) => Effect.gen(function* () { const writer = yield* Writer.MemoryWriter;