Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
fix(memory): preserve pending update governance (#44)
Leo4fdaeb54e12d
diff --git a/apps/server/src/memory/Layers/MemoryCandidateRepository.test.ts b/apps/server/src/memory/Layers/MemoryCandidateRepository.test.tsindex b49221f96..7da4a233e 100644--- a/apps/server/src/memory/Layers/MemoryCandidateRepository.test.ts+++ b/apps/server/src/memory/Layers/MemoryCandidateRepository.test.ts@@ -73,6 +73,7 @@ const candidate = (id: string): AkeruMemoryCandidate => ({sensitive: false,confidence: 0.9,affectedBotIds: [access.botId],+ pendingUpdate: null,status: "pending",createdAt: "2026-08-30T20:00:00.000Z",decidedAt: null,diff --git a/apps/server/src/memory/Layers/MemoryCandidateRepository.ts b/apps/server/src/memory/Layers/MemoryCandidateRepository.tsindex ef9aa440b..0fec340a9 100644--- a/apps/server/src/memory/Layers/MemoryCandidateRepository.ts+++ b/apps/server/src/memory/Layers/MemoryCandidateRepository.ts@@ -1,5 +1,6 @@import {AkeruMemoryCandidate,+ AkeruMemoryCandidateUpdate,AkeruMemoryDecisionReceipt,AkeruMemoryEntityId,type AkeruMemoryRevision,@@ -36,6 +37,7 @@ const CandidateRow = Schema.Struct({sensitive: Schema.Number,confidence: Schema.Number,affectedBotIds: Schema.String,+ pendingUpdate: Schema.NullOr(Schema.String),status: Schema.String,createdAt: Schema.String,decidedAt: Schema.NullOr(Schema.String),@@ -48,7 +50,8 @@ const candidateColumns = `initiating_user_id AS initiatingUserId, source_thread_id AS sourceThreadId,source_message_id AS sourceMessageId, author_bot_id AS authorBotId,fact_text AS fact, target_scope AS scope, sensitive, confidence,- affected_bot_ids_json AS affectedBotIds, status, created_at AS createdAt,+ affected_bot_ids_json AS affectedBotIds, pending_update_json AS pendingUpdate,+ status, created_at AS createdAt,decided_at AS decidedAt, decided_memory_root_id AS decidedMemoryRootId`;@@ -57,9 +60,16 @@ const decodeCandidate = Effect.fn("MemoryCandidateRepository.decodeCandidate")(const affectedBotIds = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Schema.String)),)(row.affectedBotIds);+ const pendingUpdate =+ row.pendingUpdate === null+ ? null+ : yield* Schema.decodeUnknownEffect(Schema.fromJsonString(AkeruMemoryCandidateUpdate))(+ row.pendingUpdate,+ );return yield* Schema.decodeUnknownEffect(AkeruMemoryCandidate)({...row,affectedBotIds,+ pendingUpdate,sensitive: row.sensitive === 1,});},@@ -67,6 +77,7 @@ const decodeCandidate = Effect.fn("MemoryCandidateRepository.decodeCandidate")();const encodeBotIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));+const encodePendingUpdate = Schema.encodeSync(Schema.fromJsonString(AkeruMemoryCandidateUpdate));const encodeValue = Schema.encodeSync(Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),);@@ -105,7 +116,7 @@ const authorizeCandidate = (access: AkeruMemoryThreadAccess, candidate: AkeruMem};const targetScope = (revision: AkeruMemoryRevision): AkeruMemoryTargetScope =>- revision.partition.scope === "bot-user"+ revision.partition.scope === "bot-user" || revision.partition.scope === "user"? "private": (revision.partition.scope as AkeruMemoryTargetScope);@@ -177,13 +188,14 @@ const makeMemoryCandidateRepository = Effect.gen(function* () {candidate_id, tenant_id, initiating_user_id, source_thread_id,source_message_id, author_bot_id, fact_text, target_scope, sensitive,confidence, affected_bot_ids_json, status, created_at, decided_at,- decided_memory_root_id+ decided_memory_root_id, pending_update_json) VALUES (${row.candidateId}, ${row.tenantId}, ${row.initiatingUserId}, ${row.sourceThreadId},${row.sourceMessageId}, ${row.authorBotId}, ${row.fact}, ${row.scope},${row.sensitive ? 1 : 0}, ${row.confidence},${encodeBotIds(row.affectedBotIds)}, ${row.status}, ${row.createdAt},- ${row.decidedAt}, ${row.decidedMemoryRootId}+ ${row.decidedAt}, ${row.decidedMemoryRootId},+ ${row.pendingUpdate === null ? null : encodePendingUpdate(row.pendingUpdate)})`.pipe(Effect.mapError(toPersistenceSqlError("MemoryCandidateRepository.create:query")));return row;@@ -223,9 +235,14 @@ const makeMemoryCandidateRepository = Effect.gen(function* () {);const initialRevision = revision.revision === 1 && revision.supersedesId === null;const nextRevision = revision.revision > 1 && revision.supersedesId !== null;+ const candidateUpdatesExisting = candidate.pendingUpdate !== null;if (!authorized ||(!initialRevision && !nextRevision) ||+ candidateUpdatesExisting !== nextRevision ||+ (candidateUpdatesExisting &&+ (revision.rootId !== candidate.pendingUpdate?.rootId ||+ revision.revision !== candidate.pendingUpdate.expectedRevision + 1)) ||revision.supersededById !== null ||revision.approvalState !== "approved" ||revision.deletionState !== "active" ||diff --git a/apps/server/src/memory/MemoryToolHandlers.test.ts b/apps/server/src/memory/MemoryToolHandlers.test.tsindex 403fb6f83..bde37a42a 100644--- a/apps/server/src/memory/MemoryToolHandlers.test.ts+++ b/apps/server/src/memory/MemoryToolHandlers.test.ts@@ -1,6 +1,8 @@import { assert, it } from "@effect/vitest";import {AkeruMemoryCandidateId,+ AkeruMemoryEntityId,+ AkeruMemoryId,AkeruMemoryRootId,AkeruMemoryTenantId,AkeruMemoryUserId,@@ -12,6 +14,7 @@ import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";+import { resolveAuthorizedMemoryPartitions } from "./EntityMemoryAccess.ts";import { EntityMemoryRepositoryLive } from "./Layers/EntityMemoryRepository.ts";import { MemoryCandidateRepositoryLive } from "./Layers/MemoryCandidateRepository.ts";import {@@ -134,6 +137,68 @@ it.layer(layer)("MemoryToolHandlers", (it) => {}),);+ it.effect("keeps approved private updates in an imported user partition", () =>+ Effect.gen(function* () {+ const repository = yield* EntityMemoryRepository;+ const candidates = yield* MemoryCandidateRepository;+ const handlers = createMemoryToolHandlers(repository, candidates, access);+ const partition = (yield* resolveAuthorizedMemoryPartitions(access)).find(+ (candidate) => candidate.scope === "user",+ );+ assert.isDefined(partition);+ const rootId = AkeruMemoryRootId.make("imported-user-root");+ yield* repository.insert({+ access,+ revision: {+ id: AkeruMemoryId.make("imported-user-revision"),+ rootId,+ revision: 1,+ partition,+ entityKind: "user",+ entityId: AkeruMemoryEntityId.make(access.userId),+ kind: "fact",+ value: {},+ fact: "Use npm.",+ sourceThreadId: access.threadId,+ sourceMessageId: null,+ authorBotId: access.botId,+ initiatingUserId: access.userId,+ createdAt: "2026-08-31T00:00:00.000Z",+ confirmedAt: "2026-08-31T00:00:00.000Z",+ updatedAt: "2026-08-31T00:00:00.000Z",+ confidence: 1,+ approvalState: "approved",+ supersedesId: null,+ supersededById: null,+ visibility: "private",+ deletionState: "active",+ pinned: false,+ sensitive: false,+ affectedBotIds: [access.botId],+ },+ });+ const pending = (yield* Effect.promise(() =>+ execute("update_memory", handlers.update_memory, {+ memoryId: rootId,+ expectedRevision: 1,+ fact: "Use Bun.",+ scope: "private",+ }),+ )) as { candidateId: string };++ yield* Effect.promise(() =>+ decideMemoryCandidate(repository, candidates, access, {+ candidateId: AkeruMemoryCandidateId.make(pending.candidateId),+ decision: "approve",+ }),+ );+ const current = yield* repository.getCurrent({ access, rootId });+ assert.equal(current.partition.scope, "user");+ assert.equal(current.partition.partitionId, partition.partitionId);+ assert.equal(current.fact, "Use Bun.");+ }),+ );+it.effect("approves or rejects each candidate once", () =>Effect.gen(function* () {const repository = yield* EntityMemoryRepository;@@ -207,6 +272,12 @@ it.layer(layer)("MemoryToolHandlers", (it) => {}),)) as { candidateId: string };+ const storedCandidate = (yield* candidates.listPending({ access })).find(+ (candidate) => candidate.candidateId === pending.candidateId,+ );+ assert.equal(storedCandidate?.pendingUpdate?.rootId, saved.rootId);+ assert.equal(storedCandidate?.pendingUpdate?.expectedRevision, 1);+const before = yield* repository.getCurrent({access,rootId: AkeruMemoryRootId.make(saved.rootId),@@ -216,7 +287,7 @@ it.layer(layer)("MemoryToolHandlers", (it) => {yield* Effect.promise(() =>decideMemoryCandidate(repository,- candidates,+ { ...candidates },access,{candidateId: AkeruMemoryCandidateId.make(pending.candidateId),@@ -237,6 +308,120 @@ it.layer(layer)("MemoryToolHandlers", (it) => {}),);+ it.effect("requires review when an update removes shared or sensitive policy", () =>+ Effect.gen(function* () {+ const repository = yield* EntityMemoryRepository;+ const candidates = yield* MemoryCandidateRepository;+ const handlers = createMemoryToolHandlers(repository, candidates, access);+ const sharedCandidate = (yield* Effect.promise(() =>+ execute("remember", handlers.remember, {+ fact: "Shared fact.",+ scope: "project",+ }),+ )) as { candidateId: string };+ const sensitiveCandidate = (yield* Effect.promise(() =>+ execute("remember", handlers.remember, {+ fact: "Sensitive fact.",+ scope: "private",+ sensitive: true,+ }),+ )) as { candidateId: string };+ const shared = yield* Effect.promise(() =>+ decideMemoryCandidate(repository, candidates, access, {+ candidateId: AkeruMemoryCandidateId.make(sharedCandidate.candidateId),+ decision: "approve",+ }),+ );+ const sensitive = yield* Effect.promise(() =>+ decideMemoryCandidate(repository, candidates, access, {+ candidateId: AkeruMemoryCandidateId.make(sensitiveCandidate.candidateId),+ decision: "approve",+ }),+ );++ const privateUpdate = yield* Effect.promise(() =>+ execute("update_memory", handlers.update_memory, {+ memoryId: shared.memoryRootId,+ expectedRevision: 1,+ fact: "Private fact.",+ scope: "private",+ }),+ );+ const nonSensitiveUpdate = yield* Effect.promise(() =>+ execute("update_memory", handlers.update_memory, {+ memoryId: sensitive.memoryRootId,+ expectedRevision: 1,+ fact: "Non-sensitive fact.",+ scope: "private",+ sensitive: false,+ }),+ );++ assert.equal((privateUpdate as { status: string }).status, "pending");+ assert.equal((nonSensitiveUpdate as { status: string }).status, "pending");+ assert.equal(+ (yield* repository.getCurrent({+ access,+ rootId: AkeruMemoryRootId.make(String(shared.memoryRootId)),+ })).partition.scope,+ "project",+ );+ assert.isTrue(+ (yield* repository.getCurrent({+ access,+ rootId: AkeruMemoryRootId.make(String(sensitive.memoryRootId)),+ })).sensitive,+ );+ }),+ );++ it.effect("rejects a persisted pending update when its expected revision is stale", () =>+ Effect.gen(function* () {+ const repository = yield* EntityMemoryRepository;+ const candidates = yield* MemoryCandidateRepository;+ const handlers = createMemoryToolHandlers(repository, candidates, access);+ const saved = (yield* Effect.promise(() =>+ execute("remember", handlers.remember, {+ fact: "Use npm.",+ scope: "private",+ }),+ )) as { rootId: string };+ const pending = (yield* Effect.promise(() =>+ execute("update_memory", handlers.update_memory, {+ memoryId: saved.rootId,+ expectedRevision: 1,+ fact: "Use Bun.",+ scope: "project",+ }),+ )) as { candidateId: string };+ yield* Effect.promise(() =>+ execute("update_memory", handlers.update_memory, {+ memoryId: saved.rootId,+ expectedRevision: 1,+ fact: "Use pnpm.",+ scope: "private",+ }),+ );++ const failed = yield* Effect.promise(() =>+ decideMemoryCandidate(repository, { ...candidates }, access, {+ candidateId: AkeruMemoryCandidateId.make(pending.candidateId),+ decision: "approve",+ }).then(+ () => false,+ (error) => String(error).includes("stale"),+ ),+ );+ const current = yield* repository.getCurrent({+ access,+ rootId: AkeruMemoryRootId.make(saved.rootId),+ });+ assert.isTrue(failed);+ assert.equal(current.revision, 2);+ assert.equal(current.fact, "Use pnpm.");+ }),+ );+it.effect("routes forget OCC through tombstone", () =>Effect.gen(function* () {const repository = yield* EntityMemoryRepository;diff --git a/apps/server/src/memory/MemoryToolHandlers.ts b/apps/server/src/memory/MemoryToolHandlers.tsindex 72bd2dfc6..3ae5ed807 100644--- a/apps/server/src/memory/MemoryToolHandlers.ts+++ b/apps/server/src/memory/MemoryToolHandlers.ts@@ -27,13 +27,6 @@ export type AkeruMemoryToolHandler = (input: Omit<AkeruToolExecution, "toolId"> & { readonly toolId: AkeruMemoryToolId },) => Promise<unknown>;-type PendingUpdate = {- readonly rootId: AkeruMemoryRootId;- readonly expectedRevision: number;-};--const pendingUpdates = new WeakMap<MemoryCandidateRepositoryShape, Map<string, PendingUpdate>>();-const nowIso = () => DateTime.formatIso(DateTime.nowUnsafe());function field(input: unknown, name: string): unknown {@@ -124,7 +117,10 @@ async function revisionFor(now: string,current?: AkeruMemoryRevision,) {- const partition = await partitionFor(scope, access);+ const partition =+ current?.partition.scope === "user" && scope === "private"+ ? { ...current.partition, visibility: current.visibility }+ : await partitionFor(scope, access);return {...current,id: AkeruMemoryId.make(NodeCrypto.randomUUID()),@@ -154,16 +150,6 @@ async function revisionFor(} satisfies AkeruMemoryRevision;}-function rememberPendingUpdate(- candidates: MemoryCandidateRepositoryShape,- candidateId: string,- update: PendingUpdate,-) {- const updates = pendingUpdates.get(candidates) ?? new Map<string, PendingUpdate>();- updates.set(candidateId, update);- pendingUpdates.set(candidates, updates);-}-export async function decideMemoryCandidate(repository: EntityMemoryRepositoryShape,candidates: MemoryCandidateRepositoryShape,@@ -188,17 +174,17 @@ export async function decideMemoryCandidate(decidedAt,}),);- pendingUpdates.get(candidates)?.delete(candidate.candidateId);return receipt;}- const update = pendingUpdates.get(candidates)?.get(candidate.candidateId);const current =- update === undefined+ candidate.pendingUpdate === null? undefined- : await Effect.runPromise(repository.getCurrent({ access, rootId: update.rootId }));- if (current !== undefined && current.revision !== update?.expectedRevision) {- throw new Error(`Memory revision ${update?.expectedRevision} is stale.`);+ : await Effect.runPromise(+ repository.getCurrent({ access, rootId: candidate.pendingUpdate.rootId }),+ );+ if (current !== undefined && current.revision !== candidate.pendingUpdate?.expectedRevision) {+ throw new Error(`Memory revision ${candidate.pendingUpdate?.expectedRevision} is stale.`);}const revision = await revisionFor(access,@@ -217,7 +203,6 @@ export async function decideMemoryCandidate(decidedAt,}),);- pendingUpdates.get(candidates)?.delete(candidate.candidateId);if (current !== undefined) {await invalidateDerivedMemory?.({rootId: revision.rootId,@@ -241,6 +226,7 @@ export function createMemoryToolHandlers(scope: AkeruMemoryTargetScope,sensitive: boolean,now: string,+ update?: { readonly rootId: AkeruMemoryRootId; readonly expectedRevision: number },) => {const candidateId = AkeruMemoryCandidateId.make(NodeCrypto.randomUUID());return Effect.runPromise(@@ -258,6 +244,7 @@ export function createMemoryToolHandlers(sensitive,confidence: 1,affectedBotIds: affectedBotIds(access),+ pendingUpdate: update ?? null,status: "pending",createdAt: now,decidedAt: null,@@ -313,13 +300,16 @@ export function createMemoryToolHandlers(: current.sensitive;const fact = stringField(input, "fact");const now = nowIso();- if (scope !== "private" || sensitive) {- const candidate = await createCandidate(fact, scope, sensitive, now);- rememberPendingUpdate(candidates, candidate.candidateId, {+ if (+ current.partition.scope !== "bot-user" ||+ current.sensitive ||+ scope !== "private" ||+ sensitive+ ) {+ return createCandidate(fact, scope, sensitive, now, {rootId,expectedRevision: expected,});- return candidate;}const revision = await revisionFor(access, scope, fact, false, now, current);const saved = await Effect.runPromise(diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.tsindex f41012999..095cd7989 100644--- a/apps/server/src/persistence/Migrations.ts+++ b/apps/server/src/persistence/Migrations.ts@@ -69,6 +69,7 @@ import Migration0053 from "./Migrations/053_BotVoiceEnabled.ts";import Migration0054 from "./Migrations/054_AkeruEntityMemory.ts";import Migration0055 from "./Migrations/055_AkeruMemoryCandidates.ts";import Migration0056 from "./Migrations/056_AkeruBotUsageLedger.ts";+import Migration0057 from "./Migrations/057_AkeruMemoryCandidateUpdates.ts";/*** Migration loader with all migrations defined inline.@@ -137,6 +138,7 @@ export const migrationEntries = [[54, "AkeruEntityMemory", Migration0054],[55, "AkeruMemoryCandidates", Migration0055],[56, "AkeruBotUsageLedger", Migration0056],+ [57, "AkeruMemoryCandidateUpdates", Migration0057],] as const;export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);diff --git a/apps/server/src/persistence/Migrations/057_AkeruMemoryCandidateUpdates.test.ts b/apps/server/src/persistence/Migrations/057_AkeruMemoryCandidateUpdates.test.tsnew file mode 100644index 000000000..b3d5ce987--- /dev/null+++ b/apps/server/src/persistence/Migrations/057_AkeruMemoryCandidateUpdates.test.ts@@ -0,0 +1,58 @@+import { assert, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as SqlClient from "effect/unstable/sql/SqlClient";++import { runMigrations } from "../Migrations.ts";+import * as NodeSqliteClient from "../NodeSqliteClient.ts";++it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()))(+ "057_AkeruMemoryCandidateUpdates",+ (it) => {+ it.effect("stores a pending update target and expected revision", () =>+ Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ yield* runMigrations({ toMigrationInclusive: 55 });+ yield* sql`+ INSERT INTO akeru_memory_candidates (+ candidate_id, tenant_id, initiating_user_id, source_thread_id,+ fact_text, target_scope, sensitive, confidence, affected_bot_ids_json,+ status, created_at+ ) VALUES (+ 'candidate-existing', 'local', 'owner', 'thread-1', 'Existing fact.',+ 'project', 0, 1, '["bot-1"]', 'pending', '2026-08-31T00:00:00.000Z'+ )+ `;+ yield* runMigrations({ toMigrationInclusive: 57 });+ const existing = yield* sql<{ readonly pendingUpdate: string | null }>`+ SELECT pending_update_json AS pendingUpdate+ FROM akeru_memory_candidates+ WHERE candidate_id = 'candidate-existing'+ `;+ assert.deepEqual(existing, [{ pendingUpdate: null }]);++ yield* sql`+ INSERT INTO akeru_memory_candidates (+ candidate_id, tenant_id, initiating_user_id, source_thread_id,+ fact_text, target_scope, sensitive, confidence, affected_bot_ids_json,+ pending_update_json, status, created_at+ ) VALUES (+ 'candidate-update', 'local', 'owner', 'thread-1', 'Use Bun.',+ 'project', 0, 1, '["bot-1"]',+ '{"rootId":"root-1","expectedRevision":3}', 'pending',+ '2026-08-31T00:00:00.000Z'+ )+ `;++ const rows = yield* sql<{+ readonly pendingUpdate: string;+ }>`+ SELECT pending_update_json AS pendingUpdate+ FROM akeru_memory_candidates+ WHERE candidate_id = 'candidate-update'+ `;+ assert.deepEqual(rows, [{ pendingUpdate: '{"rootId":"root-1","expectedRevision":3}' }]);+ }),+ );+ },+);diff --git a/apps/server/src/persistence/Migrations/057_AkeruMemoryCandidateUpdates.ts b/apps/server/src/persistence/Migrations/057_AkeruMemoryCandidateUpdates.tsnew file mode 100644index 000000000..0413e7c9a--- /dev/null+++ b/apps/server/src/persistence/Migrations/057_AkeruMemoryCandidateUpdates.ts@@ -0,0 +1,8 @@+import * as Effect from "effect/Effect";+import * as SqlClient from "effect/unstable/sql/SqlClient";++export default Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;++ yield* sql`ALTER TABLE akeru_memory_candidates ADD COLUMN pending_update_json TEXT`;+});diff --git a/packages/contracts/src/akeruMemory.test.ts b/packages/contracts/src/akeruMemory.test.tsindex b8e424b1e..aa111c8aa 100644--- a/packages/contracts/src/akeruMemory.test.ts+++ b/packages/contracts/src/akeruMemory.test.ts@@ -81,6 +81,7 @@ describe("Akeru memory contracts", () => {decidedAt: null,decidedMemoryRootId: null,});+ assert.isNull(candidate.pendingUpdate);const decision = yield* Schema.decodeUnknownEffect(AkeruMemoryCandidateDecision)({candidateId: candidate.candidateId,decision: "approve",diff --git a/packages/contracts/src/akeruMemory.ts b/packages/contracts/src/akeruMemory.tsindex bd1600bb8..60eadc2c0 100644--- a/packages/contracts/src/akeruMemory.ts+++ b/packages/contracts/src/akeruMemory.ts@@ -62,6 +62,12 @@ export type AkeruMemoryApprovalState = typeof AkeruMemoryApprovalState.Type;export const AkeruMemoryCandidateStatus = Schema.Literals(["pending", "approved", "rejected"]);export type AkeruMemoryCandidateStatus = typeof AkeruMemoryCandidateStatus.Type;+export const AkeruMemoryCandidateUpdate = Schema.Struct({+ rootId: AkeruMemoryRootId,+ expectedRevision: PositiveInt,+});+export type AkeruMemoryCandidateUpdate = typeof AkeruMemoryCandidateUpdate.Type;+export const AkeruMemoryTargetScope = Schema.Literals(["private","bot",@@ -148,6 +154,9 @@ export const AkeruMemoryCandidate = Schema.Struct({sensitive: Schema.Boolean,confidence: AkeruMemoryConfidence,affectedBotIds: Schema.Array(BotId),+ pendingUpdate: Schema.NullOr(AkeruMemoryCandidateUpdate).pipe(+ Schema.withDecodingDefault(Effect.succeed(null)),+ ),status: AkeruMemoryCandidateStatus,createdAt: IsoDateTime,decidedAt: Schema.NullOr(IsoDateTime),