diff --git a/apps/server/src/kin/chat/clearedChatPrompt.test.ts b/apps/server/src/kin/chat/clearedChatPrompt.test.ts index 199e623d9af4..bc2377d5af86 100644 --- a/apps/server/src/kin/chat/clearedChatPrompt.test.ts +++ b/apps/server/src/kin/chat/clearedChatPrompt.test.ts @@ -54,6 +54,8 @@ const memory = Layer.succeed( ensureCheckouts: () => Effect.die("Unused"), prepareWakeup: () => Effect.die("Unused"), readIndex: () => Effect.die("Unused"), + rememberPublished: () => Effect.die("Unused"), + readRulesBook: () => Effect.die("Unused"), readRules: () => Effect.die("Unused"), query: () => Effect.succeed([]), readItem: () => Effect.die("Unused"), diff --git a/apps/server/src/kin/featureMap/feature-map.yaml b/apps/server/src/kin/featureMap/feature-map.yaml index f49c816336ed..6a79e044a6d5 100644 --- a/apps/server/src/kin/featureMap/feature-map.yaml +++ b/apps/server/src/kin/featureMap/feature-map.yaml @@ -459,6 +459,7 @@ features: proof: - apps/server/src/kin/memory/Memory.test.ts - apps/server/src/kin/memory/MemoryWriter.test.ts + - apps/server/src/kin/memory/MemoryChanges.test.ts # ── Tasks ────────────────────────────────────────────────────────────────────────────────── - id: tasks @@ -1911,6 +1912,8 @@ features: unlisted: "phone:KinBillsAdd": Where a photo or PDF shared into Kin lands; it opens the chat bills are added in at once. "web:team": Old address; opens the Settings modal on Team. + "rpc:kin.memory.readRules": Owner-only rulebook reader; editor client ships separately. + "rpc:kin.memory.saveRules": Owner-only rulebook editor; editor client ships separately. "web:memory": Old address; opens the Settings modal on Memory. "web:settings/approvals": The app's old address; opens Kin's Settings → Approvals. "web:settings/company": The app's old address; opens Kin's Settings → Company details. diff --git a/apps/server/src/kin/hostBackup.test.ts b/apps/server/src/kin/hostBackup.test.ts index ca735ea9b6ff..703869449368 100644 --- a/apps/server/src/kin/hostBackup.test.ts +++ b/apps/server/src/kin/hostBackup.test.ts @@ -373,64 +373,73 @@ it.effect("a memory write the writer refuses every night tells the owner once pe }).pipe(Effect.provide(daytimeServices)), ); -it.effect("background memory refusals open one silent notice in the owner's private chat", () => - Effect.gen(function* () { - yield* seed; - const sql = yield* SqlClient.SqlClient; - const { writeEpisode } = yield* MemoryRecoveryHooks; - if (writeEpisode === undefined) return assert.fail("Missing memory notices"); - yield* Effect.all( - [ - writeEpisode(orgId, "deleted-quotes", "remote"), - writeEpisode(orgId, "deleted-quotes", "remote"), - ], - { concurrency: "unbounded", discard: true }, - ); - yield* writeEpisode(orgId, "deleted-quotes", "scanner"); - yield* writeEpisode(orgId, "deleted-quotes", "remote"); - const rows = sql<{ chatId: string; person: string; silent: number; open: number }>`SELECT +it.effect.each(["deleted-quotes", "online-copy"] as const)( + "background %s refusals open one silent notice in the owner's private chat", + (operation) => + Effect.gen(function* () { + yield* seed; + const sql = yield* SqlClient.SqlClient; + const { writeEpisode } = yield* MemoryRecoveryHooks; + if (writeEpisode === undefined) return assert.fail("Missing memory notices"); + const refusal = operation === "online-copy" ? "direct-push-refused" : "remote"; + yield* Effect.all( + [writeEpisode(orgId, operation, refusal), writeEpisode(orgId, operation, refusal)], + { concurrency: "unbounded", discard: true }, + ); + if (operation === "online-copy") { + const rows = yield* sql<{ body: string }>`SELECT body FROM kin_messages + WHERE org_id = ${orgId} AND message_id LIKE 'kin-memory-write:%'`; + assert.deepStrictEqual(rows, [ + { + body: "Memory is saved here, but the repository refused to publish it; ask the host administrator to check write access and branch protection.", + }, + ]); + } + yield* writeEpisode(orgId, operation, "scanner"); + yield* writeEpisode(orgId, operation, refusal); + const rows = sql<{ chatId: string; person: string; silent: number; open: number }>`SELECT m.chat_id AS "chatId", w.person_id AS person, m.silent, w.resolved_at IS NULL AS open FROM kin_messages m JOIN kin_waiting w ON w.org_id = m.org_id AND w.message_id = m.message_id WHERE m.org_id = ${orgId} AND m.message_id LIKE 'kin-memory-write:%' ORDER BY m.seq`; - assert.deepStrictEqual(yield* rows, [ - { chatId: "rhea-chief", person: "rhea", silent: 1, open: 1 }, - { chatId: "rhea-chief", person: "rhea", silent: 1, open: 1 }, - ]); - const chat = yield* Chat.KinChatService; - const [answered] = yield* sql<{ waitingId: string }>`SELECT waiting_id AS "waitingId" - FROM kin_waiting WHERE org_id = ${orgId} AND message_id LIKE 'kin-memory-write:%:remote:%'`; - if (answered === undefined) return assert.fail("Missing owner notice"); - yield* chat.resolveNotice({ - orgId, - waitingId: KinWaitingId.make(answered.waitingId), - resolution: "answered", - }); - yield* writeEpisode(orgId, "deleted-quotes", "remote"); - assert.deepStrictEqual( - (yield* rows).map(({ open }) => open), - [0, 1], - ); - yield* writeEpisode(orgId, "deleted-quotes", undefined); - assert.deepStrictEqual( - (yield* rows).map(({ open }) => open), - [0, 0], - ); - yield* writeEpisode(orgId, "deleted-quotes", "remote"); - assert.deepStrictEqual( - (yield* rows).map(({ open }) => open), - [0, 0, 1], - ); - }).pipe( - Effect.provide( - OwnerNotices.layer.pipe( - Layer.provideMerge(services), - withFixtureClock(DAY_START + 13 * HOUR), + assert.deepStrictEqual(yield* rows, [ + { chatId: "rhea-chief", person: "rhea", silent: 1, open: 1 }, + { chatId: "rhea-chief", person: "rhea", silent: 1, open: 1 }, + ]); + const chat = yield* Chat.KinChatService; + const [answered] = yield* sql<{ waitingId: string }>`SELECT waiting_id AS "waitingId" + FROM kin_waiting WHERE org_id = ${orgId} AND message_id LIKE ${`kin-memory-write:%:${refusal}:%`}`; + if (answered === undefined) return assert.fail("Missing owner notice"); + yield* chat.resolveNotice({ + orgId, + waitingId: KinWaitingId.make(answered.waitingId), + resolution: "answered", + }); + yield* writeEpisode(orgId, operation, refusal); + assert.deepStrictEqual( + (yield* rows).map(({ open }) => open), + [0, 1], + ); + yield* writeEpisode(orgId, operation, undefined); + assert.deepStrictEqual( + (yield* rows).map(({ open }) => open), + [0, 0], + ); + yield* writeEpisode(orgId, operation, refusal); + assert.deepStrictEqual( + (yield* rows).map(({ open }) => open), + [0, 0, 1], + ); + }).pipe( + Effect.provide( + OwnerNotices.layer.pipe( + Layer.provideMerge(services), + withFixtureClock(DAY_START + 13 * HOUR), + ), ), ), - ), ); const decodeCard = Schema.decodeUnknownSync(Schema.fromJsonString(KinHostTroubleCard)); diff --git a/apps/server/src/kin/lead/LeadPrompt.test.ts b/apps/server/src/kin/lead/LeadPrompt.test.ts index dfd54b059aad..ba21485ee13b 100644 --- a/apps/server/src/kin/lead/LeadPrompt.test.ts +++ b/apps/server/src/kin/lead/LeadPrompt.test.ts @@ -4670,6 +4670,8 @@ const markedMemory = Layer.succeed( ensureCheckouts: () => Effect.die("Unused"), prepareWakeup: () => Effect.die("Unused"), readIndex: () => Effect.die("Unused"), + rememberPublished: () => Effect.die("Unused"), + readRulesBook: () => Effect.die("Unused"), readRules: () => Effect.die("Unused"), query: () => Effect.succeed([]), readItem: () => Effect.die("Unused"), diff --git a/apps/server/src/kin/lead/LeadPrompt.testkit.ts b/apps/server/src/kin/lead/LeadPrompt.testkit.ts index 248e6e8d0c9d..63025136113b 100644 --- a/apps/server/src/kin/lead/LeadPrompt.testkit.ts +++ b/apps/server/src/kin/lead/LeadPrompt.testkit.ts @@ -227,6 +227,8 @@ export const memory = Layer.succeed( ensureCheckouts: () => Effect.die("Unused"), prepareWakeup: () => Effect.die("Unused"), readIndex: () => Effect.die("Unused"), + rememberPublished: () => Effect.die("Unused"), + readRulesBook: () => Effect.die("Unused"), readRules: () => Effect.die("Unused"), // A reminder asked for in fixture-room, which only some tests create. query: () => diff --git a/apps/server/src/kin/lead/LeadPrompt.ts b/apps/server/src/kin/lead/LeadPrompt.ts index 27b34bb70af1..2d87b5204c29 100644 --- a/apps/server/src/kin/lead/LeadPrompt.ts +++ b/apps/server/src/kin/lead/LeadPrompt.ts @@ -354,6 +354,7 @@ export interface KinLeadPromptInput { readonly wakeupId: KinWakeupId; readonly events: ReadonlyArray; readonly memoryHead: string; + readonly rulesHead?: string; readonly budgetContext?: string; readonly observePrompt?: (fingerprint: PromptFingerprint) => void; /** The chat the lead's plain text goes to; see the reply bridge. */ @@ -2011,7 +2012,12 @@ export class KinLeadPrompt extends Context.Service< ); const snapshot = ownerOnly ? yield* Effect.gen(function* () { - const read = yield* memory.readPromptSnapshot(orgId, memoryHead, { lead: agentId }); + const read = yield* memory.readPromptSnapshot( + orgId, + memoryHead, + { lead: agentId }, + input.rulesHead, + ); const hidden = yield* sharedOrigins(orgId, agentId); return hidden.size === 0 ? read @@ -2037,7 +2043,12 @@ export class KinLeadPrompt extends Context.Service< const teamIndex = ownerOnly ? "" : yield* Effect.gen(function* () { - const read = yield* memory.readPromptSnapshot(orgId, memoryHead, { lead: agentId }); + const read = yield* memory.readPromptSnapshot( + orgId, + memoryHead, + { lead: agentId }, + input.rulesHead, + ); const items = yield* reaching( orgId, audience, diff --git a/apps/server/src/kin/lead/OwnerNotices.ts b/apps/server/src/kin/lead/OwnerNotices.ts index a53145d5f33a..08d2745678c4 100644 --- a/apps/server/src/kin/lead/OwnerNotices.ts +++ b/apps/server/src/kin/lead/OwnerNotices.ts @@ -44,7 +44,10 @@ export const layer = Layer.effect( ? undefined : { id: failure, - body: `${MEMORY_WRITE_OPERATION_WORDS[operation]} ${MEMORY_WRITE_FAILURE_WORDS[failure]}${link === undefined ? "" : ` ${link}`}`, + body: + failure === "direct-push-refused" + ? MEMORY_WRITE_FAILURE_WORDS[failure] + : `${MEMORY_WRITE_OPERATION_WORDS[operation]} ${MEMORY_WRITE_FAILURE_WORDS[failure]}${link === undefined ? "" : ` ${link}`}`, scope: "cause", silentDuringQuietHours: true, }, diff --git a/apps/server/src/kin/lead/WakeupRunner.test.ts b/apps/server/src/kin/lead/WakeupRunner.test.ts index 6f2537ca2d0c..ecd22f6722a0 100644 --- a/apps/server/src/kin/lead/WakeupRunner.test.ts +++ b/apps/server/src/kin/lead/WakeupRunner.test.ts @@ -74,6 +74,8 @@ import * as Budget from "./KinBudget.ts"; import * as KinIdentity from "../chat/KinIdentity.ts"; import * as Writer from "../memory/MemoryWriter.ts"; import * as Memory from "../memory/Memory.ts"; +import { MemoryLanderHooks } from "../memory/MemoryLander.ts"; +import * as SecretScan from "../memory/secretScan.ts"; import * as MemoryConfig from "../memory/MemoryConfig.ts"; import * as VcsProcess from "../../vcs/VcsProcess.ts"; import * as ProjectService from "../../project/ProjectService.ts"; @@ -733,6 +735,8 @@ describe("WakeupRunner", () => { const writer = Layer.succeed( Writer.MemoryWriter, Writer.MemoryWriter.of({ + readRulesBook: () => Effect.die("Unused"), + saveRulesBook: () => Effect.die("Unused"), stagedDeferral: () => Effect.die("unused"), dropStagedDeferral: () => Effect.die("unused"), dreamBase: () => Effect.die("unused"), @@ -1445,6 +1449,8 @@ describe("WakeupRunner", () => { const writer = Layer.succeed( Writer.MemoryWriter, Writer.MemoryWriter.of({ + readRulesBook: () => Effect.die("Unused"), + saveRulesBook: () => Effect.die("Unused"), stagedDeferral: () => Effect.die("unused"), dropStagedDeferral: () => Effect.die("unused"), dreamBase: () => Effect.die("unused"), @@ -1711,6 +1717,8 @@ describe("WakeupRunner", () => { Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; return Writer.MemoryWriter.of({ + readRulesBook: () => Effect.die("Unused"), + saveRulesBook: () => Effect.die("Unused"), stagedDeferral: () => Effect.die("unused"), dropStagedDeferral: () => Effect.die("unused"), stage: () => Effect.die("unused"), @@ -2569,6 +2577,164 @@ describe("WakeupRunner", () => { }, ); + it.live.each(["disjoint", "conflicting"] as const)( + "a %s journal push race completes the wake and keeps the session", + (race) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const vcs = yield* VcsProcess.VcsProcess; + const root = yield* fs.realPath(yield* fs.makeTempDirectoryScoped()); + const source = `${root}/source`; + const remote = `${root}/memory.git`; + yield* fs.makeDirectory(source); + const git = (cwd: string, args: ReadonlyArray) => + vcs + .run({ operation: "WakeupTest.git", command: "git", cwd, args }) + .pipe(Effect.map(({ stdout }) => stdout.trim())); + const commit = [ + "-c", + "user.name=Quill Vale", + "-c", + "user.email=quill@example.invalid", + "commit", + "-am", + ]; + const journal = "journal/2026/11-08.md"; + yield* git(source, ["init", "-b", "main"]); + yield* fs.writeFileString(`${source}/rules.md`, "Use the first ledger.\n"); + yield* fs.makeDirectory(`${source}/journal/2026`, { recursive: true }); + yield* fs.writeFileString(`${source}/${journal}`, "Original journal.\n"); + yield* git(source, ["add", "--", "rules.md", journal]); + yield* git(source, [...commit, "Initial memory"]); + yield* git(root, ["clone", "--bare", "--", source, remote]); + const outside = race === "disjoint" ? "rules.md" : journal; + yield* fs.writeFileString(`${source}/${outside}`, "Use the violet ledger.\n"); + yield* git(source, [...commit, "Outside edit"]); + const outsidePush = git(source, ["push", "--", remote, "main"]); + let raced = false; + const intercepted = Layer.succeed(VcsProcess.VcsProcess, { + run: Effect.fn("WakeupTest.remoteRace")(function* (input: VcsProcess.VcsProcessInput) { + if ( + !raced && + input.args.includes("push") && + input.args.some((arg) => arg.endsWith(":refs/heads/main")) + ) { + raced = true; + yield* outsidePush.pipe(Effect.orDie); + } + return yield* vcs.run(input); + }), + }); + const outcomes = yield* Queue.unbounded(); + const notices: string[] = []; + const recovery = Layer.succeed(Memory.MemoryRecoveryHooks, { + notify: (notice) => + Effect.sync(() => { + if (notice.owner !== undefined) notices.push(notice.owner); + }), + }); + const config = Layer.succeed(MemoryConfig.MemoryConfig, { + baseDirectory: root, + directMainPush: true, + repositories: [{ orgId, repoUrl: remote, path: "fixture" }], + }); + const memoryLayer = Memory.layer.pipe(Layer.provide(recovery)); + let memory: Memory.Memory["Service"] | undefined; + let rules = ""; + const writer = Writer.layer.pipe( + Layer.provide(Layer.succeed(Writer.MemoryWriterHooks, { notify: () => Effect.void })), + Layer.provide( + Layer.succeed(MemoryLanderHooks, { + settled: () => Queue.offer(outcomes, undefined).pipe(Effect.asVoid), + }), + ), + Layer.provide( + Layer.succeed(Writer.MemoryWriterAuthority, { + resolve: (orgId, wakeupId) => + Effect.succeed({ + orgId, + wakeupId, + agentId, + level: "L1", + timeZone: "UTC", + startedAt: "2026-11-08T00:00:00.000Z", + eventIds: [], + sources: new Map(), + }), + }), + ), + Layer.provide( + memoryLayer.pipe( + Layer.tap((context) => + Effect.sync(() => { + memory = Context.get(context, Memory.Memory); + }), + ), + ), + ), + Layer.provide(recovery), + Layer.provide(SecretScan.layer), + Layer.provide(config), + Layer.provide(intercepted), + Layer.provide(NodeServices.layer), + ); + const reads: string[] = []; + yield* Effect.gen(function* () { + yield* seedCarry; + yield* wake("fixture-race-first"); + yield* Queue.take(outcomes); + const [first] = yield* carryRows; + assert.strictEqual(first?.status, "completed"); + assert.isTrue(raced); + const stored = yield* git(root, [`--git-dir=${remote}`, "show", `main:${journal}`]); + if (race === "disjoint") { + assert.include(stored, `wake-up ${first!.wakeupId}`); + assert.deepStrictEqual(notices, []); + } else { + assert.strictEqual(stored, "Use the violet ledger."); + assert.lengthOf(notices, 1); + } + yield* wake("fixture-race-second"); + yield* Queue.take(outcomes); + assert.include((yield* carryRows).at(-1), { status: "completed", sent: "carried" }); + assert.deepStrictEqual(yield* sessions(), [1, 1]); + if (race === "disjoint") assert.include(reads[0], "Use the violet ledger."); + else assert.lengthOf(notices, 1); + }).pipe( + Effect.provide( + carryHarness({ + writer, + prepare: (orgId, wakeupId) => + Effect.gen(function* () { + if (memory === undefined) return yield* Effect.die("No real memory service"); + const pin = yield* memory.prepareWakeup(orgId, wakeupId); + rules = (yield* memory.readPromptSnapshot(orgId, pin.head)).rules; + return pin; + }), + memoryChanges: { + changedItems: (...args) => + memory?.changedItems?.(...args) ?? Effect.die("No real memory service"), + standingChange: (...args) => + memory?.standingChange(...args) ?? Effect.die("No real memory service"), + }, + standingRules: () => rules, + beforeTurn: ({ threadId, runOrdinal }) => + runOrdinal === 2 + ? readCarryHook(threadId).pipe( + Effect.tap((note) => Effect.sync(() => reads.push(note))), + Effect.asVoid, + ) + : Effect.void, + }), + ), + ); + }).pipe( + Effect.provide(VcsProcess.layer.pipe(Layer.provideMerge(NodeServices.layer))), + Effect.scoped, + provideDeterministicTestRuntime, + ), + ); + const longStanding = "Quote amounts with the currency code. ".repeat(140).trimEnd(); it.effect.each([ ["", "Use the ISO currency code.", 'They are, in full: "Use the ISO currency code."'], diff --git a/apps/server/src/kin/lead/WakeupRunner.testkit.ts b/apps/server/src/kin/lead/WakeupRunner.testkit.ts index 149d2a9578c5..bae801df8a8e 100644 --- a/apps/server/src/kin/lead/WakeupRunner.testkit.ts +++ b/apps/server/src/kin/lead/WakeupRunner.testkit.ts @@ -268,6 +268,7 @@ type HarnessOptions = { readonly cacheWrites?: ReadonlyMap; readonly compactsOn?: number; readonly prepare?: Memory.Memory["Service"]["prepareWakeup"]; + readonly memoryChanges?: Pick; /** Reads a memory item; by default no item exists. */ readonly readItem?: Memory.Memory["Service"]["readItemQuietly"]; /** Each turn opens a command approval and ends only once it is answered. */ @@ -973,8 +974,15 @@ function parts(options: HarnessOptions) { })), checkoutPaths: () => Effect.succeed({ writer: "/private/tmp", read: "/private/tmp" }), ensureCheckouts: () => Effect.succeed({ writer: "/private/tmp", read: "/private/tmp" }), + rememberPublished: () => Effect.die("Unused"), + readRulesBook: () => Effect.die("Unused"), readRules: () => Effect.sync(() => options.standingRules?.() ?? "invented standing"), - standingChange: () => Clock.currentTimeMillis.pipe(Effect.map((at) => ({ at }))), + standingChange: + options.memoryChanges?.standingChange ?? + (() => Clock.currentTimeMillis.pipe(Effect.map((at) => ({ at })))), + ...(options.memoryChanges?.changedItems === undefined + ? {} + : { changedItems: options.memoryChanges.changedItems }), readPromptSnapshot: () => Effect.succeed({ rules: "rules", index: "index", items: [], bodies: new Map() }), readItemQuietly: diff --git a/apps/server/src/kin/lead/WakeupRunner.ts b/apps/server/src/kin/lead/WakeupRunner.ts index 39bc83a7b213..5c262cdfde0a 100644 --- a/apps/server/src/kin/lead/WakeupRunner.ts +++ b/apps/server/src/kin/lead/WakeupRunner.ts @@ -1766,7 +1766,11 @@ const make = Effect.gen(function* () { cursor: Cursor, chatId: string, workChanges?: ReadonlyMap>, - definitions?: { readonly before: SessionDefinitions; readonly after: SessionDefinitions }, + definitions?: { + readonly before: SessionDefinitions; + readonly after: SessionDefinitions; + readonly rulesHead?: string; + }, ) { const from = facts.previousCursor; if (from === undefined) return undefined; @@ -1777,7 +1781,7 @@ const make = Effect.gen(function* () { const ruleStamp = ruleChanged && cursor.memoryHead !== null ? yield* memory - .standingChange(row.orgId, cursor.memoryHead) + .standingChange(row.orgId, definitions?.rulesHead ?? cursor.memoryHead) .pipe(Effect.catch(() => Effect.undefined)) : undefined; if (ruleChanged && ruleStamp === undefined) return { _tag: "unseen" } as const; @@ -2319,6 +2323,7 @@ const make = Effect.gen(function* () { wakeupId, events, memoryHead: pinned.head, + ...(pinned.rulesHead === undefined ? {} : { rulesHead: pinned.rulesHead }), budgetContext, routineFacts, workFor, @@ -2749,7 +2754,11 @@ const make = Effect.gen(function* () { cursor, cursorChat, decision.refill ? built.fullWorkChanges : built.workChanges, - { before: previous.seen, after: seen }, + { + before: previous.seen, + after: seen, + ...(pinned.rulesHead === undefined ? {} : { rulesHead: pinned.rulesHead }), + }, ); if (changes === undefined) reason = "changes"; else if (changes._tag !== "ready") reason = changes._tag; diff --git a/apps/server/src/kin/lead/layer.test.ts b/apps/server/src/kin/lead/layer.test.ts index 1819adeb9f76..4a69fff3ec1e 100644 --- a/apps/server/src/kin/lead/layer.test.ts +++ b/apps/server/src/kin/lead/layer.test.ts @@ -135,6 +135,8 @@ vi.mock("../memory/Memory.ts", async (importOriginal) => { }) : Effect.die("Prompt and runner must share pinned memory"), readIndex: () => Effect.die("unused"), + rememberPublished: () => Effect.die("Unused"), + readRulesBook: () => Effect.die("Unused"), readRules: () => Effect.die("unused"), query: () => Effect.succeed([]), readItem: () => Effect.die("unused"), diff --git a/apps/server/src/kin/lead/layer.ts b/apps/server/src/kin/lead/layer.ts index 35ab70c37fcf..c3d42837e546 100644 --- a/apps/server/src/kin/lead/layer.ts +++ b/apps/server/src/kin/lead/layer.ts @@ -209,7 +209,7 @@ const memorySync = Effect.fn("KinMemory.syncDue")(function* ( ({ orgId }) => memory.syncCheckout(orgId).pipe( Effect.catchCause((cause) => - Effect.logWarning("Kin memory sync failed; the next wake-up re-checks", { + Effect.logWarning("Kin memory sync failed", { orgId, cause: Cause.pretty(cause), }), @@ -284,6 +284,8 @@ const runner = Layer.effectDiscard( retire: writer.value.retire, restore: writer.value.restore, recordDecision: writer.value.recordDecision, + readRulesBook: writer.value.readRulesBook, + saveRulesBook: writer.value.saveRulesBook, items: (orgId) => memory.items(orgId), snapshot: (orgId) => memory.snapshotItems(orgId), }); diff --git a/apps/server/src/kin/memory/Memory.test.ts b/apps/server/src/kin/memory/Memory.test.ts index 54107979618f..66ede0f031ca 100644 --- a/apps/server/src/kin/memory/Memory.test.ts +++ b/apps/server/src/kin/memory/Memory.test.ts @@ -3,6 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, expect, it } from "@effect/vitest"; import { KinAgentId, KinWakeupId, KinMemoryItemId, KinOrgId } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; import * as Clock from "effect/Clock"; import * as ConfigProvider from "effect/ConfigProvider"; import * as Context from "effect/Context"; @@ -661,21 +662,25 @@ it.effect( const checks = repository.counts(); yield* memory.prepareWakeup(orgA); expect(yield* memory.readIndex(orgA)).toBe(before); - // A wake-up validates the writer; fsck and the remote are the background sync's. + // An old pin starts one background sync; the next local read stays on that pin. expect([repository.counts().fsck, repository.counts().remote]).toEqual([ checks.fsck, - checks.remote, + checks.remote + 1, ]); expect(repository.counts().validations).toBeGreaterThan(checks.validations); + // The poll still scans the checkout, including fetched objects, and never adopts a bad head. repository.failFsck(true); + const trusted = yield* memory.anchor(orgA, "main"); + yield* TestClock.adjust("5 minutes"); expect((yield* memory.syncCheckout(orgA).pipe(Effect.flip))._tag).toBe("MemoryError"); + expect(yield* memory.anchor(orgA, "main")).toBe(trusted); expect(repository.counts().fsck).toBe(checks.fsck + 1); - // Until a sync passes, every wake-up re-runs it and refuses to start. expect((yield* memory.prepareWakeup(orgA).pipe(Effect.flip))._tag).toBe("MemoryError"); - expect(repository.counts().fsck).toBe(checks.fsck + 2); + expect(repository.counts().fsck).toBe(checks.fsck + 1); repository.failFsck(false); + yield* memory.syncCheckout(orgA); yield* memory.prepareWakeup(orgA); - expect(repository.counts().fsck).toBe(checks.fsck + 3); + expect(repository.counts().fsck).toBe(checks.fsck + 2); yield* TestClock.adjust("1 hour"); const refreshed = yield* memory.prepareWakeup(orgA); expect(yield* memory.readIndex(orgA)).not.toBe(before); @@ -1064,6 +1069,215 @@ const fixtureRepository = Effect.fn("Test.fixtureRepository")(function* () { return { root, source, git, commit }; }); +it.effect.each(["healthy", "slow"] as const)("turn-start memory sync with a %s remote", (speed) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const vcs = yield* VcsProcess.VcsProcess; + const { root, source, git, commit } = yield* fixtureRepository(); + const remote = `${root}/freshness.git`; + yield* git(root, ["clone", "--bare", "--", source, remote]); + const entered = yield* Deferred.make(); + const release = yield* Deferred.make(); + let pauseRemote = false; + const intercepted = Layer.succeed(VcsProcess.VcsProcess, { + run: Effect.fn("MemoryTest.remoteDelay")(function* (input) { + if (pauseRemote && input.args.includes("ls-remote")) { + yield* Deferred.succeed(entered, undefined); + yield* Deferred.await(release); + } + return yield* vcs.run(input); + }), + }); + yield* Effect.gen(function* () { + const memory = yield* Memory.Memory; + const initial = yield* memory.prepareWakeup(orgA, "first"); + yield* fs.writeFileString(`${source}/rules.md`, "Use the copper ledger.\n"); + const remoteHead = yield* commit(source); + yield* git(source, ["push", "--", remote, "main"]); + yield* TestClock.adjust("31 seconds"); + if (speed === "slow") { + pauseRemote = true; + const turn = yield* memory.prepareWakeup(orgA, "second").pipe(Effect.forkScoped); + yield* Effect.raceFirst( + Deferred.await(entered), + Fiber.await(turn).pipe(Effect.andThen(Effect.die("No background remote check started."))), + ); + yield* TestClock.adjust("1500 millis"); + const pinned = yield* Fiber.join(turn); + expect(pinned.head).toBe(initial.head); + expect((yield* memory.readPromptSnapshot(orgA, pinned.head)).rules).not.toContain("copper"); + yield* Deferred.succeed(release, undefined); + yield* memory.syncCheckout(orgA); + } + const next = yield* memory.prepareWakeup(orgA, "third"); + expect(next.head).toBe(remoteHead); + expect((yield* memory.readPromptSnapshot(orgA, next.head)).rules).toBe( + "Use the copper ledger.\n", + ); + }).pipe( + Effect.provide( + memoryTestLayer.pipe( + Layer.provide(configLayer(`${root}/state`, remote)), + Layer.provide(intercepted), + ), + ), + ); + }).pipe( + Effect.provide(Layer.mergeAll(gitLayer, NodeServices.layer, databaseLayer)), + Effect.scoped, + ), +); + +it.effect.each(["transient", "persistent"] as const)( + "a %s failed integrity audit gets one prompt background retry", + (kind) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const repo = fakeRepository(fs); + repo.files.set("rules.md", "Use the teal ledger.\n"); + const root = yield* fs.realPath(yield* fs.makeTempDirectoryScoped()); + const entered = yield* Deferred.make(); + const release = yield* Deferred.make(); + let auditCalls = 0; + const intercepted = Layer.effect( + VcsProcess.VcsProcess, + Effect.map(VcsProcess.VcsProcess, (vcs) => ({ + run: Effect.fn("MemoryTest.gateAuditRetry")(function* ( + input: VcsProcess.VcsProcessInput, + ) { + if (input.args.includes("fsck") && ++auditCalls === 3) { + yield* Deferred.succeed(entered, undefined); + yield* Deferred.await(release); + } + const result = yield* vcs.run(input); + if (input.args.includes("clone")) + yield* fs.makeDirectory(`${input.args.at(-1)}/.git/refs`).pipe(Effect.orDie); + return result; + }), + })), + ).pipe(Layer.provide(repo.layer)); + const clock = yield* Clock.Clock; + let retryTimers = 0; + const advance = (amount: Duration.Input) => + TestClock.adjust(amount).pipe(Effect.provideService(Clock.Clock, clock)); + yield* Effect.gen(function* () { + const memory = yield* Memory.Memory; + const first = yield* memory.prepareWakeup(orgA); + const prepare = memory.prepareWakeup(orgA); + expect(auditCalls).toBe(1); + + yield* advance("5 minutes"); + repo.failFsck(true); + expect((yield* memory.syncCheckout(orgA).pipe(Effect.flip))._tag).toBe("MemoryError"); + expect((yield* prepare.pipe(Effect.flip))._tag).toBe("MemoryError"); + expect(retryTimers).toBe(1); + yield* advance("29999 millis"); + expect(auditCalls).toBe(2); + if (kind === "transient") repo.failFsck(false); + expect((yield* prepare.pipe(Effect.flip))._tag).toBe("MemoryError"); + + yield* advance("1 millis"); + yield* Deferred.await(entered); + expect((yield* prepare.pipe(Effect.flip))._tag).toBe("MemoryError"); + const settled = yield* memory + .syncCheckout(orgA) + .pipe(Effect.result, Effect.forkScoped({ startImmediately: true })); + yield* Deferred.succeed(release, undefined); + expect((yield* Fiber.join(settled))._tag).toBe( + kind === "transient" ? "Success" : "Failure", + ); + if (kind === "transient") expect((yield* prepare).head).toBe(first.head); + else expect((yield* prepare.pipe(Effect.flip))._tag).toBe("MemoryError"); + yield* advance("269999 millis"); + expect(auditCalls).toBe(3); + expect(retryTimers).toBe(1); + if (kind === "persistent") { + yield* advance("1 millis"); + expect((yield* memory.syncCheckout(orgA).pipe(Effect.flip))._tag).toBe("MemoryError"); + expect(auditCalls).toBe(4); + expect(retryTimers).toBe(2); + } + }).pipe( + Effect.provide( + memoryTestLayer.pipe( + Layer.provide(configLayer(root, "unused")), + Layer.provide(intercepted), + ), + ), + Effect.provideService(Clock.Clock, { + ...clock, + sleep: (duration) => { + if (Duration.toMillis(duration) === 30_000) retryTimers++; + return clock.sleep(duration); + }, + }), + ); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, databaseLayer)), Effect.scoped), +); + +it.effect("the scheduled integrity check rejects corruption in newly fetched history", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const vcs = yield* VcsProcess.VcsProcess; + const { root, source, git, commit } = yield* fixtureRepository(); + const remote = `${root}/audit.git`; + yield* git(root, ["clone", "--bare", "--", source, remote]); + const auditing = yield* Deferred.make(); + const auditMayFinish = yield* Deferred.make(); + let damagedBlob: string | undefined; + const corrupt = Layer.succeed(VcsProcess.VcsProcess, { + run: Effect.fn("MemoryTest.corruptFetchedObject")(function* (input) { + if (input.args.includes("fsck") && damagedBlob !== undefined) { + yield* Deferred.succeed(auditing, undefined); + yield* Deferred.await(auditMayFinish); + const object = `${input.cwd}/.git/objects/${damagedBlob.slice(0, 2)}/${damagedBlob.slice(2)}`; + yield* fs.remove(object).pipe(Effect.orDie); + yield* fs.writeFileString(object, "Invented damage.").pipe(Effect.orDie); + damagedBlob = undefined; + } + return yield* vcs.run(input); + }), + }); + yield* Effect.gen(function* () { + const memory = yield* Memory.Memory; + const initial = yield* memory.prepareWakeup(orgA, "first"); + const historic = "history-only.txt"; + yield* fs.writeFileString(`${source}/${historic}`, "Invented prior history."); + yield* commit(source); + const blob = yield* git(source, ["rev-parse", `HEAD:${historic}`]); + yield* fs.remove(`${source}/${historic}`); + yield* fs.writeFileString(`${source}/rules.md`, "Use the teal ledger.\n"); + const external = yield* commit(source); + yield* git(source, ["push", "--", remote, "main"]); + expect(external).not.toBe(initial.head); + damagedBlob = blob; + yield* TestClock.adjust("5 minutes"); + const audit = yield* memory.syncCheckout(orgA).pipe(Effect.flip, Effect.forkScoped); + yield* Deferred.await(auditing); + const turn = yield* memory.prepareWakeup(orgA, "during-audit"); + expect(turn.head).toBe(initial.head); + yield* Deferred.succeed(auditMayFinish, undefined); + expect(yield* Fiber.join(audit)).toMatchObject({ _tag: "MemoryError", operation: "git" }); + expect(damagedBlob).toBeUndefined(); + expect(yield* memory.anchor(orgA, "main")).toBe(initial.head); + expect(yield* memory.prepareWakeup(orgA, "second").pipe(Effect.flip)).toMatchObject({ + _tag: "MemoryError", + operation: "git", + }); + }).pipe( + Effect.provide( + memoryTestLayer.pipe( + Layer.provide(configLayer(`${root}/state`, remote)), + Layer.provide(corrupt), + ), + ), + ); + }).pipe( + Effect.provide(Layer.mergeAll(gitLayer, NodeServices.layer, databaseLayer)), + Effect.scoped, + ), +); + it.live( "materializes a large journal checkout in one blob read, staged on the state filesystem", () => diff --git a/apps/server/src/kin/memory/Memory.ts b/apps/server/src/kin/memory/Memory.ts index 4f2abac581da..d8fc6aa70d19 100644 --- a/apps/server/src/kin/memory/Memory.ts +++ b/apps/server/src/kin/memory/Memory.ts @@ -13,6 +13,7 @@ import { import { type KinAgentId, type KinMemoryItemId, + type KinMemoryRules, type KinOrgId, MemoryItemHead, type MemoryItemKind, @@ -22,12 +23,14 @@ import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import type * as Result from "effect/Result"; import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as SqlClient from "effect/sql/SqlClient"; @@ -210,6 +213,12 @@ export interface MemoryHistoryRewrite { export class Memory extends Context.Service< Memory, { + /** Records a successful direct push while the publisher holds the landing lock. */ + readonly rememberPublished: ( + orgId: KinOrgId, + expected: string, + published: string, + ) => Effect.Effect; readonly withWriterLock: ( orgId: KinOrgId, effect: Effect.Effect, @@ -270,19 +279,20 @@ export class Memory extends Context.Service< readonly ensureCheckouts: (orgId: KinOrgId) => Effect.Effect; /** * Validates the writer and swaps in a fresh read checkout, `read`: the waking lead's own - * (`memory-read-`) with its view. No other lead's prepare touches it. The first wake-up - * after a start, and every one after a failed `syncCheckout`, syncs inline first. + * (`memory-read-`) with its view. No other lead's prepare touches it. */ readonly prepareWakeup: ( orgId: KinOrgId, wakeupId?: string, view?: LeadView, - ) => Effect.Effect<{ head: string; indexAsOf: DateTime.Utc; read: string }, MemoryFailure>; + ) => Effect.Effect< + { head: string; rulesHead?: string; indexAsOf: DateTime.Utc; read: string }, + MemoryFailure + >; /** * The writer's integrity check (`git fsck`) and default-branch sync with the remote, off the * reply path; it reads the remote before taking the writer lock. Skips an organization with no - * clone yet, or whose last sync failed: its next wake-up re-runs the sync and refuses to start - * until it passes. + * clone yet. */ readonly syncCheckout: (orgId: KinOrgId) => Effect.Effect; readonly changedItems?: ( @@ -298,6 +308,7 @@ export class Memory extends Context.Service< orgId: KinOrgId, expectedHead: string, view?: LeadView, + rulesHead?: string, ) => Effect.Effect< { readonly rules: string; @@ -315,6 +326,18 @@ export class Memory extends Context.Service< ) => Effect.Effect<{ readonly at: number } | undefined, MemoryFailure>; readonly readIndex: (orgId: KinOrgId) => Effect.Effect; readonly readRules: (orgId: KinOrgId) => Effect.Effect; + /** Owner-client writer port; the caller holds the writer lock. */ + readonly readRulesBook: ( + orgId: KinOrgId, + head: string, + ) => Effect.Effect< + { + readonly book: KinMemoryRules; + readonly present: boolean; + readonly oversizedBytes?: number; + }, + MemoryFailure + >; /** * With `admit`, only the items it admits exist: they are judged and returned from one * snapshot, so what was checked is what is returned, and what it hides changes nothing. @@ -369,6 +392,8 @@ interface Snapshot extends MemorySyncSnapshot { readonly files: ReadonlyMap; /** Blob id of each memory file, to tell a shadow branch's own changes from inherited ones. */ readonly blobIds: ReadonlyMap; + readonly rulesPresent?: boolean; + readonly rulesBytes?: number; index?: string; } @@ -388,7 +413,7 @@ const make = Effect.gen(function* () { const config = yield* MemoryConfig; const app = yield* gitHubApp; const fs = yield* FileSystem.FileSystem; - const { notify } = yield* MemoryRecoveryHooks; + const { notify, writeEpisode } = yield* MemoryRecoveryHooks; const vcs = yield* VcsProcess; const refresh = yield* KinRefreshObserver; const memoryGit = (...args: Parameters) => @@ -399,8 +424,10 @@ const make = Effect.gen(function* () { ); const path = yield* Path.Path; const sql = yield* SqlClient.SqlClient; + const scope = yield* Scope.Scope; const writerLocks = new Map(); const landingLocks = new Map(); + const remoteSyncLocks = new Map(); const pinnedHeads = new Map(); const skipWarnedHeads = new Map(); const hooks = yield* MemorySyncHooks; @@ -416,6 +443,7 @@ const make = Effect.gen(function* () { }; const withWriterLock = lockIn(writerLocks); const withLandingLock = lockIn(landingLocks); + const withRemoteSyncLock = lockIn(remoteSyncLocks); const persistence = (orgId: KinOrgId, effect: Effect.Effect) => effect.pipe( Effect.mapError(toPersistenceSqlError("Memory.anchor")), @@ -492,8 +520,17 @@ const make = Effect.gen(function* () { const cache = yield* MemoryCache.MemoryCache; const locks = new Map(); const initializedCheckouts = new Set(); - // Whether the last sync passed; absent until the first one after start or a history rewrite. - const synced = new Map(); + const lastSynced = new Map(); + const lastAttempt = new Map(); + const syncFailures = new Map(); + const integrity = new Map>(); + const syncFlights = new Map< + KinOrgId, + { + readonly full: boolean; + readonly done: Deferred.Deferred; + } + >(); const historyGenerations = new Map(); const mainBranch = config.defaultBranch ?? "main"; // Keyed by `snapshotKey`: each branch a lead reads has its own snapshot and blob cache. @@ -780,7 +817,9 @@ const make = Effect.gen(function* () { operation: "bootstrap", reason: "Existing anchor differs", }); + yield* git(orgId, temporary, ["update-ref", "--no-deref", remoteRef, head]); yield* fs.rename(temporary, paths.writer); + lastSynced.set(orgId, yield* Clock.currentTimeMillis); }).pipe(Effect.scoped), ); } @@ -968,11 +1007,16 @@ const make = Effect.gen(function* () { yield* Effect.logWarning("Duplicate memory id", { orgId, branch, id }); } if (explicitHead === undefined) duplicateWarnings.set(key, duplicateIds); + const rules = entries.find(({ relative }) => relative === "rules.md"); const snapshot: Snapshot = { head, branch, items, files, + rulesPresent: verifiedEntries.some( + ({ relative }) => relative === "rules.md" || relative.startsWith("rules.md/"), + ), + ...(rules !== undefined && Number.isFinite(rules.size) ? { rulesBytes: rules.size } : {}), blobIds: new Map(entries.map((entry) => [entry.relative, entry.sha])), duplicateIds, ...(previous?.head === head && previous.index !== undefined ? { index: previous.index } : {}), @@ -1265,7 +1309,30 @@ const make = Effect.gen(function* () { let conflictSequence = 0; // Local and remote heads whose content conflict the owner already heard about. - const conflictNotices = new Set(); + const conflictNotices = new Map(); + const preserveAfterSync = new Map(); + const remoteRef = "refs/kin/verified-upstream"; + const reportRemoteConflict = Effect.fn("Memory.reportRemoteConflict")(function* ( + orgId: KinOrgId, + remote: string, + reason: string, + ) { + const alreadyTold = conflictNotices.has(orgId); + conflictNotices.set(orgId, remote); + if (alreadyTold) return; + yield* notify({ + orgId, + branch: mainBranch, + reason, + ...(writeEpisode === undefined + ? { + owner: + "Kin couldn’t combine the two copies of memory. The changes are still saved separately on this server and on GitHub. Review the differences before publishing again.", + } + : {}), + }); + yield* writeEpisode?.(orgId, "online-copy", "online-conflict") ?? Effect.void; + }); const preserve = Effect.fn("Memory.preserve")(function* ( orgId: KinOrgId, writer: string, @@ -1533,8 +1600,14 @@ const make = Effect.gen(function* () { : "Kept the anchored shadow branch, but it is only on this server: the push was refused", }); } + yield* git(orgId, paths.writer, ["update-ref", "--no-deref", remoteRef, main]); + if (conflictNotices.delete(orgId)) + yield* writeEpisode?.(orgId, "online-copy", undefined) ?? Effect.void; pinnedHeads.delete(orgId); - synced.delete(orgId); + lastSynced.delete(orgId); + lastAttempt.delete(orgId); + syncFailures.delete(orgId); + integrity.delete(orgId); forgetSnapshots(orgId); }); @@ -1563,18 +1636,6 @@ const make = Effect.gen(function* () { const generation = historyGenerations.get(orgId) ?? 0; return { generation, fetched: yield* fetchRemote(orgId, writer, repo.repoUrl) }; }); - // A purge may have dropped the fetched objects; an invalid prefetch must be rechecked under lock. - const stillFetched = ( - orgId: KinOrgId, - prefetched: Effect.Success>, - ) => - prefetched?.generation === (historyGenerations.get(orgId) ?? 0) && - !( - prefetched.fetched._tag === "Failure" && - prefetched.fetched.failure._tag === "MemoryCheckoutInvalid" - ) - ? prefetched.fetched - : undefined; /** * The local commit whose tree GitHub's newest unmerged squash of this server's memory carries: @@ -1623,33 +1684,55 @@ const make = Effect.gen(function* () { return sha === undefined ? absent : ({ _tag: "exhausted" } as const); }); - // Callers have run `ensureCheckouts`. A head fetched before the lock was taken is merged as it - // is; the lander skips `fsck`, which the periodic sync and a wake-up's own sync still run. + const checkIntegrity = Effect.fn("Memory.checkIntegrity")(function* ( + orgId: KinOrgId, + writer: string, + ) { + yield* git(orgId, writer, [ + "fsck", + "--full", + "--strict", + "--no-reflogs", + yield* anchor(orgId, mainBranch), + ]); + }); + + // Callers have run `ensureCheckouts`; merge the exact head fetched before taking the writer lock. const sync = Effect.fn("Memory.sync")(function* ( orgId: KinOrgId, - prefetched: Fetched | undefined, - options: { readonly wakeupId?: string; readonly fsck: boolean }, + fetched: Fetched, + preserveConflict: boolean, ) { - const { wakeupId } = options; const paths = yield* pathsFor(orgId); yield* refuseUnfinishedOperation(orgId, paths.writer); yield* validateWriter(orgId, paths); - if (options.fsck) - yield* git(orgId, paths.writer, [ - "fsck", - "--full", - "--strict", - "--no-reflogs", - yield* anchor(orgId, config.defaultBranch ?? "main"), - ]); - const { repo } = yield* pathsFor(orgId); const branch = config.defaultBranch ?? "main"; let head = yield* anchor(orgId, branch); - const fetched = prefetched ?? (yield* fetchRemote(orgId, paths.writer, repo.repoUrl)); - if (fetched._tag === "Failure" && fetched.failure._tag === "MemoryCheckoutInvalid") + if ( + fetched._tag === "Failure" && + fetched.failure._tag === "MemoryCheckoutInvalid" && + fetched.failure.operation !== "remote" + ) return yield* fetched.failure; if (fetched._tag === "Success") { const remote = fetched.success.trim(); + const previousRemote = yield* git(orgId, paths.writer, [ + "rev-parse", + "--verify", + "--quiet", + remoteRef, + ]).pipe( + Effect.map((sha) => sha.trim()), + Effect.option, + ); + if ( + previousRemote._tag === "Some" && + previousRemote.value !== remote && + !(yield* isAncestor(orgId, paths.writer, previousRemote.value, remote)) + ) { + yield* reportRemoteConflict(orgId, remote, "Memory history on the remote was rewritten."); + return undefined; + } if (remote !== head) { const remoteAncestors = yield* walkAncestors(orgId, paths.writer, remote, head); let next = remote; @@ -1669,19 +1752,9 @@ const make = Effect.gen(function* () { ? landed.commit : uniqueMergeBase(localAncestors, remoteAncestors); if (!mergeBase) { - const conflictBranch = yield* preserve( - orgId, - paths.writer, - repo.repoUrl, - head, - wakeupId, - ); - yield* notify({ - orgId, - branch, - reason: "No unique verified merge base", - conflictBranch, - }); + yield* reportRemoteConflict(orgId, remote, "No unique verified merge base"); + if (!preserveConflict) return undefined; + preserveAfterSync.set(orgId, head); return yield* new MemorySyncConflict({ orgId, operation: "merge", @@ -1721,18 +1794,12 @@ const make = Effect.gen(function* () { metadata.get(next)!, ); if (!merged) { - // This server's copy stays as it is: it may hold commits GitHub never got. - next = head; - const key = `${orgId}\u0000${head}\u0000${remote}`; - if (!conflictNotices.has(key)) { - conflictNotices.add(key); - yield* notify({ - orgId, - branch, - reason: - "Memory write not merged: memory on GitHub changed in a way Kin could not combine with this server's. Memory is still saved on this server; the GitHub copy stays behind until the two are reconciled", - }); - } + yield* reportRemoteConflict( + orgId, + remote, + "Memory write not merged: memory on GitHub changed in a way Kin could not combine with this server's.", + ); + return undefined; } else { const { files: mergedFiles, modes } = merged; const remoteOriginal = new Map(remoteFiles); @@ -1873,15 +1940,134 @@ const make = Effect.gen(function* () { head = next; } } + if (previousRemote._tag === "None" || previousRemote.value !== remote) + yield* git(orgId, paths.writer, ["update-ref", "--no-deref", remoteRef, remote]); + if (conflictNotices.delete(orgId)) + yield* writeEpisode?.(orgId, "online-copy", undefined) ?? Effect.void; return remote; } return undefined; }); - const checkedSync = (...args: Parameters) => - sync(...args).pipe( - Effect.tap(() => Effect.sync(() => synced.set(args[0], true))), - Effect.tapError(() => Effect.sync(() => synced.set(args[0], false))), + const checkedSync = Effect.fn("Memory.checkedSync")(function* ( + orgId: KinOrgId, + prefetched: Fetched, + preserveConflict: boolean, + ) { + const remote = yield* sync(orgId, prefetched, preserveConflict); + if (remote !== undefined) lastSynced.set(orgId, yield* Clock.currentTimeMillis); + return remote; + }); + + const syncCheckout = Effect.fn("Memory.syncCheckout")(function* ( + orgId: KinOrgId, + full: boolean, + retryAudit: boolean, + ): Effect.fn.Return { + const result = yield* withRemoteSyncLock( + orgId, + Effect.gen(function* () { + const prefetched = yield* prefetch(orgId); + if (prefetched === undefined) return; + const { writer } = yield* pathsFor(orgId); + // The poll audits fetched objects too, but does not hold the writer lock during fsck. + const checked = full ? yield* checkIntegrity(orgId, writer).pipe(Effect.result) : undefined; + yield* withWriterLock( + orgId, + locked( + orgId, + Effect.gen(function* () { + if (prefetched.generation !== (historyGenerations.get(orgId) ?? 0)) return; + yield* ensureCheckouts(orgId); + if (checked !== undefined) yield* rememberIntegrity(orgId, checked, retryAudit); + const audited = integrity.get(orgId); + // The first local pin or startup poll must audit the repository before a quick sync can adopt a head. + if (audited === undefined) return; + if (audited._tag === "Failure") return yield* audited.failure; + const fetched = prefetched.fetched; + if ( + fetched._tag === "Failure" && + fetched.failure._tag === "MemoryCheckoutInvalid" && + fetched.failure.operation === "git" + ) + return; + yield* checkedSync(orgId, fetched, true).pipe( + Effect.tap(() => Effect.sync(() => syncFailures.delete(orgId))), + Effect.tapError((failure) => Effect.sync(() => syncFailures.set(orgId, failure))), + ); + }), + ), + ); + }), + ).pipe(Effect.result); + const retained = preserveAfterSync.get(orgId); + if (retained !== undefined) { + preserveAfterSync.delete(orgId); + yield* withLandingLock( + orgId, + Effect.gen(function* () { + const { writer, repo } = yield* pathsFor(orgId); + if ((yield* anchor(orgId, mainBranch)) !== retained) return; + yield* preserve(orgId, writer, repo.repoUrl, retained).pipe( + Effect.catch((error) => + Effect.logWarning("Kin couldn't publish a memory recovery branch", { + orgId, + errorTag: error._tag, + }), + ), + ); + }), + ); + } + return yield* Effect.fromResult(result); + }); + + const syncInBackground = Effect.fn("Memory.syncInBackground")(function* ( + orgId: KinOrgId, + full: boolean, + retryAudit = full, + ) { + const existing = syncFlights.get(orgId); + if (existing !== undefined && (!full || existing.full)) return existing; + const done = Deferred.makeUnsafe(); + const flight = { full, done }; + syncFlights.set(orgId, flight); + const previous = + existing === undefined ? Effect.void : Deferred.await(existing.done).pipe(Effect.ignore); + yield* previous.pipe( + Effect.andThen(syncCheckout(orgId, full, retryAudit)), + Effect.onExit((exit) => + Effect.sync(() => { + if (syncFlights.get(orgId) === flight) syncFlights.delete(orgId); + }).pipe(Effect.andThen(Deferred.done(done, exit)), Effect.asVoid), + ), + Effect.ignore, + Effect.interruptible, + Effect.forkIn(scope), ); + return flight; + }, Effect.uninterruptible); + + const rememberIntegrity = Effect.fn("Memory.rememberIntegrity")(function* ( + orgId: KinOrgId, + checked: Result.Result, + retryAudit: boolean, + ) { + integrity.set(orgId, checked); + if (checked._tag === "Success" || !retryAudit) return; + yield* Effect.sleep("30 seconds").pipe( + Effect.andThen( + Effect.gen(function* () { + if (integrity.get(orgId) !== checked || syncFlights.get(orgId)?.full) return; + const { done } = yield* syncInBackground(orgId, true, false); + yield* Deferred.await(done); + }), + ), + Effect.catch((error) => + Effect.logWarning("Kin memory audit retry failed", { orgId, errorTag: error._tag }), + ), + Effect.forkIn(scope, { startImmediately: true }), + ); + }); const isAncestor = (orgId: KinOrgId, writer: string, older: string, newer: string) => git(orgId, writer, ["merge-base", "--is-ancestor", older, newer]).pipe( @@ -1911,11 +2097,21 @@ const make = Effect.gen(function* () { orgId: KinOrgId, fetched: Fetched, ) { + const audited = integrity.get(orgId); + if (audited?._tag === "Failure") return yield* audited.failure; yield* ensureCheckouts(orgId); const { writer } = yield* pathsFor(orgId); - const remote = yield* checkedSync(orgId, fetched, { fsck: false }); + const remote = yield* checkedSync(orgId, fetched, false); const local = yield* anchor(orgId, mainBranch); - if (remote === undefined) return { writer, local, remote }; + if (remote === undefined) { + const conflict = conflictNotices.get(orgId); + return { + writer, + local, + remote: + conflict === undefined ? undefined : { head: conflict, pending: true, descends: false }, + }; + } return { writer, local, @@ -1927,21 +2123,20 @@ const make = Effect.gen(function* () { }; }); - const prepare = Effect.fn("Memory.prepare")(function* ( - orgId: KinOrgId, - wakeupId?: string, - view?: LeadView, - prefetched?: Fetched, - ) { + const prepare = Effect.fn("Memory.prepare")(function* (orgId: KinOrgId, view?: LeadView) { const paths = yield* ensureCheckouts(orgId, false, true); - if (synced.get(orgId) === true) { - yield* refuseUnfinishedOperation(orgId, paths.writer); - yield* validateWriter(orgId, yield* pathsFor(orgId)); - } else - yield* checkedSync(orgId, prefetched, { - fsck: true, - ...(wakeupId === undefined ? {} : { wakeupId }), - }); + yield* refuseUnfinishedOperation(orgId, paths.writer); + yield* validateWriter(orgId, yield* pathsFor(orgId)); + const failure = syncFailures.get(orgId); + if (failure !== undefined && !(failure._tag === "MemoryError" && failure.operation === "git")) + return yield* failure; + const audited = integrity.get(orgId); + if (audited?._tag === "Failure") return yield* audited.failure; + if (audited === undefined) { + const first = yield* checkIntegrity(orgId, paths.writer).pipe(Effect.result); + yield* rememberIntegrity(orgId, first, true); + yield* Effect.fromResult(first); + } const branch = config.defaultBranch ?? "main"; const head = yield* anchor(orgId, branch); // The read checkout holds the waking lead's view: its shadow branch at L0. @@ -1952,16 +2147,25 @@ const make = Effect.gen(function* () { Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(VcsProcess, vcs), ); - const kept = entries.filter( - ({ relative, mode }) => ["100644", "100755"].includes(mode) && isCheckoutPath(relative), - ); + const usable = ({ relative, mode }: (typeof entries)[number]) => + ["100644", "100755"].includes(mode) && isCheckoutPath(relative); + const kept = entries.filter(usable); if (kept.length < entries.length && skipWarnedHeads.get(orgId) !== checkoutHead) { - const keptSet = new Set(kept); yield* Effect.logWarning("Kin memory checkout skipped paths", { orgId, - paths: entries.filter((entry) => !keptSet.has(entry)).map(({ relative }) => relative), + paths: entries.filter((entry) => !usable(entry)).map(({ relative }) => relative), }); } + if (checkoutHead !== head) { + const at = kept.findIndex((entry) => entry.relative === "rules.md"); + if (at >= 0) kept.splice(at, 1); + const mainTree = yield* readTree(orgId, paths.writer, head).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(VcsProcess, vcs), + ); + const rules = mainTree.find((entry) => entry.relative === "rules.md"); + if (rules !== undefined && usable(rules)) kept.push(rules); + } skipWarnedHeads.set(orgId, checkoutHead); const sizes = new Map(); if (kept.length) @@ -2069,6 +2273,7 @@ const make = Effect.gen(function* () { ).pipe(Effect.mapError((cause) => new MemoryError({ orgId, operation: "indexDate", cause }))); return { head: checkoutHead, + ...(checkoutHead === head ? {} : { rulesHead: head }), indexAsOf: DateTime.toUtc(indexAsOf), read: readTarget, }; @@ -2092,7 +2297,10 @@ const make = Effect.gen(function* () { } initializedCheckouts.delete(orgId); pinnedHeads.delete(orgId); - synced.delete(orgId); + lastSynced.delete(orgId); + lastAttempt.delete(orgId); + syncFailures.delete(orgId); + integrity.delete(orgId); skipWarnedHeads.delete(orgId); for (const key of checkoutBranches.keys()) if (key.startsWith(`${orgId}\u0000`)) checkoutBranches.delete(key); @@ -2146,16 +2354,45 @@ const make = Effect.gen(function* () { ) => withLandingLock(orgId, withWriterLock(orgId, body(historyRewrite(orgId)))); return Memory.of({ + rememberPublished: Effect.fn("Memory.rememberPublished")((orgId, expected, published) => + withRemoteSyncLock( + orgId, + withWriterLock( + orgId, + Effect.gen(function* () { + const { writer } = yield* pathsFor(orgId); + const known = (yield* git(orgId, writer, ["rev-parse", "--verify", remoteRef])).trim(); + if (known !== expected) return; + yield* git(orgId, writer, ["update-ref", "--no-deref", remoteRef, published, known]); + lastSynced.set(orgId, yield* Clock.currentTimeMillis); + }), + ), + ), + ), withWriterLock, withLandingLock, - landingState: Effect.fn("Memory.landingStateLocked")(function* (orgId) { - const { writer, repo } = yield* pathsFor(orgId); - if (!(yield* io(orgId, "exists", fs.exists(writer)))) return undefined; - if ((yield* purgeInFlight(orgId)) !== undefined) return undefined; - // The network part, outside the writer lock; the lock covers only the local merge. - const fetched = yield* fetchRemote(orgId, writer, repo.repoUrl); - return yield* withWriterLock(orgId, locked(orgId, landingState(orgId, fetched))); - }), + landingState: Effect.fn("Memory.landingStateLocked")((orgId) => + withRemoteSyncLock( + orgId, + Effect.gen(function* () { + const { writer, repo } = yield* pathsFor(orgId); + if (!(yield* io(orgId, "exists", fs.exists(writer)))) return undefined; + if ((yield* purgeInFlight(orgId)) !== undefined) return undefined; + const generation = historyGenerations.get(orgId); + const fetched = yield* fetchRemote(orgId, writer, repo.repoUrl); + return yield* withWriterLock( + orgId, + locked( + orgId, + Effect.gen(function* () { + if (generation !== historyGenerations.get(orgId)) return undefined; + return yield* landingState(orgId, fetched); + }), + ), + ); + }), + ), + ), withHistoryRewrite, purgeInFlight: Effect.fn("Memory.purgeInFlightLocked")((orgId) => locked(orgId, purgeInFlight(orgId)), @@ -2164,7 +2401,7 @@ const make = Effect.gen(function* () { Effect.sync(() => historyGenerations.get(orgId) ?? 0), ), recover: Effect.fn("Memory.recoverLocked")((orgId) => - withWriterLock(orgId, locked(orgId, recover(orgId))), + withLandingLock(orgId, withWriterLock(orgId, locked(orgId, recover(orgId)))), ), anchor, record, @@ -2172,35 +2409,31 @@ const make = Effect.gen(function* () { ensureCheckouts: Effect.fn("Memory.ensureCheckoutsLocked")((orgId) => locked(orgId, ensureCheckouts(orgId, true)), ), - prepareWakeup: Effect.fn("Memory.prepareWakeup")(function* (orgId, wakeupId, view) { - // A wake-up that has to sync reads GitHub before it takes the writer lock, like the lander. - const prefetched = synced.get(orgId) === true ? undefined : yield* prefetch(orgId); - return yield* withWriterLock( - orgId, - locked( - orgId, - Effect.suspend(() => prepare(orgId, wakeupId, view, stillFetched(orgId, prefetched))), - ), + prepareWakeup: Effect.fn("Memory.prepareWakeup")(function* (orgId, _wakeupId, view) { + const now = yield* Clock.currentTimeMillis; + const last = Math.max( + lastSynced.get(orgId) ?? -Infinity, + lastAttempt.get(orgId) ?? -Infinity, ); + if (now - last >= 30_000) { + lastAttempt.set(orgId, now); + const flight = yield* syncInBackground(orgId, false); + if (!flight.full) + yield* Deferred.await(flight.done).pipe( + Effect.catch((error) => + Effect.logWarning("Kin could not refresh memory before a turn", { + orgId, + errorTag: error._tag, + }), + ), + Effect.timeoutOption("1500 millis"), + ); + } + return yield* withWriterLock(orgId, locked(orgId, prepare(orgId, view))); }), - syncCheckout: Effect.fn("Memory.syncCheckout")(function* (orgId) { - if (synced.get(orgId) === false) return; - // The network part, outside the writer lock, so a slow GitHub never holds up a lead. - const prefetched = yield* prefetch(orgId); - if (prefetched === undefined) return; - yield* withWriterLock( - orgId, - locked( - orgId, - Effect.gen(function* () { - if (synced.get(orgId) === false) return; - const { writer } = yield* pathsFor(orgId); - if (!(yield* io(orgId, "exists", fs.exists(writer)))) return; - yield* ensureCheckouts(orgId); - yield* checkedSync(orgId, stillFetched(orgId, prefetched), { fsck: true }); - }), - ), - ); + syncCheckout: Effect.fn("Memory.awaitSync")(function* (orgId) { + const { done } = yield* syncInBackground(orgId, true); + yield* Deferred.await(done); }), changedItems: Effect.fn("Memory.changedItems")((orgId, from, to, options) => locked( @@ -2288,49 +2521,54 @@ const make = Effect.gen(function* () { }), ), ), - readPromptSnapshot: Effect.fn("Memory.readPromptSnapshot")((orgId, expectedHead, view) => - locked( - orgId, - Effect.gen(function* () { - const current = yield* load(orgId, false, view); - const snapshot = - current.head === expectedHead - ? current - : yield* pinnedSnapshot(orgId, current.branch, expectedHead); - const rules = snapshot.files.get("rules.md"); - if (rules === undefined) - return yield* new MemoryError({ - orgId, - operation: "promptSnapshot", - reason: "Missing committed prompt rules", - }); - // Deferrals as their runs make them (a tap moved or cancelled one): the index is drawn - // again only then, so an unchanged prompt keeps its stored index. - const heads = snapshot.items.map((item) => item.head); - const items = yield* withRuns(orgId, heads).pipe( - Effect.provideService(SqlClient.SqlClient, sql), - Effect.mapError( - (cause) => new MemoryError({ orgId, operation: "promptSnapshot", cause }), - ), - ); - const index = items.some((head, at) => head !== heads[at]) - ? buildIndex( - items, - yield* cache - .lastReads(orgId) - .pipe(Effect.orElseSucceed(() => Object.fromEntries([]))), - yield* Clock.currentTimeMillis, - yield* cache.ownerTimeZone(orgId), - ) - : (snapshot.index ?? snapshot.files.get("INDEX.md") ?? ""); - return { - rules, - index, - items, - bodies: new Map(snapshot.items.map((item) => [item.head.path, item.body])), - }; - }), - ), + readPromptSnapshot: Effect.fn("Memory.readPromptSnapshot")( + (orgId, expectedHead, view, rulesHead) => + locked( + orgId, + Effect.gen(function* () { + const current = yield* load(orgId, false, view); + const snapshot = + current.head === expectedHead + ? current + : yield* pinnedSnapshot(orgId, current.branch, expectedHead); + const standing = + rulesHead === undefined + ? snapshot + : yield* pinnedSnapshot(orgId, mainBranch, rulesHead); + const rules = standing.files.get("rules.md"); + if (rules === undefined) + return yield* new MemoryError({ + orgId, + operation: "promptSnapshot", + reason: "Missing committed prompt rules", + }); + // Deferrals as their runs make them (a tap moved or cancelled one): the index is drawn + // again only then, so an unchanged prompt keeps its stored index. + const heads = snapshot.items.map((item) => item.head); + const items = yield* withRuns(orgId, heads).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + Effect.mapError( + (cause) => new MemoryError({ orgId, operation: "promptSnapshot", cause }), + ), + ); + const index = items.some((head, at) => head !== heads[at]) + ? buildIndex( + items, + yield* cache + .lastReads(orgId) + .pipe(Effect.orElseSucceed(() => Object.fromEntries([]))), + yield* Clock.currentTimeMillis, + yield* cache.ownerTimeZone(orgId), + ) + : (snapshot.index ?? snapshot.files.get("INDEX.md") ?? ""); + return { + rules, + index, + items, + bodies: new Map(snapshot.items.map((item) => [item.head.path, item.body])), + }; + }), + ), ), standingChange: Effect.fn("Memory.standingChange")((orgId, head) => locked( @@ -2360,6 +2598,67 @@ const make = Effect.gen(function* () { ), ), readIndex: Effect.fn("Memory.readIndex")((orgId) => locked(orgId, readFile(orgId, "INDEX.md"))), + readRulesBook: Effect.fn("Memory.readRulesBook")((orgId, head) => + locked( + orgId, + Effect.gen(function* () { + const { writer } = yield* pathsFor(orgId); + const snapshot = yield* pinnedSnapshot(orgId, mainBranch, head); + const text = snapshot.files.get("rules.md"); + const logRule = (at: string) => + git(orgId, writer, [ + "log", + "-1", + "--format=%H%x00%at%x00%an", + at, + "--", + "rules.md", + ]).pipe(Effect.map((line) => line.trimEnd().split("\0"))); + let [revision, date, name] = yield* logRule(head); + if (revision && revision !== head) { + const commitAt = (sha: string) => + readCommit(orgId, writer, sha).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(VcsProcess, vcs), + ); + const change = yield* commitAt(revision); + const authored = /^Kin-Local: ([a-f0-9]{40}(?:[a-f0-9]{24})?)$/m.exec( + change.message, + )?.[1]; + // A squash may rename the author; its identical, anchored source still has the owner commit. + if (authored !== undefined && (yield* isAncestor(orgId, writer, authored, head))) { + const source = yield* commitAt(authored); + if (source.tree === change.tree) [revision, date, name] = yield* logRule(authored); + } + } + const present = snapshot.rulesPresent === true; + const oversizedBytes = + snapshot.rulesBytes !== undefined && snapshot.rulesBytes > maxBlobBytes + ? snapshot.rulesBytes + : undefined; + if (text === undefined && present && oversizedBytes === undefined) + return yield* new MemoryError({ + orgId, + operation: "readRulesBook", + reason: "Unreadable rules.md", + }); + const stamp = date === undefined ? undefined : DateTime.make(Number(date) * 1000); + const syncedAt = lastSynced.get(orgId); + return { + present, + ...(oversizedBytes === undefined ? {} : { oversizedBytes }), + book: { + text: text ?? "", + revision: revision || null, + changedAt: stamp && stamp._tag === "Some" ? DateTime.formatIso(stamp.value) : null, + changedBy: name || null, + lastSyncedAt: + syncedAt === undefined ? null : DateTime.formatIso(DateTime.makeUnsafe(syncedAt)), + }, + }; + }), + ), + ), readRules: Effect.fn("Memory.readRules")((orgId) => locked(orgId, readFile(orgId, "rules.md"))), items: Effect.fn("Memory.items")((orgId, view) => locked(orgId, load(orgId, false, view).pipe(Effect.map((snapshot) => snapshot.items))), diff --git a/apps/server/src/kin/memory/MemoryChanges.test.ts b/apps/server/src/kin/memory/MemoryChanges.test.ts index 96bb5b250a30..e1b282375646 100644 --- a/apps/server/src/kin/memory/MemoryChanges.test.ts +++ b/apps/server/src/kin/memory/MemoryChanges.test.ts @@ -2,6 +2,9 @@ import { pairSession } from "../auth/ProofKeySessions.testkit.ts"; import { assert, it } from "@effect/vitest"; import { AuthSessionId, + AuthKinChatScope, + AuthKinTasksScope, + KinOrgId, AuthStandardClientScopes, KIN_MEMORY_CHANGES_CARD, KinAgentId, @@ -22,6 +25,7 @@ import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; import * as Sqlite from "../../persistence/Sqlite.ts"; +import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; import * as Audit from "../approvals/Audit.ts"; import * as PendingActions from "../approvals/PendingActions.ts"; import * as Chat from "../chat/layer.ts"; @@ -31,6 +35,7 @@ import { KinIdentity } from "../chat/KinIdentity.ts"; import { DREAM_LEFT_OUT_PREFIX } from "../dreaming/checkDream.ts"; import * as Kin from "../layer.ts"; import { dormantLeadDependencies } from "../lead/layer.testkit.ts"; +import { makeKinHandlers } from "../rpcHandlers.ts"; import { KinRecords } from "../work/KinRecords.ts"; import * as OwnerDocs from "../work/ownerDocs.ts"; import { KinMemoryChanges, type KinMemoryUndo } from "./MemoryChanges.ts"; @@ -58,6 +63,146 @@ const decodeCard = Schema.decodeUnknownSync(KinMemoryChangeCard); const encodeCard = Schema.encodeSync(KinMemoryChangeCard); const decodeHead = Schema.decodeUnknownSync(MemoryItemHead); +it.effect.each([ + "owner client", + "renewed owner phone", + "owner desktop", + "reusable dev token", + "migration owner device", + "removed teammate", + "co-owner client", + "teammate client", + "lead", + "agent MCP", + "schedule", + "owner coding-agent key", + "general API key", + "revoked owner client", + "expired owner client", + "wrong company", +] as const)("standing rules only accept the owner's own client: %s", (kind) => + Effect.gen(function* () { + const services = Option.getOrThrow((yield* Kin.KinServer).services); + const memory = Context.get(services, KinMemoryChanges); + const { owner } = Context.get(services, KinIdentity); + const { orgId } = owner; + const sql = yield* SqlClient.SqlClient; + const phone = kind === "renewed owner phone"; + const teammate = + kind === "co-owner client" || kind === "teammate client" || kind === "removed teammate"; + const caller: AuthenticatedSession = { + ...session, + subject: kind === "owner coding-agent key" ? "kin-coding-agent" : kind, + method: phone + ? "dpop-access-token" + : kind.endsWith("key") || kind === "agent MCP" || kind === "owner desktop" + ? "bearer-access-token" + : "browser-session-cookie", + ...(phone ? { proofKeyThumbprint: "fixture-phone-proof" } : {}), + scopes: teammate + ? [AuthKinChatScope] + : kind === "owner coding-agent key" + ? [AuthKinTasksScope] + : AuthStandardClientScopes, + }; + yield* sql`INSERT INTO auth_sessions (session_id, subject, method, scopes, issued_at, expires_at, revoked_at) + VALUES (${caller.sessionId}, ${caller.subject}, ${caller.method}, ${JSON.stringify(caller.scopes)}, '1970-01-01T00:00:00.000Z', + ${kind === "expired owner client" ? "1969-12-31T23:59:59.000Z" : "2099-01-01T00:00:00.000Z"}, + ${kind === "revoked owner client" ? "1970-01-01T00:00:00.000Z" : null})`; + if (teammate) { + const person = KinPersonId.make("fixture-teammate"); + yield* sql`INSERT INTO kin_people (org_id, person_id, handle, display_name, created_at, access) + VALUES (${orgId}, ${person}, 'fern', 'Fern Cove', '1970-01-01T00:00:00.000Z', + ${kind === "co-owner client" ? "co_owner" : "member"})`; + if (kind === "removed teammate") + yield* sql`UPDATE kin_people SET removed_at = '1970-01-01T00:00:00.000Z' WHERE person_id = ${person}`; + yield* sql`INSERT INTO kin_session_bindings (org_id, session_id, person_id, bound_at) + VALUES (${orgId}, ${caller.sessionId}, ${person}, 0)`; + } + if ( + kind === "owner client" || + kind.endsWith("owner client") || + kind === "wrong company" || + phone + ) + yield* pairSession(caller.sessionId); + if (phone) { + yield* sql`UPDATE auth_sessions SET expires_at = '1970-01-01T00:00:00.000Z', + proof_key_thumbprint = ${caller.proofKeyThumbprint} WHERE session_id = ${caller.sessionId}`; + yield* sql`UPDATE auth_sessions SET expires_at = '2099-01-01T00:00:00.000Z' + WHERE session_id = ${caller.sessionId}`; + } + const via = + kind === "reusable dev token" + ? "reusable-dev-token" + : kind === "migration owner device" + ? "migration" + : kind === "owner desktop" + ? "desktop-bootstrap" + : undefined; + if (via !== undefined) + yield* sql`INSERT INTO kin_auth_paired_sessions (session_id, via, created_at) + VALUES (${caller.sessionId}, ${via}, 0)`; + let writes = 0; + const book = { + text: "Use the silver ledger.", + revision: null, + changedAt: null, + changedBy: null, + lastSyncedAt: null, + }; + yield* memory.attachWriter({ + readRulesBook: () => Effect.succeed(book), + saveRulesBook: (input, authenticate) => + authenticate.pipe( + Effect.map((name) => { + writes++; + return { ...book, text: input.text, changedBy: name }; + }), + ), + undo: () => Effect.die("Unused"), + relabel: () => Effect.die("Unused"), + retire: () => Effect.die("Unused"), + restore: () => Effect.die("Unused"), + recordDecision: () => Effect.die("Unused"), + items: () => Effect.succeed([]), + }); + if (kind === "removed teammate") + assert.deepStrictEqual(yield* Context.get(services, KinIdentity).resolve(caller), []); + const target = kind === "wrong company" ? KinOrgId.make("fixture-other") : orgId; + const wire = yield* makeKinHandlers(caller); + const read = wire["kin.memory.readRules"]({ orgId: target }); + const save = wire["kin.memory.saveRules"]({ + orgId: target, + text: "New rules.", + revision: null, + }); + if (kind === "owner client" || phone || kind === "owner desktop") { + assert.deepStrictEqual(yield* read, book); + assert.strictEqual((yield* save).text, "New rules."); + assert.strictEqual(writes, 1); + } else if (kind === "migration owner device" || kind === "reusable dev token") { + for (const error of [yield* read.pipe(Effect.flip), yield* save.pipe(Effect.flip)]) { + if (kind === "migration owner device") { + assert.strictEqual(error._tag, "KinMemoryRulesPairAgain"); + assert.strictEqual( + error.message, + "This device was signed in before Kin recorded how devices were paired; pair it again to see or change standing rules.", + ); + } else { + if (error._tag !== "KinChatError") return assert.fail("Expected plain access refusal"); + assert.strictEqual(error.reason, "not_allowed"); + } + } + assert.strictEqual(writes, 0); + } else { + assert.strictEqual((yield* read.pipe(Effect.exit))._tag, "Failure"); + assert.strictEqual((yield* save.pipe(Effect.exit))._tag, "Failure"); + assert.strictEqual(writes, 0); + } + }).pipe(Effect.scoped, Effect.provide(root)), +); + it.effect("only the owner can undo an item on an earlier memory change card", () => Effect.gen(function* () { const kin = yield* Kin.KinServer; diff --git a/apps/server/src/kin/memory/MemoryChanges.ts b/apps/server/src/kin/memory/MemoryChanges.ts index d2bde8c27b16..87915cf6a37a 100644 --- a/apps/server/src/kin/memory/MemoryChanges.ts +++ b/apps/server/src/kin/memory/MemoryChanges.ts @@ -4,6 +4,12 @@ import { KinChatId, KinMemoryChangeCard, KinMessageId, + KinMemoryRulesChanged, + KinMemoryRulesPairAgain, + type KinMemoryRulesTooLarge, + type KinMemoryReadRulesInput, + type KinMemoryRules, + type KinMemorySaveRulesInput, type KinAgentId, type KinMemoryConfirmSuggestionsInput, type KinMemoryConfirmSuggestionsResult, @@ -37,13 +43,14 @@ import type * as Scope from "effect/Scope"; import * as SqlClient from "effect/sql/SqlClient"; import * as SqlError from "effect/sql/SqlError"; +import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; import { KinRefreshObserver } from "../chat/KinRefreshHub.ts"; import { toPersistenceSqlError } from "../../persistence/Errors.ts"; import * as Hub from "../chat/KinChatHub.ts"; import * as Repository from "../chat/KinChatRepository.ts"; import { KinIdentity, type PersonIdentity } from "../chat/KinIdentity.ts"; import { DREAM_LEFT_OUT_PREFIX } from "../dreaming/checkDream.ts"; -import { ownerLevel } from "../people/KinAccess.ts"; +import { isOwnerHimself, ownerLevel } from "../people/KinAccess.ts"; import { endedBy } from "./frontMatter.ts"; import { CHAT_SOURCE, readableSources } from "./quoteAccess.ts"; import type { MemoryItem } from "./MemoryCache.ts"; @@ -64,6 +71,8 @@ export type KinMemoryUndo = MemoryWriter["Service"]["undoChange"]; /** What the owner's own memory actions need of the lead runtime, which owns memory and its writer. */ export interface KinMemoryPort { readonly undo: KinMemoryUndo; + readonly readRulesBook?: MemoryWriter["Service"]["readRulesBook"]; + readonly saveRulesBook?: MemoryWriter["Service"]["saveRulesBook"]; readonly relabel: MemoryWriter["Service"]["relabel"]; readonly retire: MemoryWriter["Service"]["retire"]; readonly restore: MemoryWriter["Service"]["restore"]; @@ -141,6 +150,20 @@ export class KinMemoryChanges extends Context.Service< readonly snapshot?: boolean; }, ) => Effect.Effect, KinChatError>; + readonly readRules: ( + session: AuthenticatedSession, + input: KinMemoryReadRulesInput, + ) => Effect.Effect< + KinMemoryRules, + KinChatError | KinMemoryRulesPairAgain | KinMemoryRulesTooLarge + >; + readonly saveRules: ( + session: AuthenticatedSession, + input: KinMemorySaveRulesInput, + ) => Effect.Effect< + KinMemoryRules, + KinChatError | KinMemoryRulesChanged | KinMemoryRulesPairAgain | KinMemoryRulesTooLarge + >; /** The owner's switch for team memory in chats with teammates; owner level only. */ readonly setTeamMemory: ( people: ReadonlyArray, @@ -193,7 +216,8 @@ const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const repo = yield* Repository.KinChatRepository; const hub = yield* Hub.KinChatHub; - const { owner } = yield* KinIdentity; + const identity = yield* KinIdentity; + const { owner } = identity; let port: KinMemoryPort | undefined; const refresh = yield* KinRefreshObserver; // The labels these write are what the memory page reads, so their commits tell its refresh. @@ -261,6 +285,37 @@ const make = Effect.gen(function* () { ); const forgottenOnes = (items: ReadonlyArray, now: number) => items.filter(({ head }) => endedBy(head, now) && head.superseded_by === null); + const rulesOwner = Effect.fn("KinMemoryChanges.rulesOwner")(function* ( + session: AuthenticatedSession, + orgId: KinOrgId, + ) { + if ( + orgId !== owner.orgId || + !(yield* identity.resolve(session)).some( + (person) => person.orgId === orgId && isOwnerHimself(owner, person.personId), + ) + ) + return yield* ownerOnly; + const now = DateTime.formatIso(yield* DateTime.now); + // Only the pairing exchange records this provenance. Issued keys and agent MCP sessions do not. + const [person] = yield* sql<{ name: string; via: string; admitted: number }>` + SELECT p.display_name AS name, paired.via, + paired.via IN ('one-time-token', 'desktop-bootstrap') AS admitted + FROM auth_sessions s + JOIN kin_auth_paired_sessions paired ON paired.session_id = s.session_id + JOIN kin_people p ON p.org_id = ${orgId} AND p.person_id = ${owner.personId} + WHERE s.session_id = ${session.sessionId} AND s.subject = ${session.subject} + AND s.method = ${session.method} AND s.revoked_at IS NULL AND s.expires_at > ${now} + AND p.access = 'owner' AND p.removed_at IS NULL`.pipe(Effect.mapError(() => ownerOnly)); + if (person?.admitted !== 1) + return yield* person?.via === "migration" + ? new KinMemoryRulesPairAgain({ + message: + "This device was signed in before Kin recorded how devices were paired; pair it again to see or change standing rules.", + }) + : ownerOnly; + return person.name; + }); const ownerOf = Effect.fn("KinMemoryChanges.ownerOf")(function* ( people: ReadonlyArray, orgId: KinOrgId, @@ -643,6 +698,32 @@ const make = Effect.gen(function* () { .toSorted((a, b) => b.recordedAt - a.recordedAt || a.itemId.localeCompare(b.itemId)) .slice(0, input.limit); }), + readRules: Effect.fn("KinMemoryChanges.readRules")(function* (session, input) { + yield* rulesOwner(session, input.orgId); + if (port?.readRulesBook === undefined) return yield* unavailable; + const book = yield* port.readRulesBook(input.orgId).pipe(Effect.result); + yield* rulesOwner(session, input.orgId); + return yield* Effect.fromResult(book).pipe( + Effect.mapError((error) => (error._tag === "KinMemoryRulesTooLarge" ? error : unavailable)), + ); + }), + saveRules: Effect.fn("KinMemoryChanges.saveRules")(function* (session, input) { + const check = rulesOwner(session, input.orgId); + yield* check; + if (port?.saveRulesBook === undefined) return yield* unavailable; + return yield* port + .saveRulesBook(input, check) + .pipe( + Effect.mapError((error) => + error._tag === "KinMemoryRulesChanged" || + error._tag === "KinMemoryRulesPairAgain" || + error._tag === "KinMemoryRulesTooLarge" || + error._tag === "KinChatError" + ? error + : unavailable, + ), + ); + }), setTeamMemory: Effect.fn("KinMemoryChanges.setTeamMemory")(function* (people, input) { const { person } = yield* ownerOf(people, input.orgId); yield* setTeamMemory(input.orgId, input.on, person.personId).pipe(provideSql); diff --git a/apps/server/src/kin/memory/MemoryLander.ts b/apps/server/src/kin/memory/MemoryLander.ts index 53661d44cb22..fbcd7ec285c0 100644 --- a/apps/server/src/kin/memory/MemoryLander.ts +++ b/apps/server/src/kin/memory/MemoryLander.ts @@ -36,6 +36,7 @@ import type { MemoryWriteFailure } from "./writeFailure.ts"; /** The commit of the open guard-rails PR, kept so its head never changes under the owner. */ const GUARD_RAILS_REF = "refs/kin/guard-rails"; +const STANDING_RULES_BATCH = "refs/kin/standing-rules-batch"; const GUARD_RAILS_BRANCH = `${WRITE_BRANCH_PREFIX}guard-rails/`; // Left by servers from before Kin wrote every memory folder alone; folded in once at start. const LEGACY_REVIEW_REFS = "refs/kin/review/"; @@ -79,7 +80,7 @@ export class MemoryLander extends Context.Service< MemoryLander, { /** Wakes the org's lander and returns at once; signals during a landing ride the next batch. */ - readonly signal: (orgId: KinOrgId) => Effect.Effect; + readonly signal: (orgId: KinOrgId, shadow?: string) => Effect.Effect; /** Closes `kin/write/*` PRs no landing waits on; wakes the lander while its guard-rails PR waits. */ readonly sweep: ( orgId: KinOrgId, @@ -122,6 +123,8 @@ const make = Effect.gen(function* () { const foldedIn = new Set(); // One server owns a state directory (`serverOwnership.ts`), so no second process lands this repo. const signals = new Map>(); + const pendingShadows = new Map>(); + const reviewingRules = new Set(); const provide = (effect: Effect.Effect) => effect.pipe( @@ -134,8 +137,9 @@ const make = Effect.gen(function* () { args: ReadonlyArray, env: NodeJS.ProcessEnv = {}, stdin?: string, + onStdoutChunk?: (chunk: Uint8Array) => void, ) => - memoryGit(cwd, args, stdin, env).pipe( + memoryGit(cwd, args, stdin, env, onStdoutChunk).pipe( Effect.provideService(MemoryConfig, config), provide, Effect.mapError((cause) => new MemoryError({ orgId, operation: "land", cause })), @@ -575,6 +579,19 @@ const make = Effect.gen(function* () { yield* done; }); + const rulesBatch = (orgId: KinOrgId, writer: string) => + git(orgId, writer, ["rev-parse", "--verify", "--quiet", STANDING_RULES_BATCH]).pipe( + Effect.option, + ); + const forgetRulesBatch = Effect.fn("MemoryLander.forgetRulesBatch")(function* ( + orgId: KinOrgId, + writer: string, + batch: string, + ) { + yield* git(orgId, writer, ["update-ref", "--no-deref", "-d", STANDING_RULES_BATCH, batch]); + reviewingRules.delete(orgId); + }); + const landOnce = Effect.fn("MemoryLander.landOnce")(function* ( orgId: KinOrgId, target: NonNullable>, @@ -582,38 +599,76 @@ const make = Effect.gen(function* () { ) { if (Option.isNone(pullRequests)) return { _tag: "idle" } as const; const { writer, local, remote } = state; + const waitingRules = yield* rulesBatch(orgId, writer); if (remote !== undefined && remote.descends) { const upgrade = yield* upgradeGuardRails(orgId, writer, remote.head, target); // GitHub's head moved: the next batch starts from a fresh sync. if (upgrade === "merged") return { _tag: "upgraded" } as const; } if (remote !== undefined && !remote.pending) { + if (Option.isSome(waitingRules)) yield* forgetRulesBatch(orgId, writer, waitingRules.value); stuck.delete(orgId); yield* recovery.writeEpisode?.(orgId, "online-copy", undefined) ?? Effect.void; return { _tag: "idle" } as const; } - const held = stuck.get(orgId); + const held = Option.isSome(waitingRules) ? undefined : stuck.get(orgId); if (held?.owner !== undefined && remote !== undefined) { if ((yield* guardRailsKey(orgId, writer, remote.head)) === held.owner) return { _tag: "waiting" } as const; } else if (held?.local === local) return { _tag: "waiting" } as const; if (remote === undefined) return yield* refuse(orgId, local, "Kin could not reach GitHub"); - // Sync already logged why the two copies could not be combined. - if (!remote.descends) - return yield* refuse(orgId, local, "GitHub's copy changed in a way Kin could not combine", { - told: true, - failure: "online-conflict", - }); - // One commit on GitHub's head with this server's tree, so the PR holds just what GitHub lacks. - const tree = yield* git(orgId, writer, ["rev-parse", `${local}^{tree}`]); - const message = `kin: memory from this server up to ${local.slice(0, 12)}\n\nKin-Local: ${local}\n`; - const batch = yield* git( - orgId, - writer, - ["commit-tree", tree, "-p", remote.head], - yield* identity(), - message, - ); + if (!remote.descends) { + const reason = "GitHub's copy changed in a way Kin could not combine"; + stuck.set(orgId, { local, reason }); + return { _tag: "stuck", reason } as const; + } + const base = Option.isSome(waitingRules) + ? yield* git(orgId, writer, ["rev-parse", `${waitingRules.value}^`]) + : remote.head; + const standingRules = + Option.isSome(waitingRules) || + (yield* git(orgId, writer, ["diff-tree", "--name-only", base, local, "--", "rules.md"])) === + "rules.md"; + const prior = Option.isSome(waitingRules) + ? yield* git(orgId, writer, ["log", "-1", "--format=%B", waitingRules.value]) + : undefined; + const source = + prior === undefined + ? local + : /^Kin-Local: ([a-f0-9]{40}(?:[a-f0-9]{24})?)$/m.exec(prior)?.[1]; + if (source === undefined) + return yield* refuse(orgId, local, "Kin couldn’t read the pending rules revision"); + const tree = yield* git(orgId, writer, ["rev-parse", `${source}^{tree}`]); + const message = + prior ?? + `${standingRules ? "Update standing rules in Kin" : `kin: memory from this server up to ${source.slice(0, 12)}`}\n\nKin-Local: ${source}\n`; + const batch = Option.isSome(waitingRules) + ? waitingRules.value + : yield* git(orgId, writer, ["commit-tree", tree, "-p", base], yield* identity(), message); + if (standingRules && Option.isNone(waitingRules)) + yield* git(orgId, writer, [ + "update-ref", + "--no-deref", + STANDING_RULES_BATCH, + batch, + "0".repeat(batch.length), + ]); + if (standingRules) reviewingRules.add(orgId); + if (Option.isSome(waitingRules)) { + const descends = (older: string, newer: string) => + git(orgId, writer, ["merge-base", "--is-ancestor", older, newer]).pipe(Effect.isSuccess); + if ( + (yield* git(orgId, writer, ["rev-parse", `${batch}^{tree}`])) !== tree || + !(yield* descends(source, local)) || + !(yield* descends(base, source)) || + !(yield* descends(base, remote.head)) + ) + return yield* refuse( + orgId, + local, + "The pending standing rules revision does not match this repository", + ); + } const branch = `${WRITE_BRANCH_PREFIX}land/${batch.slice(0, 12)}`; const pushed = yield* git(orgId, writer, [ "push", @@ -632,7 +687,7 @@ const make = Effect.gen(function* () { sha: batch, title: message.split("\n")[0] ?? message, message, - kind: "batch", + kind: standingRules ? "standing-rules" : "batch", }) .pipe(Effect.result); if (landed._tag === "Failure") { @@ -651,6 +706,24 @@ const make = Effect.gen(function* () { ...(upgrading.has(orgId) ? {} : { failure: "review-needed" as const }), }); } + if (landed.success._tag === "held" && standingRules) { + yield* ( + recovery.writeEpisode?.( + orgId, + "online-copy", + landed.success.waitsOnOwner ? "review-needed" : "review", + landed.success.url, + ) ?? Effect.void + ); + return { _tag: "waiting" } as const; + } + if (landed.success._tag === "closed" && standingRules) { + yield* forgetRulesBatch(orgId, writer, batch); + return yield* refuse(orgId, local, "The standing rules pull request was closed", { + url: landed.success.url, + failure: "review", + }); + } if (landed.success._tag !== "merged") return yield* refuse(orgId, local, "GitHub kept the memory PR open", { failure: "review" }); const { url, commit } = landed.success; @@ -660,7 +733,7 @@ const make = Effect.gen(function* () { yield* git(orgId, writer, ["rev-parse", `${commit}^`]), yield* git(orgId, writer, ["rev-parse", `${commit}^{tree}`]), ]; - if (parent === remote.head && merged !== tree) + if (parent === base && merged !== tree) return yield* refuse(orgId, local, "GitHub merged a different tree than Kin pushed", { url, failure: "review", @@ -670,14 +743,15 @@ const make = Effect.gen(function* () { const landedAs = yield* git( orgId, writer, - ["commit-tree", tree, "-p", commit, "-p", local], + ["commit-tree", tree, "-p", commit, "-p", source], yield* identity(), - `kin: landed ${local} as ${commit}\n`, + `kin: landed ${source} as ${commit}\n`, ); const before = yield* git(orgId, writer, ["rev-parse", "--verify", "--quiet", LANDED_REF]).pipe( Effect.option, ); yield* git(orgId, writer, ["update-ref", LANDED_REF, landedAs]); + if (standingRules) yield* forgetRulesBatch(orgId, writer, batch); stuck.delete(orgId); yield* recovery.writeEpisode?.(orgId, "online-copy", undefined) ?? Effect.void; yield* git(orgId, writer, ["push", "--", target.repoUrl, `:refs/heads/${branch}`]).pipe( @@ -756,6 +830,8 @@ const make = Effect.gen(function* () { "--quiet", GUARD_RAILS_REF, ]).pipe(Effect.option); + const waitingRules = yield* rulesBatch(orgId, writer); + if (Option.isSome(waitingRules)) reviewingRules.add(orgId); const { pulls: open } = yield* pullRequests.value .openPulls({ orgId, repo: target.github }) .pipe(Effect.mapError(refused)); @@ -765,7 +841,16 @@ const make = Effect.gen(function* () { (sha) => pull.head === sha && pull.branch === `${GUARD_RAILS_BRANCH}${sha.slice(0, 12)}`, ); // Old review PRs are the fold-in's to close, once it has kept what they hold. - if (kept || LEGACY_REVIEW_BRANCH.test(pull.branch)) continue; + if ( + kept || + LEGACY_REVIEW_BRANCH.test(pull.branch) || + Option.exists( + waitingRules, + (sha) => + pull.head === sha && pull.branch === `${WRITE_BRANCH_PREFIX}land/${sha.slice(0, 12)}`, + ) + ) + continue; yield* pullRequests.value .close({ orgId, @@ -784,40 +869,139 @@ const make = Effect.gen(function* () { } }); - if (Option.isSome(pullRequests)) - for (const { orgId } of config.repositories) { - const queue = yield* Queue.dropping(1); - signals.set(orgId, queue); - // At start, changes an older server held for review are folded in and PRs a crash left open - // are closed before anything lands, so none is duplicated; then whatever is unlanded goes out. - const resume = sweep(orgId).pipe( - Effect.catchCause((cause) => - Effect.logWarning("Kin memory PR sweep failed at start", { - orgId, - cause: Cause.pretty(cause), - }), + const publishDirect = Effect.fn("MemoryLander.publishDirect")(function* ( + orgId: KinOrgId, + repoUrl: string, + ) { + let failed: { readonly head: string; readonly refused: boolean } | undefined; + for (let attempt = 0; attempt < 3; attempt++) { + const state = yield* memory.landingState(orgId); + if (state === undefined || state.remote === undefined || !state.remote.descends) return; + if (!state.remote.pending) { + yield* recovery.writeEpisode?.(orgId, "online-copy", undefined) ?? Effect.void; + return; + } + if (state.remote.head === failed?.head) { + if (failed.refused) + yield* ( + recovery.writeEpisode?.(orgId, "online-copy", "direct-push-refused") ?? Effect.void + ); + break; + } + const ref = `refs/heads/${main}`; + const refspec = `${state.local}:${ref}`; + let status = ""; + const decoder = new TextDecoder(); + // The expected tip rejects a rewind; only Git's per-ref remote rejection proves a refusal. + const pushed = yield* gitRaw( + orgId, + state.writer, + [ + "push", + "--porcelain", + `--force-with-lease=${ref}:${state.remote.head}`, + "--", + repoUrl, + refspec, + ], + { LC_ALL: "C" }, + undefined, + (chunk) => { + if (status.length < 4096) + status += decoder.decode(chunk.subarray(0, 4096 - status.length), { stream: true }); + }, + ).pipe(Effect.isSuccess); + if (pushed) { + yield* memory.rememberPublished(orgId, state.remote.head, state.local); + yield* recovery.writeEpisode?.(orgId, "online-copy", undefined) ?? Effect.void; + return; + } + failed = { + head: state.remote.head, + refused: status.split("\n").some((line) => { + const [flag, target, summary] = line.split("\t"); + return ( + flag === "!" && + target === refspec && + (summary?.startsWith("[remote rejected] ") ?? false) + ); + }), + }; + } + yield* Effect.logWarning("Memory journal publication will retry at the next sync", { orgId }); + }); + + const publishShadows = Effect.fn("MemoryLander.publishShadows")(function* ( + orgId: KinOrgId, + repoUrl: string, + ) { + const branches = pendingShadows.get(orgId); + if (branches === undefined || branches.size === 0) return; + if ((yield* memory.purgeInFlight(orgId)) !== undefined) return; + const generation = yield* memory.historyGeneration(orgId); + const { writer } = yield* memory.checkoutPaths(orgId); + for (const branch of branches) { + const head = yield* memory.anchor(orgId, branch); + if ( + !(yield* git(orgId, writer, ["push", "--", repoUrl, `${head}:refs/heads/${branch}`]).pipe( + Effect.isSuccess, + )) + ) { + yield* Effect.logWarning("Shadow journal publication will retry at the next sync", { + orgId, + branch, + }); + continue; + } + if ( + generation === (yield* memory.historyGeneration(orgId)) && + head === (yield* memory.anchor(orgId, branch)) + ) + branches.delete(branch); + } + }); + + for (const { orgId, repoUrl } of config.repositories) { + const queue = yield* Queue.dropping(1); + signals.set(orgId, queue); + pendingShadows.set(orgId, new Set()); + const start = Option.isSome(pullRequests); + // Only PR mode examines GitHub for orphaned PRs when the host starts. + const resume = sweep(orgId).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Kin memory PR sweep failed at start", { + orgId, + cause: Cause.pretty(cause), + }), + ), + Effect.andThen(land(orgId, true)), + ); + const publish = Effect.gen(function* () { + yield* publishShadows(orgId, repoUrl); + if (config.directMainPush === true && Option.isNone(pullRequests)) + yield* publishDirect(orgId, repoUrl); + if (start) yield* land(orgId); + else yield* hooks.settled(orgId, { _tag: "idle" }); + }); + const run = (atStart: boolean) => + memory.withLandingLock(orgId, atStart ? resume : publish).pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logError("Kin memory lander run ended abnormally", { + orgId, + cause: Cause.pretty(cause), + }), ), - Effect.andThen(land(orgId, true)), - ); - // A defect in one run must not end the loop: later signals would land nothing. - const run = (atStart: boolean) => - memory.withLandingLock(orgId, atStart ? resume : land(orgId)).pipe( - Effect.catchCauseIf( - (cause) => !Cause.hasInterruptsOnly(cause), - (cause) => - Effect.logError("Kin memory lander run ended abnormally", { - orgId, - cause: Cause.pretty(cause), - }), - ), - ); - yield* run(true).pipe( - Effect.andThen(Queue.take(queue).pipe(Effect.andThen(run(false)), Effect.forever)), - Effect.forkScoped, ); - } + yield* (start ? run(true) : Effect.void).pipe( + Effect.andThen(Queue.take(queue).pipe(Effect.andThen(run(false)), Effect.forever)), + Effect.forkScoped, + ); + } - const signal = Effect.fn("MemoryLander.signal")(function* (orgId: KinOrgId) { + const signal = Effect.fn("MemoryLander.signal")(function* (orgId: KinOrgId, shadow?: string) { + if (shadow !== undefined) pendingShadows.get(orgId)?.add(shadow); const queue = signals.get(orgId); if (queue !== undefined) yield* Queue.offer(queue, undefined); }); @@ -827,7 +1011,13 @@ const make = Effect.gen(function* () { // Every 5 minutes: the owner's approval on GitHub changes nothing Kin hears of otherwise. sweep: Effect.fn("MemoryLander.sweepLocked")(function* (orgId) { yield* memory.withLandingLock(orgId, sweep(orgId)); - if (upgrading.has(orgId)) yield* signal(orgId); + if ( + config.directMainPush === true || + upgrading.has(orgId) || + reviewingRules.has(orgId) || + (pendingShadows.get(orgId)?.size ?? 0) > 0 + ) + yield* signal(orgId); }), }); }); diff --git a/apps/server/src/kin/memory/MemoryPullRequests.test.ts b/apps/server/src/kin/memory/MemoryPullRequests.test.ts index 87809eb2bce6..2204ed537296 100644 --- a/apps/server/src/kin/memory/MemoryPullRequests.test.ts +++ b/apps/server/src/kin/memory/MemoryPullRequests.test.ts @@ -101,6 +101,7 @@ const scenarios = [ "crash-beyond-search", "decision-then-journal", "code-owner-refusal", + "owner-rules-review", "guard-rails-upgrade", "review-leftovers", ] as const; @@ -163,18 +164,27 @@ it.effect.each(scenarios)("memory writes through PRs: %s", (scenario) => fs .readFileString(`${ops}/memory-check.yml`) .pipe(Effect.map((text) => text.replace('""', `"${pin}"`))); - const guarded = ["decision-then-journal", "code-owner-refusal", "guard-rails-upgrade"].includes( - scenario, - ); + const guarded = [ + "decision-then-journal", + "owner-rules-review", + "code-owner-refusal", + "guard-rails-upgrade", + ].includes(scenario); if (guarded) { yield* fs.makeDirectory(`${source}/.github/workflows`, { recursive: true }); yield* fs.writeFileString( `${source}/.github/CODEOWNERS`, - scenario === "decision-then-journal" ? installed : oldCodeowners, + scenario === "decision-then-journal" || scenario === "owner-rules-review" + ? installed + : oldCodeowners, ); yield* fs.writeFileString( `${source}/.github/workflows/memory-check.yml`, - yield* workflow(scenario === "decision-then-journal" ? buildCommit : oldPin), + yield* workflow( + scenario === "decision-then-journal" || scenario === "owner-rules-review" + ? buildCommit + : oldPin, + ), ); } if (scenario === "off-github-strip-quotes") { @@ -713,6 +723,35 @@ it.effect.each(scenarios)("memory writes through PRs: %s", (scenario) => return; } + if (scenario === "owner-rules-review") { + const before = yield* writer.readRulesBook(orgId); + const saved = yield* writer.saveRulesBook( + { orgId, revision: before.revision, text: "Use the violet ledger.\n" }, + Effect.succeed("Quill Vale"), + ); + expect(saved.changedBy).toBe("Quill Vale"); + expect(yield* landing).toEqual({ _tag: "waiting" }); + expect(pulls.get(1)?.state).toBe("open"); + expect(yield* bare("show", "main:rules.md")).not.toContain("violet"); + expect(yield* memory.readRules(orgId)).toContain("violet"); + yield* journal("wake1"); + expect(yield* landing).toEqual({ _tag: "waiting" }); + expect(opened()).toBe(1); + approved.add(1); + yield* lander.sweep(orgId); + expect(yield* landing).toMatchObject({ _tag: "merged" }); + expect(yield* landing).toMatchObject({ _tag: "merged" }); + yield* settled; + expect(yield* bare("show", "main:rules.md")).toContain("violet"); + expect(yield* writer.readRulesBook(orgId)).toMatchObject({ + revision: saved.revision, + changedBy: "Quill Vale", + }); + expect(yield* bare("show", `main:${journalPath}`)).toContain("wake-up wake1"); + expect(opened()).toBe(2); + return; + } + if (scenario === "code-owner-refusal") { yield* writer.recordDecision(orgId, decision("decision-0001")); expect(yield* landing).toMatchObject({ diff --git a/apps/server/src/kin/memory/MemoryPullRequests.ts b/apps/server/src/kin/memory/MemoryPullRequests.ts index 16507f7ed535..78222b0a7976 100644 --- a/apps/server/src/kin/memory/MemoryPullRequests.ts +++ b/apps/server/src/kin/memory/MemoryPullRequests.ts @@ -117,7 +117,7 @@ interface MemoryPullRequestInput { * the repo's guard rails up to date: only the owner may approve it, so it stays open, its head * untouched (a push would dismiss his approval), and every landing run tries to merge it again. */ - readonly kind: "batch" | "guard-rails"; + readonly kind: "batch" | "guard-rails" | "standing-rules"; } export interface OpenMemoryPullRequest { @@ -325,6 +325,7 @@ export const make = Effect.fn("MemoryPullRequests.make")(function* (options: { input.repo, ); const guardRails = input.kind === "guard-rails"; + const reviewable = input.kind !== "batch"; const describe = (answer: { status: number; message: string }) => `HTTP ${answer.status}${answer.message ? `: ${answer.message}` : ""}`; const openFromBranch = call( @@ -334,8 +335,8 @@ export const make = Effect.fn("MemoryPullRequests.make")(function* (options: { ).pipe(Effect.map((listed) => Option.getOrUndefined(decodePulls(listed.body))?.[0])); // The guard-rails PR is opened once and found again on every later run. - let pull = guardRails ? yield* openFromBranch : undefined; - if (guardRails && pull === undefined) { + let pull = reviewable ? yield* openFromBranch : undefined; + if (reviewable && pull === undefined) { const listed = yield* call( "pulls.list", "GET", @@ -351,7 +352,9 @@ export const make = Effect.fn("MemoryPullRequests.make")(function* (options: { base: input.base, body: guardRails ? `Kin's memory repo guard rails, as its server now ships them: \`.github/CODEOWNERS\` and \`.github/workflows/memory-check.yml\`, nothing else. Kin pushed \`${input.sha}\` and merges this itself once you approve it and \`${MEMORY_CHECK_NAME}\` passes. It never pushes to this branch again, so your approval stays; if the head differs, close it.` - : `Kin merges this once \`${MEMORY_CHECK_NAME}\` passes on the commit it pushed.`, + : input.kind === "standing-rules" + ? `Standing rules saved by the company owner in Kin. Kin merges the exact commit once \`${MEMORY_CHECK_NAME}\` and the repository’s review requirements are satisfied.` + : `Kin merges this once \`${MEMORY_CHECK_NAME}\` passes on the commit it pushed.`, maintainer_can_modify: false, }); pull = opened.status === 201 ? Option.getOrUndefined(decodePull(opened.body)) : undefined; @@ -370,7 +373,7 @@ export const make = Effect.fn("MemoryPullRequests.make")(function* (options: { ); // A batch PR is closed on any refusal; the guard-rails PR waits, open, for what can change it. const hold = (reason: string, waitsOnOwner = false) => - guardRails + reviewable ? Effect.succeed({ _tag: "held", url, reason, waitsOnOwner } as const) : refuseAndClose(reason, waitsOnOwner); diff --git a/apps/server/src/kin/memory/MemoryWriter.test.ts b/apps/server/src/kin/memory/MemoryWriter.test.ts index 5105f6fdc2fc..0f10658e350a 100644 --- a/apps/server/src/kin/memory/MemoryWriter.test.ts +++ b/apps/server/src/kin/memory/MemoryWriter.test.ts @@ -1,3 +1,5 @@ +import * as Queue from "effect/Queue"; +import { MemoryLander, MemoryLanderHooks } from "./MemoryLander.ts"; import * as SqlClient from "effect/sql/SqlClient"; import { memoryGit } from "./git.ts"; import * as NodeZlib from "node:zlib"; @@ -51,6 +53,15 @@ it.live.each([ "two-leads-same-id", "recovery-after-other-commit", "prompt-snapshot-stale-head", + "owner-rules-cas", + "owner-rules-missing", + "owner-rules-oversized", + "owner-rules-no-publication", + "journal-protected-push", + "journal-offline-push", + "journal-push-race", + "journal-push-conflict", + "journal-push-rewritten", "completed", "failed", "blocked", @@ -209,6 +220,23 @@ it.live.each([ ]); yield* commit(source); } + if (scenario === "journal-push-conflict") { + yield* fs.makeDirectory(`${source}/journal/2026`, { recursive: true }); + yield* fs.writeFileString(`${source}/journal/2026/11-08.md`, "Original journal.\n"); + yield* git(source, ["add", "--", "journal"]); + yield* commit(source); + } + if (scenario === "journal-push-rewritten") + yield* git(source, [ + "-c", + "user.name=Fixture Bot", + "-c", + "user.email=fixture@example.invalid", + "commit", + "--allow-empty", + "-m", + "Later upstream revision", + ]); yield* git(root, ["clone", "--bare", "--", source, remote]); let attack: { objectPath: string; sha: string; expression: string; bytes: Buffer } | undefined; let swapped = false; @@ -224,6 +252,9 @@ it.live.each([ >) | undefined; let failBranch = false; + let beforeDirectPush: ReturnType | undefined; + let refusedPushes = 0; + let pushOffline = scenario === "journal-offline-push"; let restarted = false; const memoryRuns: Array = []; const interceptedGit = Layer.succeed( @@ -250,7 +281,32 @@ it.live.each([ cause: "fixture branch failure", }); } - const result = yield* vcs.run(input); + const direct = + input.args.includes("push") && + input.args.some((arg) => arg.endsWith(":refs/heads/main")); + if (direct && beforeDirectPush !== undefined) { + const publishOutside = beforeDirectPush; + beforeDirectPush = undefined; + yield* publishOutside.pipe(Effect.orDie); + } + const result = yield* vcs + .run( + direct && pushOffline + ? { + ...input, + args: input.args.map((arg) => + arg === remote ? `${root}/unreachable.git` : arg, + ), + } + : input, + ) + .pipe( + Effect.tapError(() => + Effect.sync(() => { + if (direct) refusedPushes++; + }), + ), + ); if (substituteTree && input.args.includes("write-tree")) return { ...result, stdout: substituteTree }; if (onRefChange && input.args.includes("update-ref")) { @@ -263,17 +319,30 @@ it.live.each([ }), ); const notices: Writer.WriterNotice[] = []; + const ownerNotices: string[] = []; + const publishEpisodes: Array = []; + const landingSettled = yield* Queue.unbounded(); + const landerHooks = Layer.succeed(MemoryLanderHooks, { + settled: () => Queue.offer(landingSettled, undefined).pipe(Effect.asVoid), + }); const config = Layer.succeed(MemoryConfig, { baseDirectory: root, credentialHelper: "fixture-server-helper", sshCommand: "ssh -i /fixture/kin-memory-key", - directMainPush: true, + directMainPush: scenario !== "owner-rules-no-publication", repositories: [{ orgId, repoUrl: remote, path: "state" }], }); const synced: Array> = []; const memoryLayer = Memory.layer.pipe( Layer.provide(config), - Layer.provide(Layer.succeed(Memory.MemoryRecoveryHooks, { notify: () => Effect.void })), + Layer.provide( + Layer.succeed(Memory.MemoryRecoveryHooks, { + notify: (notice) => + Effect.sync(() => { + if (notice.owner !== undefined) ownerNotices.push(notice.owner); + }), + }), + ), Layer.provide( Layer.succeed(Memory.MemorySyncHooks, { syncItems: (_org, snapshot) => @@ -314,6 +383,9 @@ it.live.each([ scenario === "prompt-snapshot-stale-head" || scenario === "conflict" || scenario === "B5-journal" || + scenario.startsWith("journal-push-") || + scenario === "journal-protected-push" || + scenario === "journal-offline-push" || scenario === "read-during-record" || scenario.startsWith("deferral-") ? "L1" @@ -365,8 +437,17 @@ it.live.each([ }); const scan = Scan.layer; const layer = Writer.layer.pipe( + Layer.provide(landerHooks), Layer.provideMerge(memoryLayer), - Layer.provide(Layer.succeed(Memory.MemoryRecoveryHooks, { notify: () => Effect.void })), + Layer.provide( + Layer.succeed(Memory.MemoryRecoveryHooks, { + notify: () => Effect.void, + writeEpisode: (_org, operation, failure) => + Effect.sync(() => { + if (operation === "online-copy") publishEpisodes.push(failure); + }), + }), + ), Layer.provide(config), Layer.provide(hooks), Layer.provide(auth), @@ -581,6 +662,216 @@ it.live.each([ expect(journal).not.toContain(Writer.RESTART_JOURNAL_LINE); return; } + if (scenario === "owner-rules-no-publication") { + const book = yield* writer.readRulesBook(orgId); + const result = yield* writer + .saveRulesBook( + { orgId, revision: book.revision, text: "Use the gray ledger." }, + Effect.succeed("Quill Vale"), + ) + .pipe(Effect.flip); + expect(result).toMatchObject({ + _tag: "KinChatError", + reason: "invalid_state", + message: + "Standing rules can’t be saved on this host because memory has no way to publish; ask the host administrator to set up memory publishing.", + }); + expect(yield* memory.anchor(orgId, "main")).toBe(original); + return; + } + if (scenario === "owner-rules-missing" || scenario === "owner-rules-oversized") { + const oversized = scenario === "owner-rules-oversized"; + if (oversized) + yield* fs.writeFileString(`${source}/rules.md`, "x".repeat(Memory.maxBlobBytes + 1)); + else yield* fs.remove(`${source}/rules.md`); + yield* git(source, ["add", "-A", "--", "rules.md"]); + yield* commit(source); + const revision = yield* git(source, ["rev-parse", "HEAD"]); + yield* git(source, ["push", "--", remote, "main"]); + yield* memory.syncCheckout(orgId); + const auth = Effect.succeed("Quill Vale"); + if (oversized) { + const tooLarge = { + _tag: "KinMemoryRulesTooLarge", + revision, + sizeBytes: Memory.maxBlobBytes + 1, + maxBytes: Memory.maxBlobBytes, + }; + expect(yield* writer.readRulesBook(orgId).pipe(Effect.flip)).toMatchObject(tooLarge); + expect( + yield* writer + .saveRulesBook({ orgId, revision: original, text: "Not a repair." }, auth) + .pipe(Effect.flip), + ).toMatchObject(tooLarge); + } else { + expect(yield* writer.readRulesBook(orgId)).toMatchObject({ text: "", revision }); + const pin = yield* memory.prepareWakeup(orgId, "wake1"); + expect(yield* memory.readPromptSnapshot(orgId, pin.head).pipe(Effect.flip)).toMatchObject( + { + reason: "Missing committed prompt rules", + }, + ); + } + expect(yield* memory.anchor(orgId, "main")).toBe(revision); + expect( + yield* writer.saveRulesBook({ orgId, revision, text: "Use the new ledger." }, auth), + ).toMatchObject({ + text: "Use the new ledger.", + changedBy: "Quill Vale", + }); + return; + } + if (scenario === "journal-offline-push") { + const local = yield* writer.commitWakeup(orgId, "wake1", "completed"); + yield* Queue.take(landingSettled); + expect(refusedPushes).toBe(1); + expect(publishEpisodes).toEqual([]); + expect(yield* git(root, [`--git-dir=${remote}`, "rev-parse", "main"])).toBe(original); + pushOffline = false; + const lander = yield* MemoryLander; + yield* lander.sweep(orgId); + yield* Queue.take(landingSettled); + expect(yield* git(root, [`--git-dir=${remote}`, "rev-parse", "main"])).toBe(local.commit); + return; + } + if (scenario === "journal-protected-push") { + const hook = `${remote}/hooks/pre-receive`; + yield* fs.writeFileString(hook, "#!/bin/sh\nexit 1\n"); + yield* fs.chmod(hook, 0o755); + const local = yield* writer.commitWakeup(orgId, "wake1", "completed"); + yield* Queue.take(landingSettled); + expect(refusedPushes).toBe(1); + expect(publishEpisodes).toEqual(["direct-push-refused"]); + expect(yield* memory.anchor(orgId, "main")).toBe(local.commit); + expect(yield* git(root, [`--git-dir=${remote}`, "rev-parse", "main"])).toBe(original); + const lander = yield* MemoryLander; + yield* lander.sweep(orgId); + yield* Queue.take(landingSettled); + expect(publishEpisodes).toEqual(["direct-push-refused", "direct-push-refused"]); + yield* fs.remove(hook); + yield* lander.sweep(orgId); + yield* Queue.take(landingSettled); + expect(publishEpisodes.at(-1)).toBeUndefined(); + expect(yield* git(root, [`--git-dir=${remote}`, "rev-parse", "main"])).toBe(local.commit); + return; + } + if (scenario === "owner-rules-cas") { + const sql = yield* SqlClient.SqlClient; + const at = "2026-11-08T00:00:00.000Z"; + yield* sql`INSERT INTO kin_orgs VALUES (${orgId}, 'Fixture', ${at})`; + yield* sql`INSERT INTO kin_people (person_id, org_id, handle, display_name, created_at) VALUES ('owner', ${orgId}, 'owner', 'Quill Vale', ${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, direct_key, last_seq, created_at) + VALUES ('fixture-direct', ${orgId}, 'direct', 'owner:fixture-direct', 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, '{}', '[]', 'fixture-direct')`; + const shadow = yield* writer.commitWakeup(orgId, "wake0", "completed"); + yield* Queue.take(landingSettled); + const initial = yield* writer.readRulesBook(orgId); + const view = { lead: agentId }; + const before = yield* memory.prepareWakeup(orgId, "wake1", view); + expect(before.head).toBe(shadow.commit); + expect(initial.text).toBe("Invented rules\n"); + const authenticate = Effect.succeed("Quill Vale"); + const draft = { orgId, revision: initial.revision, text: "Use the amber ledger.\n" }; + const saved = yield* writer.saveRulesBook(draft, authenticate); + expect(saved).toMatchObject({ text: draft.text, changedBy: "Quill Vale" }); + expect(saved.revision).not.toBe(initial.revision); + const after = yield* memory.prepareWakeup(orgId, "wake2", view); + expect(after.head).toBe(before.head); + expect(after.rulesHead).toBe(saved.revision); + expect( + (yield* memory.readPromptSnapshot(orgId, before.head, view, before.rulesHead)).rules, + ).toBe(initial.text); + expect( + (yield* memory.readPromptSnapshot(orgId, after.head, view, after.rulesHead)).rules, + ).toBe(draft.text); + expect(yield* fs.readFileString(`${after.read}/rules.md`)).toBe(draft.text); + expect(yield* memory.standingChange(orgId, after.rulesHead!)).toBeDefined(); + const tooBig = yield* writer + .saveRulesBook( + { ...draft, revision: saved.revision, text: "é".repeat(131_073) }, + authenticate, + ) + .pipe(Effect.flip); + expect(tooBig).toMatchObject({ _tag: "KinChatError", reason: "limit" }); + const badText = yield* writer + .saveRulesBook( + { ...draft, revision: saved.revision, text: String.fromCharCode(0xd800) }, + authenticate, + ) + .pipe(Effect.flip); + expect(badText).toMatchObject({ _tag: "KinChatError", reason: "invalid_state" }); + const stale = yield* writer + .saveRulesBook({ ...draft, text: "Different text" }, authenticate) + .pipe(Effect.flip); + expect(stale).toMatchObject({ + _tag: "KinMemoryRulesChanged", + current: { text: saved.text, revision: saved.revision, changedBy: saved.changedBy }, + }); + const withdrawn = yield* writer.saveRulesBook( + { ...draft, revision: saved.revision, text: "" }, + authenticate, + ); + expect(withdrawn.text).toBe(""); + expect((yield* writer.readRulesBook(orgId)).text).toBe(""); + const emptyPin = yield* memory.prepareWakeup(orgId, "wake3", view); + expect( + (yield* memory.readPromptSnapshot(orgId, emptyPin.head, view, emptyPin.rulesHead)).rules, + ).toBe(""); + return; + } + if (scenario === "journal-push-rewritten") { + const parent = yield* git(source, ["rev-parse", "HEAD^"]); + beforeDirectPush = git(root, [ + `--git-dir=${remote}`, + "update-ref", + "refs/heads/main", + parent, + original, + ]); + const journal = yield* writer.commitWakeup(orgId, "wake1", "completed"); + yield* Queue.take(landingSettled); + expect(refusedPushes).toBe(1); + expect(yield* git(root, [`--git-dir=${remote}`, "rev-parse", "main"])).toBe(parent); + expect(yield* memory.anchor(orgId, "main")).toBe(journal.commit); + expect(ownerNotices).toHaveLength(1); + yield* memory.syncCheckout(orgId); + expect(ownerNotices).toHaveLength(1); + return; + } + if (scenario === "journal-push-race" || scenario === "journal-push-conflict") { + const conflicting = scenario === "journal-push-conflict"; + const path = conflicting ? "journal/2026/11-08.md" : "rules.md"; + if (conflicting) yield* fs.makeDirectory(`${source}/journal/2026`, { recursive: true }); + yield* fs.writeFileString(`${source}/${path}`, "An outside edit.\n"); + yield* git(source, ["add", "--", path]); + yield* commit(source); + const remoteCommit = yield* git(source, ["rev-parse", "HEAD"]); + beforeDirectPush = git(source, ["push", "--", remote, "main"]); + yield* writer.appendJournal(orgId, "wake1", ["A local journal line."]); + const { commit: journal } = yield* writer.commitWakeup(orgId, "wake1", "completed"); + yield* Queue.take(landingSettled); + expect(refusedPushes).toBe(1); + const published = yield* git(root, [`--git-dir=${remote}`, "rev-parse", "main"]); + if (conflicting) { + expect(published).toBe(remoteCommit); + expect(yield* memory.anchor(orgId, "main")).toBe(journal); + expect(ownerNotices).toHaveLength(1); + yield* memory.syncCheckout(orgId); + expect(ownerNotices).toHaveLength(1); + } else { + expect(published).not.toBe(remoteCommit); + expect(yield* git(root, [`--git-dir=${remote}`, "show", "main:rules.md"])).toBe( + "An outside edit.", + ); + expect( + yield* git(root, [`--git-dir=${remote}`, "show", "main:journal/2026/11-08.md"]), + ).toContain("A local journal line."); + expect(ownerNotices).toEqual([]); + } + return; + } if (scenario === "prompt-snapshot-stale-head") { const pinned = yield* memory.prepareWakeup(orgId, "wake1"); yield* writer.stage(orgId, "wake2", { @@ -801,6 +1092,7 @@ it.live.each([ yield* memory.prepareWakeup(orgId); } const result = yield* writer.commitWakeup(orgId, "wake1", "completed"); + yield* Queue.take(landingSettled); expect(yield* git(root, [`--git-dir=${remote}`, "show", `${result.commit}:rules.md`])).toBe( "Invented rules", ); @@ -840,6 +1132,7 @@ it.live.each([ content: fixtureItem({ kind: "claim" }), }); yield* writer.commitWakeup(orgId, "wake1", "completed"); + yield* Queue.take(landingSettled); const remoteRuns = memoryRuns.filter((run) => run.args.includes(remote)); expect( new Set( @@ -898,6 +1191,7 @@ it.live.each([ // The remote lost the shadow branch (a refused push, say); the anchored local head is its only copy. const shadow = `kin/shadow/${agentId}`; const { commit } = yield* writer.commitWakeup(orgId, "wake0", "completed"); + yield* Queue.take(landingSettled); yield* git(root, [`--git-dir=${remote}`, "update-ref", "-d", `refs/heads/${shadow}`]); yield* memory.recover(orgId); expect(yield* memory.anchor(orgId, shadow)).toBe(commit); @@ -908,11 +1202,15 @@ it.live.each([ return; } if (scenario === "P8-lost-writer" || scenario === "P9-shadow") { - if (scenario === "P9-shadow") yield* writer.commitWakeup(orgId, "wake0", "completed"); + if (scenario === "P9-shadow") { + yield* writer.commitWakeup(orgId, "wake0", "completed"); + yield* Queue.take(landingSettled); + } yield* fs.remove(paths.writer, { recursive: true }); yield* memory.recover(orgId); yield* memory.prepareWakeup(orgId); const result = yield* writer.commitWakeup(orgId, "wake1", "completed"); + yield* Queue.take(landingSettled); expect( yield* git(root, [ `--git-dir=${remote}`, @@ -1272,15 +1570,23 @@ it.live.each([ expect(yield* git(paths.writer, ["rev-parse", "main"])).toBe(original); return; } - if (scenario === "blocked" || scenario === "conflict") { - expect(result._tag).toBe("Failure"); - if (result._tag === "Failure") - expect(result.failure._tag).toBe( - scenario === "blocked" ? "MemorySecretBlocked" : "MemorySyncConflict", - ); - + if (scenario === "conflict") { + expect(result._tag).toBe("Success"); + yield* Queue.take(landingSettled); + expect(notices).toHaveLength(0); + expect(ownerNotices).toHaveLength(1); + expect(yield* git(root, [`--git-dir=${remote}`, "show", "main:claims/new.md"])).toBe( + "Owner conflicting fixture", + ); + expect(yield* git(paths.writer, ["show", "main:claims/new.md"])).not.toContain( + "Owner conflicting fixture", + ); + return; + } + if (scenario === "blocked") { + expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: "MemorySecretBlocked" } }); expect(notices).toHaveLength(1); - if (scenario === "blocked") { + { expect(JSON.stringify(notices)).not.toContain("aB3dE6gH9jK2mN5pQ8sT1vW4yZ7cF0iL3oR6"); expect(yield* git(paths.writer, ["rev-parse", "HEAD"])).toBe(original); expect( @@ -1304,6 +1610,7 @@ it.live.each([ if (scenario === "B3-execution") expect(yield* fs.readFileString(marker).pipe(Effect.orElseSucceed(() => ""))).toBe(""); if (scenario === "B4-pushurl") { + yield* Queue.take(landingSettled); expect( yield* git(root, [`--git-dir=${remote}`, "rev-parse", `refs/heads/${branch}`]), ).toBe(result._tag === "Success" ? result.success.commit : ""); @@ -1850,7 +2157,12 @@ it.effect( repositories: [{ orgId, repoUrl: remote, path: "state" }], }); const episodes: Array<{ operation: string; failure: string | undefined }> = []; + const landed = yield* Queue.unbounded(); + const landerHooks = Layer.succeed(MemoryLanderHooks, { + settled: () => Queue.offer(landed, undefined).pipe(Effect.asVoid), + }); const layer = Writer.layer.pipe( + Layer.provide(landerHooks), Layer.provideMerge( Memory.layer.pipe( Layer.provide(config), @@ -1913,6 +2225,7 @@ it.effect( // An L0 lead's wake-up leaves the same items on its shadow branch. yield* writer.appendJournal(orgId, "wake0", ["Only a note."]); yield* writer.commitWakeup(orgId, "wake0", "completed"); + yield* Queue.take(landed); const shadow = Memory.shadowBranch(agentId); const bare = (args: ReadonlyArray) => git(root, [`--git-dir=${remote}`, ...args]); const show = (branch: string, path: string) => bare(["show", `${branch}:${path}`]); diff --git a/apps/server/src/kin/memory/MemoryWriter.ts b/apps/server/src/kin/memory/MemoryWriter.ts index 25ddff36a02e..ca242900133f 100644 --- a/apps/server/src/kin/memory/MemoryWriter.ts +++ b/apps/server/src/kin/memory/MemoryWriter.ts @@ -11,6 +11,11 @@ import { isCheckoutPath } from "./checkoutPaths.ts"; import * as MemoryCache from "./MemoryCache.ts"; import { KinChatError, + KinMemoryRulesChanged, + type KinMemoryRulesPairAgain, + KinMemoryRulesTooLarge, + type KinMemoryRules, + type KinMemorySaveRulesInput, MemoryItemFrontMatter, type KinAgentId, type KinChatId, @@ -44,6 +49,7 @@ import { MemoryNotFound, MemoryDuplicateId, shadowBranch, + maxBlobBytes, } from "./Memory.ts"; import { changedKeys, @@ -237,6 +243,20 @@ export class MemoryWriter extends Context.Service< wakeupId: string, outcome: "completed" | "failed", ) => Effect.Effect<{ commit: string }, Failure>; + readonly readRulesBook: ( + orgId: KinOrgId, + ) => Effect.Effect; + readonly saveRulesBook: ( + input: KinMemorySaveRulesInput, + authenticate: Effect.Effect, + ) => Effect.Effect< + KinMemoryRules, + | Failure + | KinChatError + | KinMemoryRulesChanged + | KinMemoryRulesPairAgain + | KinMemoryRulesTooLarge + >; readonly dreamBase: ( orgId: KinOrgId, ) => Effect.Effect<{ head: string; files: ReadonlyMap }, Failure>; @@ -356,7 +376,6 @@ const make = Effect.gen(function* () { const unquotedHeads = new Map(); const recovery = yield* MemoryRecoveryHooks; // Shadow branches whose last push was refused; the owner hears once until a push lands. - const unpushedShadows = new Set(); const authority = yield* MemoryWriterAuthority; const hooks = yield* MemoryWriterHooks; const lander = yield* MemoryLander.MemoryLander; @@ -663,6 +682,25 @@ const make = Effect.gen(function* () { const paths = yield* memory.ensureCheckouts(orgId); return paths; }); + const oversizedRules = (revision: KinMemoryRules["revision"], sizeBytes: number) => + new KinMemoryRulesTooLarge({ + revision, + sizeBytes, + maxBytes: maxBlobBytes, + message: `The saved standing rules are ${sizeBytes} bytes, above the ${maxBlobBytes}-byte limit; replace them with a shorter rulebook.`, + }); + const existingRulesCheckout = Effect.fn("MemoryWriter.existingRulesCheckout")(function* ( + orgId: KinOrgId, + ) { + const { writer } = yield* memory.checkoutPaths(orgId); + if (!(yield* io(orgId, fs.exists(writer)))) + return yield* new MemoryCheckoutInvalid({ + orgId, + operation: "rules", + reason: "The memory repository is not available locally yet", + }); + return yield* validate(orgId); + }); // Every caller holds the writer lock, and the marker only changes under it. const refuseDuringPurge = Effect.fn("MemoryWriter.refuseDuringPurge")(function* ( orgId: KinOrgId, @@ -750,6 +788,7 @@ const make = Effect.gen(function* () { parentFiles: ReadonlyMap, changes: ReadonlyMap, message: string, + rulesAuthor?: string, ) { return yield* Effect.scoped( Effect.gen(function* () { @@ -757,6 +796,12 @@ const make = Effect.gen(function* () { const env = { GIT_INDEX_FILE: `${temporary}/index`, ...(yield* memoryIdentity(config, app)), + ...(rulesAuthor === undefined + ? {} + : { + GIT_AUTHOR_NAME: rulesAuthor, + GIT_AUTHOR_EMAIL: "kin-owner@localhost", + }), }; yield* git(orgId, writer, ["read-tree", "--empty"], env); const entries = yield* treeAt(orgId, writer, parent); @@ -765,7 +810,9 @@ const make = Effect.gen(function* () { for (const [file, bytes] of changes) finalFiles.set(file, bytes); const expected = new Map(); for (const [file, bytes] of finalFiles) { - if (changes.has(file)) yield* safePath(orgId, writer, file, true); + // The separate authenticated rules method can pass only this fixed path. + if (changes.has(file) && !(file === "rules.md" && rulesAuthor !== undefined)) + yield* safePath(orgId, writer, file, true); const input = `${temporary}/blob`; yield* io(orgId, fs.writeFile(input, bytes)); const mode = changes.has(file) ? "100644" : (metadata.get(file)?.mode ?? "100644"); @@ -1234,36 +1281,8 @@ const make = Effect.gen(function* () { ctx.level === "L0" ? shadowBranch(ctx.agentId) : (config.defaultBranch ?? "main"); const onMain = branch === (config.defaultBranch ?? "main"); if (onMain && mainWrites === "refused") return yield* refuseMainWrite(orgId); - const viaPullRequest = onMain && mainWrites === "pull_request"; const recorded = yield* branchHead(orgId, writer, branch); - const unpushedKey = `${orgId}\u0000${branch}`; - const push = (sha: string) => - git(orgId, writer, ["push", "--", repo.repoUrl, `${sha}:refs/heads/${branch}`]).pipe( - Effect.tap(() => Effect.sync(() => unpushedShadows.delete(unpushedKey))), - // A shadow commit is already what the lead reads, so a refused push leaves it on this server only. - Effect.tapError(() => - onMain || unpushedShadows.has(unpushedKey) - ? Effect.void - : Effect.sync(() => unpushedShadows.add(unpushedKey)).pipe( - Effect.andThen( - recovery.notify({ - orgId, - branch, - reason: `The memory repo refused ${branch}, so this agent's shadow memory is only on this server. Kin pushes it again with the next commit; check that the memory deploy key can push kin/shadow/*`, - }), - ), - ), - ), - Effect.mapError( - (cause) => - new MemorySyncConflict({ - orgId, - operation: "push", - reason: "Push rejected; retry or reconcile remote", - cause, - }), - ), - ); + const publish = lander.signal(orgId, onMain ? undefined : branch); return yield* Effect.gen(function* () { const subject = wakeupSubject(ctx); const fingerprintOf = () => @@ -1288,8 +1307,7 @@ const make = Effect.gen(function* () { !body.includes(`Kin-Request: ${fingerprint}`)) ) return yield* new MemoryWriteRejected({ reason: "Different wake-up retry" }); - if (viaPullRequest) yield* lander.signal(orgId); - else yield* push(recorded); + yield* publish; return { commit: own }; } if (outcome === "failed") state.files.clear(); @@ -1374,14 +1392,109 @@ const make = Effect.gen(function* () { }), ), ); - if (viaPullRequest) yield* lander.signal(orgId); - else yield* push(commit); + yield* publish; return { commit }; }).pipe(Effect.ensuring(Effect.sync(() => finish(orgId, wakeupId)))); }), ), ), ), + readRulesBook: Effect.fn("MemoryWriter.readRulesBook")((orgId) => + locked( + orgId, + Effect.gen(function* () { + yield* existingRulesCheckout(orgId); + const head = yield* memory.anchor(orgId, config.defaultBranch ?? "main"); + const { book, oversizedBytes } = yield* memory.readRulesBook(orgId, head); + return oversizedBytes === undefined + ? book + : yield* oversizedRules(book.revision, oversizedBytes); + }), + ), + ), + saveRulesBook: Effect.fn("MemoryWriter.saveRulesBook")((input, authenticate) => + locked( + input.orgId, + Effect.gen(function* () { + const { orgId, revision, text } = input; + yield* authenticate; + const bytes = Buffer.from(text); + if (bytes.length > maxBlobBytes) + return yield* new KinChatError({ + reason: "limit", + message: "Standing rules must be 256 KiB or smaller.", + }); + if (bytes.toString("utf8") !== text) + return yield* new KinChatError({ + reason: "invalid_state", + message: "Standing rules must be valid UTF-8 text.", + }); + const { writer } = yield* existingRulesCheckout(orgId); + yield* refuseDuringPurge(orgId); + const branch = config.defaultBranch ?? "main"; + const head = yield* branchHead(orgId, writer, branch); + const { + book: current, + present, + oversizedBytes, + } = yield* memory.readRulesBook(orgId, head); + yield* authenticate; + if (revision !== current.revision) { + if (oversizedBytes !== undefined) + return yield* oversizedRules(current.revision, oversizedBytes); + return yield* new KinMemoryRulesChanged({ + message: "Standing rules changed since you opened them.", + current, + }); + } + if (present && oversizedBytes === undefined && current.text === text) return current; + if (mainWrites === "refused") + return yield* new KinChatError({ + reason: "invalid_state", + message: + "Standing rules can’t be saved on this host because memory has no way to publish; ask the host administrator to set up memory publishing.", + }); + const findings = yield* scanner.scan({ + orgId, + files: [{ path: "rules.md", content: bytes }], + }); + if (findings.length > 0) + return yield* new KinChatError({ + reason: "invalid_state", + message: "Standing rules can’t contain credentials.", + }); + const author = yield* authenticate; + const commit = yield* writeCommit( + orgId, + writer, + head, + yield* filesAt(orgId, writer, head), + new Map([["rules.md", bytes]]), + "Update standing rules in Kin\n", + author, + ); + const { book: result } = yield* memory.readRulesBook(orgId, commit); + yield* Effect.uninterruptible( + Effect.gen(function* () { + yield* authenticate; + const ref = `refs/heads/${branch}`; + yield* git(orgId, writer, ["update-ref", "--no-deref", ref, commit, head]); + yield* memory + .record(orgId, branch, head, commit) + .pipe( + Effect.onError(() => + git(orgId, writer, ["update-ref", "--no-deref", ref, head, commit]).pipe( + Effect.ignore, + ), + ), + ); + yield* lander.signal(orgId); + }), + ); + return result; + }), + ), + ), dreamBase: Effect.fn("MemoryWriter.dreamBase")((orgId) => locked( orgId, diff --git a/apps/server/src/kin/memory/rpcHandlers.ts b/apps/server/src/kin/memory/rpcHandlers.ts index 39471ee4388e..d83bf8d5cc9e 100644 --- a/apps/server/src/kin/memory/rpcHandlers.ts +++ b/apps/server/src/kin/memory/rpcHandlers.ts @@ -65,6 +65,18 @@ export const makeKinMemoryHandlers = Effect.fn("makeKinMemoryHandlers")(function const people = yield* Context.get(services, KinIdentity).resolve(session); return yield* Context.get(services, KinMemoryChanges).restore(people, input); }, Effect.catchDefect(defect)), + "kin.memory.readRules": (input) => + Option.isNone(kin) || Option.isNone(kin.value.services) + ? Effect.fail(disabled) + : Context.get(kin.value.services.value, KinMemoryChanges) + .readRules(session, input) + .pipe(Effect.catchDefect(defect)), + "kin.memory.saveRules": (input) => + Option.isNone(kin) || Option.isNone(kin.value.services) + ? Effect.fail(disabled) + : Context.get(kin.value.services.value, KinMemoryChanges) + .saveRules(session, input) + .pipe(Effect.catchDefect(defect)), "kin.memory.setTeamMemory": Effect.fn("KinMemory.rpc.setTeamMemory")(function* (input) { if (Option.isNone(kin) || Option.isNone(kin.value.services)) return yield* disabled; const services = kin.value.services.value; diff --git a/apps/server/src/kin/memory/writeFailure.ts b/apps/server/src/kin/memory/writeFailure.ts index 163a626bd89d..200c2ed32758 100644 --- a/apps/server/src/kin/memory/writeFailure.ts +++ b/apps/server/src/kin/memory/writeFailure.ts @@ -21,6 +21,8 @@ export const MEMORY_WRITE_FAILURE_WORDS = { "Kin couldn't send the memory changes to the online copy. What is already saved on this server goes up with the next memory change; if this stays, ask whoever looks after Kin to check the memory repository's access.", review: "GitHub didn't accept Kin's memory changes. They are kept on this server; ask whoever looks after Kin to check the memory repository's rules on GitHub.", + "direct-push-refused": + "Memory is saved here, but the repository refused to publish it; ask the host administrator to check write access and branch protection.", "online-conflict": "Kin couldn't combine the memory changes made on GitHub with the ones saved here, so both are kept apart. Ask whoever looks after Kin to settle the two in the memory repository.", "review-needed": diff --git a/apps/server/src/kin/rpcAccess.test.ts b/apps/server/src/kin/rpcAccess.test.ts index 442495f27d75..043b40aa2263 100644 --- a/apps/server/src/kin/rpcAccess.test.ts +++ b/apps/server/src/kin/rpcAccess.test.ts @@ -242,6 +242,8 @@ it.layer(layerKinAuthTest("kin-rpc-access-"))("KIN_RPC_ACCESS", (it) => { methods.filter((method) => !table.coOwner.includes(method)), [ "kin.host.cacheDaily", + "kin.memory.readRules", + "kin.memory.saveRules", "kin.people.setAccess", "kin.people.setOwnerName", // What Kin suggested to the owner, and his answers: his alone. diff --git a/apps/server/src/kin/tasksKey/reach.test.ts b/apps/server/src/kin/tasksKey/reach.test.ts index 1f196fc45ab9..a6175ad65324 100644 --- a/apps/server/src/kin/tasksKey/reach.test.ts +++ b/apps/server/src/kin/tasksKey/reach.test.ts @@ -543,6 +543,8 @@ const reach: Readonly | string>> = { "kin.memory.forget": "stays in the app: 6 (deleting or archiving)", "kin.memory.restore": "not reached yet: forgetting ends the sharing approval and search_memory only reads current lines", + "kin.memory.readRules": "stays in the app: 5 (host, company sections and settings)", + "kin.memory.saveRules": "stays in the app: 5 (host, company sections and settings)", "kin.memory.setTeamMemory": "stays in the app: 5 (host, company sections and settings)", "kin.work.summary": "not a person action (screens only: Tasks screen counts)", "kin.work.list": ["list_tasks", "list_my_tasks", "list_invoices", "list_entries"], diff --git a/packages/contracts/src/auth.kin.test.ts b/packages/contracts/src/auth.kin.test.ts index cf6e05d016e9..f0041e0ea098 100644 --- a/packages/contracts/src/auth.kin.test.ts +++ b/packages/contracts/src/auth.kin.test.ts @@ -13,7 +13,7 @@ import { import { clientRpcRequiredScopes } from "./clientRpcPermissions.ts"; import { KinCacheDailyInput } from "./kinHostCare.ts"; import { KinBankSenderRpcs } from "./kinBankSenders.ts"; -import { KIN_RPC_AGGREGATES, KIN_RPC_SCOPES, kinRpcAccess } from "./kinRpcs.ts"; +import { KIN_RPC_AGGREGATES, KIN_RPC_SCOPES, kinAccessAllows, kinRpcAccess } from "./kinRpcs.ts"; it("calls a session chat-only when it reaches Kin chats and none of the coding app", () => { const granted = (permissions: ReadonlyArray) => ({ @@ -65,3 +65,20 @@ it("requires the Usage grant and the org owner for daily cache figures, with a r for (const localDate of ["2026-02-29", "2026-02-30", "2026-13-01", "2026-11-28T00:00:00Z", null]) expect(accepts({ localDate })).toBe(false); }); + +it.each(["kin.memory.readRules", "kin.memory.saveRules"])( + "requires the chat scope and actual org owner for %s", + (tag) => { + expect(clientRpcRequiredScopes(tag, {})).toEqual([AuthKinChatScope]); + const access = kinRpcAccess(tag); + expect(access).toBe("org_owner"); + if (access === undefined) throw new Error("Missing rules access entry"); + expect(kinAccessAllows("owner", access)).toBe(true); + expect(kinAccessAllows("co_owner", access)).toBe(false); + expect(kinAccessAllows("member", access)).toBe(false); + expect(kinAccessAllows(null, access)).toBe(false); + expect( + sessionGrantsScope({ authenticated: true, scopes: [AuthKinTasksScope] }, AuthKinChatScope), + ).toBe(false); + }, +); diff --git a/packages/contracts/src/kinMemory.ts b/packages/contracts/src/kinMemory.ts index 2fd2e0cea63e..829b7a618eca 100644 --- a/packages/contracts/src/kinMemory.ts +++ b/packages/contracts/src/kinMemory.ts @@ -2,7 +2,7 @@ import * as Rpc from "effect/rpc/Rpc"; import * as Schema from "effect/Schema"; import { EnvironmentAuthorizationError, AuthKinChatScope } from "./auth.ts"; -import { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { IsoDateTime, NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { KinAgentId, KinChatError, @@ -174,6 +174,50 @@ export type KinMemorySetTeamMemoryInput = typeof KinMemorySetTeamMemoryInput.Typ export const KinMemorySetTeamMemoryResult = Schema.Struct({ teamMemory: Schema.Boolean }); export type KinMemorySetTeamMemoryResult = typeof KinMemorySetTeamMemoryResult.Type; +const KinRulesRevision = Schema.NullOr( + Schema.String.check(Schema.isPattern(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/)), +); + +export const KinMemoryReadRulesInput = Schema.Struct({ orgId: KinOrgId }); +export type KinMemoryReadRulesInput = typeof KinMemoryReadRulesInput.Type; +export const KinMemorySaveRulesInput = Schema.Struct({ + orgId: KinOrgId, + text: Schema.String, + revision: KinRulesRevision, +}); +export type KinMemorySaveRulesInput = typeof KinMemorySaveRulesInput.Type; +export const KinMemoryRules = Schema.Struct({ + text: Schema.String, + revision: KinRulesRevision, + changedAt: Schema.NullOr(IsoDateTime), + changedBy: Schema.NullOr(Schema.String), + lastSyncedAt: Schema.NullOr(IsoDateTime), +}); +export type KinMemoryRules = typeof KinMemoryRules.Type; + +export class KinMemoryRulesChanged extends Schema.TaggedError()( + "KinMemoryRulesChanged", + { + message: Schema.String, + current: KinMemoryRules, + }, +) {} + +export class KinMemoryRulesPairAgain extends Schema.TaggedError()( + "KinMemoryRulesPairAgain", + { message: Schema.String }, +) {} + +export class KinMemoryRulesTooLarge extends Schema.TaggedError()( + "KinMemoryRulesTooLarge", + { + message: Schema.String, + revision: KinRulesRevision, + sizeBytes: NonNegativeInt, + maxBytes: NonNegativeInt, + }, +) {} + const KIN_MEMORY_WS_METHODS = { undo: "kin.memory.undo", list: "kin.memory.list", @@ -182,6 +226,8 @@ const KIN_MEMORY_WS_METHODS = { forget: "kin.memory.forget", restore: "kin.memory.restore", setTeamMemory: "kin.memory.setTeamMemory", + readRules: "kin.memory.readRules", + saveRules: "kin.memory.saveRules", } as const; // Owner of the lead only, on the server; the scope gates the client's button. @@ -221,6 +267,27 @@ export const KinMemoryRpcs = [ success: KinMemorySetTeamMemoryResult, error: Schema.Union([KinChatError, EnvironmentAuthorizationError]), }), + Rpc.make(KIN_MEMORY_WS_METHODS.readRules, { + payload: KinMemoryReadRulesInput, + success: KinMemoryRules, + error: Schema.Union([ + KinChatError, + EnvironmentAuthorizationError, + KinMemoryRulesPairAgain, + KinMemoryRulesTooLarge, + ]), + }), + Rpc.make(KIN_MEMORY_WS_METHODS.saveRules, { + payload: KinMemorySaveRulesInput, + success: KinMemoryRules, + error: Schema.Union([ + KinMemoryRulesChanged, + KinChatError, + EnvironmentAuthorizationError, + KinMemoryRulesPairAgain, + KinMemoryRulesTooLarge, + ]), + }), ] as const; export const KIN_MEMORY_RPC_SCOPES = { @@ -232,4 +299,6 @@ export const KIN_MEMORY_RPC_SCOPES = { [KIN_MEMORY_WS_METHODS.forget]: AuthKinChatScope, [KIN_MEMORY_WS_METHODS.restore]: AuthKinChatScope, [KIN_MEMORY_WS_METHODS.setTeamMemory]: AuthKinChatScope, + [KIN_MEMORY_WS_METHODS.readRules]: AuthKinChatScope, + [KIN_MEMORY_WS_METHODS.saveRules]: AuthKinChatScope, } as const; diff --git a/packages/contracts/src/kinRpcs.ts b/packages/contracts/src/kinRpcs.ts index e9688552ae10..3c5f63c45bd8 100644 --- a/packages/contracts/src/kinRpcs.ts +++ b/packages/contracts/src/kinRpcs.ts @@ -381,6 +381,8 @@ const KIN_RPC_ACCESS = { "kin.memory.forget": "owner_level", "kin.memory.restore": "owner_level", "kin.memory.setTeamMemory": "owner_level", + "kin.memory.readRules": "org_owner", + "kin.memory.saveRules": "org_owner", "kin.work.summary": "person", "kin.work.list": "person", "kin.work.get": "person", @@ -784,6 +786,8 @@ export const KIN_RPC_AGGREGATES = { "kin.memory.forget": "kin-memory", "kin.memory.restore": "kin-memory", "kin.memory.setTeamMemory": "kin-memory", + "kin.memory.readRules": "kin-memory", + "kin.memory.saveRules": "kin-memory", "kin.docs.list": "kin-docs", "kin.docs.get": "kin-docs", "kin.docs.history": "kin-docs",