Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

fix(sessions): mark stale active sessions abandoned (carries #1411) (#1453)

Rohit Ghumare656ed6048e7f
diff --git a/.env.example b/.env.example
index 7a3289d7..b43aeca8 100644
--- a/.env.example
+++ b/.env.example
@@ -201,7 +201,15 @@
# III_TELEMETRY_ENABLED=false
# -----------------------------------------------------------------------------
-# 9. Claude Code bridge (opt-in)
+# 9. Session sweep
+# -----------------------------------------------------------------------------
+
+# Hourly backstop that marks stale active sessions as abandoned.
+# AGENTMEMORY_SESSION_SWEEP_ENABLED=false # Disable the hourly sweep
+# AGENTMEMORY_SESSION_SWEEP_STALE_HOURS=24 # Inactivity hours before a session is abandoned
+
+# -----------------------------------------------------------------------------
+# 10. Claude Code bridge (opt-in)
# -----------------------------------------------------------------------------
# CLAUDE_MEMORY_BRIDGE=true # Mirror compressed memories into Claude Code's CLAUDE.md
@@ -209,7 +217,7 @@
# CLAUDE_MEMORY_LINE_BUDGET=200 # Lines of memory CLAUDE.md should hold
# -----------------------------------------------------------------------------
-# 10. Obsidian export (opt-in)
+# 11. Obsidian export (opt-in)
# -----------------------------------------------------------------------------
# OBSIDIAN_AUTO_EXPORT=true # Auto-export memories to an Obsidian vault on every consolidation
diff --git a/plugin/skills/agentmemory-config/REFERENCE.md b/plugin/skills/agentmemory-config/REFERENCE.md
index f7e3b60f..c7fc1d89 100644
--- a/plugin/skills/agentmemory-config/REFERENCE.md
+++ b/plugin/skills/agentmemory-config/REFERENCE.md
@@ -3,7 +3,7 @@
Generated by scanning `src/` for `AGENTMEMORY_*` usage. Do not edit the block below by hand; run `npm run skills:gen` after adding or removing a variable. Internal markers ending in two underscores are excluded.
<!-- AUTOGEN:env START - generated by scripts/skills/generate.ts, do not edit by hand -->
-Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 52 recognized variables:
+Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 54 recognized variables:
- `AGENTMEMORY_AGENT_SCOPE`
- `AGENTMEMORY_ALLOW_AGENT_SDK`
@@ -44,6 +44,8 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e
- `AGENTMEMORY_SDK_CHILD`
- `AGENTMEMORY_SECRET`
- `AGENTMEMORY_SESSION_ID`
+- `AGENTMEMORY_SESSION_SWEEP_ENABLED`
+- `AGENTMEMORY_SESSION_SWEEP_STALE_HOURS`
- `AGENTMEMORY_SLOTS`
- `AGENTMEMORY_STATE_BACKEND`
- `AGENTMEMORY_SUPPRESS_COST_WARNING`
diff --git a/src/config.ts b/src/config.ts
index 7fc5a655..ef0597cc 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -238,6 +238,17 @@ export function getEnvVar(key: string): string | undefined {
return getMergedEnv()[key];
}
+export function isSessionSweepEnabled(): boolean {
+ return getMergedEnv()["AGENTMEMORY_SESSION_SWEEP_ENABLED"] !== "false";
+}
+
+export function getSessionSweepStaleHours(): number {
+ const raw = getMergedEnv()["AGENTMEMORY_SESSION_SWEEP_STALE_HOURS"];
+ if (!raw || !/^\d+$/.test(raw.trim())) return 24;
+ const parsed = parseInt(raw.trim(), 10);
+ return parsed > 0 ? parsed : 24;
+}
+
export function isDropStaleIndexEnabled(): boolean {
return getMergedEnv()["AGENTMEMORY_DROP_STALE_INDEX"] === "true";
}
diff --git a/src/functions/observe.ts b/src/functions/observe.ts
index e2d3c3f3..cd4ea315 100644
--- a/src/functions/observe.ts
+++ b/src/functions/observe.ts
@@ -1,5 +1,5 @@
import { TriggerAction, type IIIClient } from "iii-sdk";
-import type { RawObservation, CompressedObservation, HookPayload, Origin } from "../types.js";
+import type { RawObservation, CompressedObservation, HookPayload, Origin, Session } from "../types.js";
const TOOL_HOOKS = new Set(["pre_tool_use", "post_tool_use", "post_tool_failure"]);
import { KV, STREAM, generateId } from "../state/schema.js";
@@ -168,6 +168,7 @@ export function registerObserveFunction(
agentId?: string;
observationCount?: number;
firstPrompt?: string;
+ status?: Session["status"];
}>(KV.sessions, payload.sessionId);
const inheritedAgentId = existingSession
? existingSession.agentId
@@ -251,7 +252,7 @@ export function registerObserveFunction(
const session = existingSession;
if (session) {
- const updates: Array<{ type: "set"; path: string; value: unknown }> = [
+ const updates: Array<{ type: "set" | "remove"; path: string; value?: unknown }> = [
{ type: "set", path: "updatedAt", value: new Date().toISOString() },
{
type: "set",
@@ -259,6 +260,10 @@ export function registerObserveFunction(
value: (session.observationCount || 0) + 1,
},
];
+ if (session.status === "abandoned") {
+ updates.push({ type: "set", path: "status", value: "active" });
+ updates.push({ type: "remove", path: "endedAt" });
+ }
if (!session.firstPrompt && typeof raw.userPrompt === "string") {
const trimmed = raw.userPrompt.replace(/\s+/g, " ").trim();
if (trimmed.length > 0) {
diff --git a/src/functions/session-sweep.ts b/src/functions/session-sweep.ts
new file mode 100644
index 00000000..43da742b
--- /dev/null
+++ b/src/functions/session-sweep.ts
@@ -0,0 +1,92 @@
+import type { IIIClient } from "iii-sdk";
+import type { StateKV } from "../state/kv.js";
+import { KV } from "../state/schema.js";
+import { withKeyedLock } from "../state/keyed-mutex.js";
+import type { Session } from "../types.js";
+import { logger } from "../logger.js";
+import { safeAudit } from "./audit.js";
+import {
+ isSessionSweepEnabled,
+ getSessionSweepStaleHours,
+} from "../config.js";
+
+const HOUR_MS = 60 * 60 * 1000;
+
+export interface SessionSweepResult {
+ success: boolean;
+ scanned: number;
+ abandoned: number;
+ failed: number;
+ error?: string;
+}
+
+function isStaleActive(session: Session | null, cutoff: number): session is Session {
+ if (!session || session.status !== "active") return false;
+ const freshness = session.updatedAt ?? session.startedAt;
+ if (!freshness) return false;
+ const ts = new Date(freshness).getTime();
+ return Number.isFinite(ts) && ts < cutoff;
+}
+
+export function registerSessionSweepFunction(sdk: IIIClient, kv: StateKV): void {
+ sdk.registerFunction(
+ "mem::session-sweep",
+ async (): Promise<SessionSweepResult> => {
+ if (!isSessionSweepEnabled()) {
+ return { success: false, scanned: 0, abandoned: 0, failed: 0, error: "session sweep disabled" };
+ }
+ const cutoff = Date.now() - getSessionSweepStaleHours() * HOUR_MS;
+ let sessions: Session[];
+ try {
+ sessions = await kv.list<Session>(KV.sessions);
+ } catch (err) {
+ const error = err instanceof Error ? err.message : String(err);
+ logger.error("Session sweep scan failed", { error });
+ return { success: false, scanned: 0, abandoned: 0, failed: 0, error };
+ }
+
+ const abandonedIds: string[] = [];
+ let failed = 0;
+ for (const candidate of sessions) {
+ if (!isStaleActive(candidate, cutoff)) continue;
+ try {
+ const marked = await withKeyedLock(`obs:${candidate.id}`, async () => {
+ const current = await kv.get<Session>(KV.sessions, candidate.id);
+ if (!isStaleActive(current, cutoff)) return false;
+ await kv.update(KV.sessions, candidate.id, [
+ { type: "set", path: "status", value: "abandoned" },
+ { type: "set", path: "endedAt", value: new Date().toISOString() },
+ ]);
+ return true;
+ });
+ if (marked) abandonedIds.push(candidate.id);
+ } catch (err) {
+ failed++;
+ logger.warn("Session sweep update failed", {
+ sessionId: candidate.id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+
+ if (abandonedIds.length > 0) {
+ await safeAudit(kv, "session_sweep", "mem::session-sweep", abandonedIds, {
+ abandoned: abandonedIds.length,
+ staleHours: getSessionSweepStaleHours(),
+ });
+ logger.info("Session sweep complete", {
+ scanned: sessions.length,
+ abandoned: abandonedIds.length,
+ failed,
+ });
+ }
+ return {
+ success: failed === 0,
+ scanned: sessions.length,
+ abandoned: abandonedIds.length,
+ failed,
+ ...(failed > 0 ? { error: `${failed} session update(s) failed` } : {}),
+ };
+ },
+ );
+}
diff --git a/src/index.ts b/src/index.ts
index 1025bf9d..7134677d 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -16,6 +16,8 @@ import {
isDropStaleIndexEnabled,
getAuditRetentionMonths,
getStateBackend,
+ isSessionSweepEnabled,
+ getSessionSweepStaleHours,
} from "./config.js";
import {
createProvider,
@@ -63,6 +65,7 @@ import { registerRelationsFunction } from "./functions/relations.js";
import { registerTimelineFunction } from "./functions/timeline.js";
import { registerSmartSearchFunction } from "./functions/smart-search.js";
import { registerRecentSearchesSweepFunction } from "./functions/recent-searches-sweep.js";
+import { registerSessionSweepFunction } from "./functions/session-sweep.js";
import { registerProfileFunction } from "./functions/profile.js";
import { registerAutoForgetFunction } from "./functions/auto-forget.js";
import { registerExportImportFunction } from "./functions/export-import.js";
@@ -280,6 +283,7 @@ async function main() {
registerPatternsFunction(sdk, kv);
registerRememberFunction(sdk, kv);
registerEvictFunction(sdk, kv);
+ registerSessionSweepFunction(sdk, kv);
registerRelationsFunction(sdk, kv);
registerTimelineFunction(sdk, kv);
@@ -621,6 +625,18 @@ async function main() {
void seedViewerStreamTracker(sdk, { unorderedListing: kv.backend === "redis" }).catch(() => {});
+ if (isSessionSweepEnabled()) {
+ const sessionSweepTimer = setInterval(async () => {
+ try {
+ await sdk.trigger({ function_id: "mem::session-sweep", payload: {} });
+ } catch (err) {
+ bootLog(`Session sweep failed: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }, 60 * 60 * 1000);
+ sessionSweepTimer.unref();
+ bootLog(`Session sweep: enabled (hourly, stale after ${getSessionSweepStaleHours()}h)`);
+ }
+
if (isConsolidationEnabled()) {
const consolidationTimer = setInterval(async () => {
try {
diff --git a/src/types.ts b/src/types.ts
index a8674e2f..727a6c23 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -3,6 +3,7 @@ export interface Session {
project: string;
cwd: string;
startedAt: string;
+ updatedAt?: string;
endedAt?: string;
status: "active" | "completed" | "abandoned";
observationCount: number;
@@ -655,7 +656,8 @@ export interface AuditEntry {
| "slot_create"
| "slot_delete"
| "slot_reflect"
- | "audit_migrate";
+ | "audit_migrate"
+ | "session_sweep";
userId?: string;
functionId: string;
targetIds: string[];
diff --git a/src/viewer/index.html b/src/viewer/index.html
index 7a2e0719..50cbf48d 100644
--- a/src/viewer/index.html
+++ b/src/viewer/index.html
@@ -6714,7 +6714,8 @@
skill_extract: 'Extracted a skill', core_add: 'Added core memory', core_remove: 'Removed core memory',
auto_page: 'Paged memory out', vision_embed: 'Embedded an image',
slot_append: 'Appended to a slot', slot_replace: 'Replaced a slot', slot_create: 'Created a slot',
- slot_delete: 'Deleted a slot', slot_reflect: 'Reflected into a slot'
+ slot_delete: 'Deleted a slot', slot_reflect: 'Reflected into a slot',
+ session_sweep: 'Marked stale sessions abandoned'
};
function auditVerb(op) {
diff --git a/test/observe-reactivate-abandoned.test.ts b/test/observe-reactivate-abandoned.test.ts
new file mode 100644
index 00000000..0416b6b8
--- /dev/null
+++ b/test/observe-reactivate-abandoned.test.ts
@@ -0,0 +1,125 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+function mockKV() {
+ const store = new Map<string, Map<string, unknown>>();
+ return {
+ store,
+ get: async <T>(scope: string, key: string): Promise<T | null> =>
+ (store.get(scope)?.get(key) as T) ?? null,
+ set: async <T>(scope: string, key: string, data: T): Promise<T> => {
+ if (!store.has(scope)) store.set(scope, new Map());
+ store.get(scope)!.set(key, data);
+ return data;
+ },
+ update: async (
+ scope: string,
+ key: string,
+ updates: Array<{ type: string; path: string; value?: unknown }>,
+ ): Promise<void> => {
+ const m = store.get(scope);
+ if (!m) return;
+ const v = (m.get(key) as Record<string, unknown>) ?? {};
+ for (const u of updates) {
+ if (u.type === "remove") delete v[u.path];
+ else v[u.path] = u.value;
+ }
+ m.set(key, v);
+ },
+ delete: async (scope: string, key: string): Promise<void> => {
+ store.get(scope)?.delete(key);
+ },
+ list: async <T>(scope: string): Promise<T[]> => {
+ const m = store.get(scope);
+ return m ? (Array.from(m.values()) as T[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const fns = new Map<string, Function>();
+ return {
+ fns,
+ registerFunction: (idOrOpts: string | { id: string }, fn: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ fns.set(id, fn);
+ },
+ registerTrigger: () => {},
+ trigger: async (
+ idOrInput: string | { function_id: string; payload: unknown; action?: unknown },
+ data?: unknown,
+ ) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
+ const fn = fns.get(id);
+ if (fn) return fn(payload);
+ return null;
+ },
+ };
+}
+
+function seedSession(store: Map<string, Map<string, unknown>>, id: string, status: string) {
+ if (!store.has("mem:sessions")) store.set("mem:sessions", new Map());
+ store.get("mem:sessions")!.set(id, {
+ id,
+ project: "/home/user/myrepo",
+ cwd: "/home/user/myrepo",
+ startedAt: new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString(),
+ status,
+ observationCount: 3,
+ ...(status === "abandoned" ? { endedAt: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString() } : {}),
+ });
+}
+
+describe("observe reactivates abandoned sessions", () => {
+ beforeEach(() => {
+ vi.resetModules();
+ });
+
+ it("sets an abandoned session back to active and clears endedAt on new activity", async () => {
+ const { registerObserveFunction } = await import("../src/functions/observe.js");
+ const sdk = mockSdk();
+ const kv = mockKV();
+ seedSession(kv.store, "ses_reactivated", "abandoned");
+ registerObserveFunction(sdk as never, kv as never);
+
+ await sdk.trigger("mem::observe", {
+ sessionId: "ses_reactivated",
+ project: "/home/user/myrepo",
+ cwd: "/home/user/myrepo",
+ hookType: "post_tool_use",
+ timestamp: new Date().toISOString(),
+ data: { tool_name: "Read", tool_input: { file_path: "x.ts" } },
+ });
+
+ const session = kv.store.get("mem:sessions")!.get("ses_reactivated") as Record<string, unknown>;
+ expect(session.status).toBe("active");
+ expect("endedAt" in session).toBe(false);
+ expect(session.observationCount).toBe(4);
+ });
+
+ it("does not touch the status of an active session", async () => {
+ const { registerObserveFunction } = await import("../src/functions/observe.js");
+ const sdk = mockSdk();
+ const kv = mockKV();
+ seedSession(kv.store, "ses_active", "active");
+ registerObserveFunction(sdk as never, kv as never);
+
+ await sdk.trigger("mem::observe", {
+ sessionId: "ses_active",
+ project: "/home/user/myrepo",
+ cwd: "/home/user/myrepo",
+ hookType: "post_tool_use",
+ timestamp: new Date().toISOString(),
+ data: { tool_name: "Read", tool_input: { file_path: "y.ts" } },
+ });
+
+ const session = kv.store.get("mem:sessions")!.get("ses_active") as Record<string, unknown>;
+ expect(session.status).toBe("active");
+ expect(session.endedAt).toBeUndefined();
+ expect(session.observationCount).toBe(4);
+ });
+});
diff --git a/test/session-sweep.test.ts b/test/session-sweep.test.ts
new file mode 100644
index 00000000..a155d7e1
--- /dev/null
+++ b/test/session-sweep.test.ts
@@ -0,0 +1,234 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+import { registerSessionSweepFunction } from "../src/functions/session-sweep.js";
+import type { AuditEntry, Session } from "../src/types.js";
+import { auditMonthOf } from "../src/functions/audit.js";
+import { withKeyedLock } from "../src/state/keyed-mutex.js";
+import { KV } from "../src/state/schema.js";
+
+function mockKV() {
+ const store = new Map<string, Map<string, unknown>>();
+ return {
+ store,
+ get: async <T>(scope: string, key: string): Promise<T | null> => {
+ return (store.get(scope)?.get(key) as T) ?? null;
+ },
+ set: async <T>(scope: string, key: string, data: T): Promise<T> => {
+ if (!store.has(scope)) store.set(scope, new Map());
+ store.get(scope)!.set(key, data);
+ return data;
+ },
+ update: async (
+ scope: string,
+ key: string,
+ ops: Array<{ type: "set"; path: string; value: unknown }>,
+ ): Promise<void> => {
+ const bucket = store.get(scope)?.get(key) as Record<string, unknown> | undefined;
+ if (!bucket) return;
+ for (const op of ops) bucket[op.path] = op.value;
+ },
+ delete: async (scope: string, key: string): Promise<void> => {
+ store.get(scope)?.delete(key);
+ },
+ list: async <T>(scope: string): Promise<T[]> => {
+ const entries = store.get(scope);
+ return entries ? (Array.from(entries.values()) as T[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const functions = new Map<string, Function>();
+ const triggers: Array<{ function_id: string; payload: unknown }> = [];
+ return {
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
+ },
+ registerTrigger: () => {},
+ trigger: async (input: { function_id: string; payload: unknown }) => {
+ triggers.push(input);
+ const fn = functions.get(input.function_id);
+ if (!fn) return undefined;
+ return fn(input.payload);
+ },
+ triggers,
+ };
+}
+
+function session(partial: Partial<Session>): Session {
+ return {
+ id: "s1",
+ project: "/proj",
+ cwd: "/proj",
+ startedAt: new Date().toISOString(),
+ status: "active",
+ observationCount: 0,
+ ...partial,
+ };
+}
+
+const nowMs = Date.now();
+const H = 60 * 60 * 1000;
+
+describe("mem::session-sweep", () => {
+ let kv: ReturnType<typeof mockKV>;
+ let sdk: ReturnType<typeof mockSdk>;
+
+ beforeEach(() => {
+ vi.unstubAllEnvs();
+ kv = mockKV();
+ sdk = mockSdk();
+ registerSessionSweepFunction(sdk as never, kv as never);
+ });
+
+ it("marks stale active sessions as abandoned with endedAt", async () => {
+ kv.set(KV.sessions, "s-old", session({ id: "s-old", updatedAt: new Date(nowMs - 30 * H).toISOString() }));
+ const sweep = await (sdk as any).trigger({ function_id: "mem::session-sweep", payload: {} });
+ const updated = await kv.get<Session>(KV.sessions, "s-old");
+ expect(updated!.status).toBe("abandoned");
+ expect(updated!.endedAt).toBeTruthy();
+ expect(sweep.abandoned).toBe(1);
+ expect(sweep.success).toBe(true);
+ });
+
+ it("falls back to startedAt when the session has no heartbeat", async () => {
+ kv.set(KV.sessions, "s-nobeat", session({ id: "s-nobeat", startedAt: new Date(nowMs - 48 * H).toISOString() }));
+ const sweep = await (sdk as any).trigger({ function_id: "mem::session-sweep", payload: {} });
+ const updated = await kv.get<Session>(KV.sessions, "s-nobeat");
+ expect(updated!.status).toBe("abandoned");
+ expect(sweep.abandoned).toBe(1);
+ });
+
+ it("leaves fresh active sessions untouched", async () => {
+ kv.set(KV.sessions, "s-fresh", session({ id: "s-fresh", updatedAt: new Date(nowMs - 2 * H).toISOString() }));
+ const sweep = await (sdk as any).trigger({ function_id: "mem::session-sweep", payload: {} });
+ const updated = await kv.get<Session>(KV.sessions, "s-fresh");
+ expect(updated!.status).toBe("active");
+ expect(sweep.abandoned).toBe(0);
+ });
+
+ it("leaves completed sessions untouched", async () => {
+ kv.set(KV.sessions, "s-done", session({ id: "s-done", status: "completed", updatedAt: new Date(nowMs - 48 * H).toISOString() }));
+ const sweep = await (sdk as any).trigger({ function_id: "mem::session-sweep", payload: {} });
+ const updated = await kv.get<Session>(KV.sessions, "s-done");
+ expect(updated!.status).toBe("completed");
+ expect(sweep.abandoned).toBe(0);
+ });
+
+ it("reports failure when the session scan fails", async () => {
+ (kv as any).list = async () => {
+ throw new Error("state store down");
+ };
+ const sweep = await (sdk as any).trigger({ function_id: "mem::session-sweep", payload: {} });
+ expect(sweep.success).toBe(false);
+ expect(sweep.error).toContain("state store down");
+ });
+
+ it("reports failure when the sweep is disabled", async () => {
+ vi.stubEnv("AGENTMEMORY_SESSION_SWEEP_ENABLED", "false");
+ const sweep = await (sdk as any).trigger({ function_id: "mem::session-sweep", payload: {} });
+ expect(sweep.success).toBe(false);
+ expect(sweep.abandoned).toBe(0);
+ });
+
+ it("respects AGENTMEMORY_SESSION_SWEEP_STALE_HOURS override", async () => {
+ vi.stubEnv("AGENTMEMORY_SESSION_SWEEP_STALE_HOURS", "48");
+ kv.set(KV.sessions, "s-30h", session({ id: "s-30h", updatedAt: new Date(nowMs - 30 * H).toISOString() }));
+ const sweep = await (sdk as any).trigger({ function_id: "mem::session-sweep", payload: {} });
+ const updated = await kv.get<Session>(KV.sessions, "s-30h");
+ expect(updated!.status).toBe("active");
+ expect(sweep.abandoned).toBe(0);
+ });
+
+ it("rejects non-plain-integer stale-hour values", async () => {
+ vi.stubEnv("AGENTMEMORY_SESSION_SWEEP_STALE_HOURS", "1e2");
+ kv.set(KV.sessions, "s-2h", session({ id: "s-2h", updatedAt: new Date(nowMs - 2 * H).toISOString() }));
+ const sweep = await (sdk as any).trigger({ function_id: "mem::session-sweep", payload: {} });
+ const updated = await kv.get<Session>(KV.sessions, "s-2h");
+ expect(updated!.status).toBe("active");
+ expect(sweep.abandoned).toBe(0);
+ });
+
+ it("leaves a session alone when activity lands between the scan and the update", async () => {
+ kv.set(KV.sessions, "s-race", session({ id: "s-race", updatedAt: new Date(nowMs - 30 * H).toISOString() }));
+ const staleSnapshot = [{ ...(await kv.get<Session>(KV.sessions, "s-race"))! }];
+ (kv as any).list = async () => {
+ await kv.update(KV.sessions, "s-race", [
+ { type: "set", path: "updatedAt", value: new Date().toISOString() },
+ ]);
+ return staleSnapshot;
+ };
+ const sweep = await (sdk as any).trigger({ function_id: "mem::session-sweep", payload: {} });
+ const updated = await kv.get<Session>(KV.sessions, "s-race");
+ expect(updated!.status).toBe("active");
+ expect(updated!.endedAt).toBeUndefined();
+ expect(sweep.abandoned).toBe(0);
+ });
+
+ it("waits for the obs session lock before marking a session abandoned", async () => {
+ kv.set(KV.sessions, "s-locked", session({ id: "s-locked", updatedAt: new Date(nowMs - 30 * H).toISOString() }));
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const holder = withKeyedLock("obs:s-locked", async () => {
+ await gate;
+ await kv.update(KV.sessions, "s-locked", [
+ { type: "set", path: "updatedAt", value: new Date().toISOString() },
+ ]);
+ });
+ const sweepPromise = (sdk as any).trigger({ function_id: "mem::session-sweep", payload: {} });
+ await new Promise((r) => setTimeout(r, 10));
+ expect((await kv.get<Session>(KV.sessions, "s-locked"))!.status).toBe("active");
+ release();
+ await holder;
+ const sweep = await sweepPromise;
+ expect((await kv.get<Session>(KV.sessions, "s-locked"))!.status).toBe("active");
+ expect(sweep.abandoned).toBe(0);
+ });
+
+ it("counts failed updates and reports a partial sweep", async () => {
+ kv.set(KV.sessions, "s-ok", session({ id: "s-ok", updatedAt: new Date(nowMs - 30 * H).toISOString() }));
+ kv.set(KV.sessions, "s-bad", session({ id: "s-bad", updatedAt: new Date(nowMs - 30 * H).toISOString() }));
+ const realUpdate = kv.update;
+ (kv as any).update = async (scope: string, key: string, ops: any) => {
+ if (key === "s-bad") throw new Error("write refused");
+ return realUpdate(scope, key, ops);
+ };
+ const sweep = await (sdk as any).trigger({ function_id: "mem::session-sweep", payload: {} });
+ expect(sweep.success).toBe(false);
+ expect(sweep.abandoned).toBe(1);
+ expect(sweep.failed).toBe(1);
+ expect((await kv.get<Session>(KV.sessions, "s-ok"))!.status).toBe("abandoned");
+ expect((await kv.get<Session>(KV.sessions, "s-bad"))!.status).toBe("active");
+ });
+
+ it("writes one audit entry into the current month scope listing the abandoned sessions", async () => {
+ kv.set(KV.sessions, "s-a", session({ id: "s-a", updatedAt: new Date(nowMs - 30 * H).toISOString() }));
+ kv.set(KV.sessions, "s-b", session({ id: "s-b", startedAt: new Date(nowMs - 40 * H).toISOString() }));
+ kv.set(KV.sessions, "s-live", session({ id: "s-live", updatedAt: new Date().toISOString() }));
+ await (sdk as any).trigger({ function_id: "mem::session-sweep", payload: {} });
+ const month = auditMonthOf(new Date().toISOString());
+ const entries = await kv.list<AuditEntry>(KV.auditMonth(month));
+ expect(entries).toHaveLength(1);
+ expect(entries[0].operation).toBe("session_sweep");
+ expect([...entries[0].targetIds].sort()).toEqual(["s-a", "s-b"]);
+ const index = await kv.get<{ months: string[] }>(KV.auditMonths, "index");
+ expect(index!.months).toContain(month);
+ });
+
+ it("writes no audit entry and deletes nothing when no session is stale", async () => {
+ kv.set(KV.sessions, "s-live", session({ id: "s-live", updatedAt: new Date().toISOString() }));
+ kv.set(KV.sessions, "s-done", session({ id: "s-done", status: "abandoned", updatedAt: new Date(nowMs - 90 * H).toISOString() }));
+ await (sdk as any).trigger({ function_id: "mem::session-sweep", payload: {} });
+ const month = auditMonthOf(new Date().toISOString());
+ expect(await kv.list(KV.auditMonth(month))).toHaveLength(0);
+ expect(kv.store.get(KV.sessions)!.size).toBe(2);
+ expect(sdk.triggers.map((t) => t.function_id)).toEqual(["mem::session-sweep"]);
+ });
+});