diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index 6b4f4a0d0ea81..8c51f038b57ab 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -747,6 +747,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"), @@ -1461,6 +1462,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"), @@ -1730,6 +1732,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 4a69fff3ec1e9..e78178586dbf8 100644 --- a/apps/server/src/kin/lead/layer.test.ts +++ b/apps/server/src/kin/lead/layer.test.ts @@ -257,6 +257,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 c3d42837e5464..c79d0d467be99 100644 --- a/apps/server/src/kin/lead/layer.ts +++ b/apps/server/src/kin/lead/layer.ts @@ -225,6 +225,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/Memory.ts b/apps/server/src/kin/memory/Memory.ts index d8fc6aa70d190..3cdbe53e2fdc3 100644 --- a/apps/server/src/kin/memory/Memory.ts +++ b/apps/server/src/kin/memory/Memory.ts @@ -384,6 +384,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; @@ -886,10 +915,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 = [ @@ -971,9 +998,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 0f10658e350a7..f72747b16bc09 100644 --- a/apps/server/src/kin/memory/MemoryWriter.test.ts +++ b/apps/server/src/kin/memory/MemoryWriter.test.ts @@ -5,6 +5,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, @@ -12,12 +13,14 @@ import { KinOrgId, KinPersonId, type MemoryItemHead, + type VcsError, VcsProcessSpawnError, } from "@t3tools/contracts"; 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"; @@ -26,7 +29,9 @@ 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 { deliverHeld } from "../triggers/heldDelivery.ts"; import { FIXTURE_QUOTE, FIXTURE_SAID, fixtureItem } from "./__fixtures__/items.ts"; import { authorise, @@ -2283,3 +2288,1370 @@ 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; + readonly owner?: string; + }>; + /** 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, + | Memory.Memory + | Writer.MemoryWriter + | Repository.KinChatRepository + | SqlClient.SqlClient + | FileSystem.FileSystem + | Vcs.VcsProcess + >, + options: { readonly offGitHubPullRequests?: boolean } = {}, +) => + 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; owner?: string }> = []; + let duringScan: + | { + readonly effect: Effect.Effect; + readonly when: (paths: ReadonlyArray) => boolean; + } + | 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; + if (once === undefined || !once.when(input.files.map((file) => file.path))) + return Effect.void; + duringScan = undefined; + return once.effect; + }).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, + 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.provide( + options.offGitHubPullRequests === true + ? Layer.mock(PullRequests.MemoryPullRequests)({}) + : Layer.empty, + ), + ); + 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})`; + // 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. + 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({ + setLevel: (next) => { + level = next; + }, + bare: (args) => git(root, [`--git-dir=${remote}`, ...args]), + notices, + duringScan: (effect, when = () => true) => { + duringScan = { effect, when }; + }, + }); + }).pipe(Effect.provide(layer)); + }).pipe( + Effect.provide( + Layer.mergeAll( + gitLayer, + NodeServices.layer, + Persistence.layer.pipe(Layer.provideMerge(Sqlite.layerMemory)), + ), + ), + 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(() => vi.stubEnv("GIT_COMMITTER_DATE", "2026-11-01T00:00:00Z")), + () => 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({ + id, + kind: "person", + title, + due: null, + on_due: undefined, + review_by: null, + 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; + /** 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; + readonly message?: string; + }, + 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"]), + ...(change.orphan === true + ? [] + : (change.parents ?? [before]).flatMap((parent) => ["-p", parent])), + "-m", + change.message ?? "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"; +// 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; + 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<{ 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); +}); +// Git in the writer checkout: its shadow branches reach the remote after a wake-up, not with it, +// and pull-request mode never pushes its default branch. +const inWriter = (args: ReadonlyArray) => + Effect.gen(function* () { + const memory = yield* Memory.Memory; + const vcs = yield* Vcs.VcsProcess; + const { writer: checkout } = yield* memory.ensureCheckouts(orgId); + return (yield* vcs.run({ + operation: "test.writer", + command: "git", + cwd: checkout, + args, + })).stdout.trim(); + }); +const localMain = inWriter(["rev-parse", "refs/heads/main"]); +// 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 }) => + 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* wokeBeforeCutOver(writer, "wake0"); + assert.include(yield* inWriter(["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* inWriter(["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* inWriter([ + "show", + `${(yield* writer.commitWakeup(orgId, "wake2", "completed")).commit}:INDEX.md`, + ]); + assert.include(index, "owner-repos"); + }), + ), +); + +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("owner-repos", "The owner's two main repos")); + 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"); + + yield* writer.landShadows(orgId); + 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* inWriter(["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 }) => + Effect.gen(function* () { + const writer = yield* Writer.MemoryWriter; + 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* 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"); + // A purge-like deletion on the default branch. + 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"); + assert.include( + yield* inWriter(["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( + (yield* toldOwner).map((row) => row.body), + [ + "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.", + ], + ); + }), + ), +); + +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* wokeBeforeCutOver(writer, "wake0"); + + yield* writer.landShadows(orgId); + assert.include(yield* bare(["show", "main:people/owner-repos.md"]), "two main repos"); + assert.deepStrictEqual(yield* landedMarks, [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* wokeBeforeCutOver(writer, "wake0"); + 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"); + 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.\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(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.", + ], + ); + }), + ), +); + +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* 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( + 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("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 its notes were checked, as the commit is scanned. + duringScan( + chats + .clearChat({ + orgId, + chatId: KinChatId.make("owner-chat"), + clearedAt: "2026-11-12T00:00:00.000Z", + clearedAtMs: 0, + }) + .pipe(Effect.asVoid, Effect.orDie), + (paths) => paths.includes("INDEX.md"), + ); + + 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* 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. 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": 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", + ); + + 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* 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/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.", + ], + ); + }), + ), +); + +// 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"); + // 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( + 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"), + "people/plain-before.md": cites("plain-before", "m-plain-before"), + "people/plain-after.md": cites("plain-after", "m-plain-after"), + }, + }, + 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.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.\n- people/plain-after.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* () { + 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* inWriter(["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* 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, 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, ["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) => ({ + 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 lands on the local default branch", () => + 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"); + const remote = yield* bare(["rev-parse", "main"]); + const before = yield* memory.anchor(orgId, "main"); + + yield* writer.landShadows(orgId); + const landed = yield* memory.anchor(orgId, "main"); + assert.notStrictEqual(landed, before); + assert.strictEqual(yield* localMain, landed); + assert.strictEqual(yield* bare(["rev-parse", "main"]), remote); + assert.deepStrictEqual(yield* landedMarks, [agentId]); + yield* memory.syncCheckout(orgId); + assert.strictEqual( + (yield* memory.readItem(orgId, KinMemoryItemId.make("alex"))).head.title, + "Alex leads design", + ); + }), + { offGitHubPullRequests: true }, + ), +); + +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({ + 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 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* () { + 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; + 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, + ); + 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* marksFail(false); + 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, [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, []); + }), + ), +); + +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 doesn't count as a landing", () => + 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* inWriter(["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 ca242900133f6..b63a9e6935778 100644 --- a/apps/server/src/kin/memory/MemoryWriter.ts +++ b/apps/server/src/kin/memory/MemoryWriter.ts @@ -39,6 +39,7 @@ import { gitHubApp } from "../github/KinGitHubApp.ts"; import { MemoryConfig } from "./MemoryConfig.ts"; import { memoryIdentity } from "./memoryIdentity.ts"; import { + admittedId, Memory, MemoryCheckoutInvalid, MemoryRecoveryHooks, @@ -62,7 +63,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"; @@ -76,6 +77,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."; @@ -341,8 +347,37 @@ 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 held when leads began working on the + * 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") {} +// 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 = { + 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.", +}; +// 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 dreamBranch = /^dream\/\d{4}-\d{2}-\d{2}$/; const folders = [ "objectives", @@ -865,6 +900,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; @@ -898,10 +935,27 @@ 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); - 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, [ @@ -2068,6 +2122,341 @@ 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; + name: string; + 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", 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 + 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; + const { writer } = yield* validate(orgId); + yield* refuseDuringPurge(orgId); + const repo = yield* repoFor(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 = (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); + 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, 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} + 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; + } + // 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 || !(utcMs(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" + 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; + }); + // 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(); + // 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); + // 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 + ) + held.push({ path, why: "secret" }); + else if (!(yield* provenOrigin(agentId, owner, item.value))) + held.push({ path, why: "unverified" }); + else { + items.set(path, item.value); + claims.set(path, id); + 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 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 { 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); + } + 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 [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); + items.delete(path); + held.push({ path, why: "clash" }); + } + } + return { headFiles, files, items, held }; + }); + const remoteMain = Effect.gen(function* () { + 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]); + 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 + // 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) }), + ); + }); + // A lead that fails is logged and left unmarked, so the next sync retries it alone. + 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* onMain(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, [ + "rev-list", + "-1", + `--before=@${Math.ceil(cutOverSeconds) - 1}`, + tip, + ]); + if (shadowHead === "") return yield* landedNow(null, []); + const shadowFiles = yield* filesAt(orgId, writer, shadowHead); + const head = yield* branchHead(orgId, writer, main); + 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 | 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 ? null : path, why }); + } + if (plan.files.size === 0) yield* landedNow(null, shown); + else { + const ending = [...plan.items.values()].filter(retired).map((item) => item.id); + yield* ownerCommit(orgId, { + writer, + repoUrl: repo.repoUrl, + branch: main, + head, + headFiles: plan.headFiles, + files: plan.files, + 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: (commit) => + endSharing(orgId, ending).pipe(Effect.andThen(landed(commit, shown))), + }); + } + yield* logHeld(shown); + }).pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("Kin could not land a lead's shadow notes", { + orgId, + branch, + cause, + }), + ), + ); + }), + ), + ), }); }); export const layer = Layer.effect(MemoryWriter, make).pipe( 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"); diff --git a/apps/server/src/kin/people/leaver.test.ts b/apps/server/src/kin/people/leaver.test.ts index ffcdca752c138..6511b13534024 100644 --- a/apps/server/src/kin/people/leaver.test.ts +++ b/apps/server/src/kin/people/leaver.test.ts @@ -1071,6 +1071,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 8aab666dd63da..6cd379173c06c 100644 --- a/apps/server/src/kin/persistence/KinMigrations.test.ts +++ b/apps/server/src/kin/persistence/KinMigrations.test.ts @@ -194,6 +194,7 @@ const tableNames = [ "kin_session_bindings", "kin_session_seen", "kin_shadow_entries", + "kin_shadow_landings", "kin_social_groups", "kin_social_posts", "kin_statement_password_budget", @@ -2401,6 +2402,7 @@ describe("Kin migrations", () => { [244, "CarryClocks"], [245, "CacheParts"], [246, "SessionSeen"], + [247, "ShadowLandings"], ]); assert.deepStrictEqual(yield* sql`SELECT * FROM kin_bill_reads`, [ { @@ -2466,14 +2468,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"], - [242, "RemovedRuleLimits"], - [243, "BillCorrections"], - [244, "CarryClocks"], - [245, "CacheParts"], - [246, "SessionSeen"], - ]); + assert.deepStrictEqual(yield* runKinMigrations(), kinMigrationsFrom(241)); assert.deepStrictEqual(yield* ids, [ { org: "org-ambermill", attachment: ambermill, preview: billPhotoPreviewId(ambermill) }, { @@ -2494,14 +2489,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"], - [242, "RemovedRuleLimits"], - [243, "BillCorrections"], - [244, "CarryClocks"], - [245, "CacheParts"], - [246, "SessionSeen"], - ]); + assert.deepStrictEqual(yield* runKinMigrations(), kinMigrationsFrom(241)); assert.deepStrictEqual( yield* sql`SELECT * FROM kin_bill_reads ORDER BY org_id, sha256`, held, @@ -2600,20 +2588,12 @@ 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"], - [242, "RemovedRuleLimits"], - [243, "BillCorrections"], - [244, "CarryClocks"], - [245, "CacheParts"], - [246, "SessionSeen"], - ]); + 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), [246, "SessionSeen"]); + assert.deepStrictEqual(kinMigrations.at(-1), [247, "ShadowLandings"]); assert.deepStrictEqual(yield* runKinMigrations(), []); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); @@ -3240,6 +3220,7 @@ describe("Kin migrations", () => { [244, "CarryClocks"], [245, "CacheParts"], [246, "SessionSeen"], + [247, "ShadowLandings"], ]); const requests = sql`SELECT last_request_at, last_request_kin_at, cache_part FROM kin_wakeups`; assert.deepStrictEqual(yield* requests, [ @@ -3259,6 +3240,7 @@ describe("Kin migrations", () => { [244, "CarryClocks"], [245, "CacheParts"], [246, "SessionSeen"], + [247, "ShadowLandings"], ]); assert.deepStrictEqual(yield* requests, [ { last_request_at: 42, last_request_kin_at: 100, cache_part: null }, diff --git a/apps/server/src/kin/persistence/KinMigrations.ts b/apps/server/src/kin/persistence/KinMigrations.ts index 6cf0c5d198260..a087246d7b497 100644 --- a/apps/server/src/kin/persistence/KinMigrations.ts +++ b/apps/server/src/kin/persistence/KinMigrations.ts @@ -167,6 +167,7 @@ import BillCorrections from "./migrations/K243_BillCorrections.ts"; import CarryClocks from "./migrations/K244_CarryClocks.ts"; import CacheParts from "./migrations/K245_CacheParts.ts"; import SessionSeen from "./migrations/K246_SessionSeen.ts"; +import ShadowLandings from "./migrations/K247_ShadowLandings.ts"; import * as Effect from "effect/Effect"; import * as Migrator from "effect/sql/Migrator"; @@ -415,6 +416,7 @@ const migrations = { "244_CarryClocks": CarryClocks, "245_CacheParts": CacheParts, "246_SessionSeen": SessionSeen, + "247_ShadowLandings": ShadowLandings, }; const loader = Migrator.fromRecord(migrations); diff --git a/apps/server/src/kin/persistence/migrations/K247_ShadowLandings.ts b/apps/server/src/kin/persistence/migrations/K247_ShadowLandings.ts new file mode 100644 index 0000000000000..93aace235a7e0 --- /dev/null +++ b/apps/server/src/kin/persistence/migrations/K247_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) + )`; +});