Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
fix(agent): retain agent memory content with Context Views
white27adbd6db0a9
diff --git a/apps/node-services/src/agent/AGENTS.md b/apps/node-services/src/agent/AGENTS.mdindex fc1cc743..35dc58e2 100644--- a/apps/node-services/src/agent/AGENTS.md+++ b/apps/node-services/src/agent/AGENTS.md@@ -93,6 +93,10 @@ take precedence.Agent Service stores no Skill bytes. TeamHub configuration still selectsversions; cached bytes confer no authority. Do not reintroduce Run Tokens,Run grants, Run-scoped resource snapshots, staging, or checkpoint hooks.+- Agent Memory files and the recall summary come from one published document+ read at Context activation. The read-only files are inline Context View+ content, retained with the View rather than backed by a shared directory.+ Before-run synchronization neither rereads Agent Memory nor walks those files.- Local Runner Runtimes read collaboration resources through thestandalone TeamHub CLI, authorized by current Agent identity on each request.Tenant workers, resource roots, file deltas, topology registration anddiff --git a/apps/node-services/src/agent/agent-features/agent-memory/projection.ts b/apps/node-services/src/agent/agent-features/agent-memory/projection.tsindex 5488ffa3..12655c0f 100644--- a/apps/node-services/src/agent/agent-features/agent-memory/projection.ts+++ b/apps/node-services/src/agent/agent-features/agent-memory/projection.ts@@ -1,15 +1,6 @@-import { createHash, randomUUID } from "node:crypto";-import { lstat, mkdir, readdir, rename, rm, writeFile } from "node:fs/promises";-import path from "node:path";-import type {- AgentContextHost,- RuntimeViewMapping,-} from "../../executor/workspace.js";+import type { RuntimeViewMapping } from "../../executor/workspace.js";import type { MemoryClient } from "./client.js";-// Generation files live on shared storage, so writes overlap to hide round trips.-const WRITE_CONCURRENCY = 8;-export interface AgentMemoryProjection {/** Both are absent before the first publication. */prepare(@@ -20,7 +11,6 @@ export interface AgentMemoryProjection {export function createMemoryProjection(client: MemoryClient,- host: Pick<AgentContextHost, "ensureAgentRoots">,): AgentMemoryProjection {return {async prepare(agentId, signal) {@@ -36,48 +26,11 @@ export function createMemoryProjection(throw new Error("Invalid memory session key");files[`session_summaries/${key}.md`] = session.summary;}- const revision = createHash("sha256")- .update(JSON.stringify(files))- .digest("hex");- const roots = await host.ensureAgentRoots(agentId);- const generations = path.join(- roots.agentRoot,- "agent-memory",- "generations",- );- const target = path.join(generations, revision);- // A generation is only created by renaming a complete draft and only- // deleted after renaming it away, so an existing directory is complete.- if (!(await isGenerationDirectory(target))) {- const draft = path.join(generations, `.draft-${randomUUID()}`);- await mkdir(path.join(draft, "session_summaries"), {- recursive: true,- mode: 0o700,- });- try {- await writeGenerationFiles(draft, files);- try {- await rename(draft, target);- } catch (error) {- if (- !error ||- typeof error !== "object" ||- !("code" in error) ||- !["EEXIST", "ENOTEMPTY"].includes(String(error.code))- )- throw error;- }- } finally {- await rm(draft, { recursive: true, force: true });- }- // Cleanup never fails an activation; the next publication retries it.- await pruneGenerations(generations, revision).catch(() => undefined);- }signal.throwIfAborted();return {mapping: {kind: "memory",- sourcePath: target,+ inlineFiles: Object.freeze(files),targetPath: "/workspace/agent-memory",access: "read_only",},@@ -86,74 +39,3 @@ export function createMemoryProjection(},};}--// A Context copies a generation when it maps it, so only the current one and-// the newest other, which a concurrent activation may still be copying, stay.-// A generation is renamed to trash before deletion, so a deletion cut short-// never leaves a partial directory under a revision name.-const pruneGenerations = async (- generations: string,- current: string,-): Promise<void> => {- const entries = (await readdir(generations, { withFileTypes: true })).filter(- (entry) => entry.isDirectory(),- );- const older = await Promise.all(- entries- .filter((entry) => /^[a-f0-9]{64}$/u.test(entry.name))- .filter((entry) => entry.name !== current)- .map(async ({ name }) => ({- name,- modifiedMs: (await lstat(path.join(generations, name))).mtimeMs,- })),- );- older.sort((left, right) => right.modifiedMs - left.modifiedMs);- const trash = entries- .filter((entry) => entry.name.startsWith(".trash-"))- .map((entry) => entry.name);- for (const { name } of older.slice(1)) {- const renamed = `.trash-${randomUUID()}`;- await rename(path.join(generations, name), path.join(generations, renamed));- trash.push(renamed);- }- for (const name of trash)- await rm(path.join(generations, name), { recursive: true, force: true });-};--const isGenerationDirectory = async (target: string): Promise<boolean> => {- try {- const metadata = await lstat(target);- return metadata.isDirectory() && !metadata.isSymbolicLink();- } catch (error) {- if (error instanceof Error && "code" in error && error.code === "ENOENT")- return false;- throw error;- }-};--// Waits for every started write before returning, so the caller can remove the draft safely.-const writeGenerationFiles = async (- draft: string,- files: Readonly<Record<string, string>>,-): Promise<void> => {- const entries = Object.entries(files);- let nextIndex = 0;- let failed = false;- const worker = async (): Promise<void> => {- while (!failed && nextIndex < entries.length) {- const [name, content] = entries[nextIndex++]!;- try {- await writeFile(path.join(draft, name), content, { mode: 0o400 });- } catch (error) {- failed = true;- throw error;- }- }- };- const results = await Promise.allSettled(- Array.from({ length: Math.min(WRITE_CONCURRENCY, entries.length) }, worker),- );- for (const result of results) {- if (result.status === "rejected") throw result.reason;- }-};diff --git a/apps/node-services/src/agent/agent-features/agent-memory/services.ts b/apps/node-services/src/agent/agent-features/agent-memory/services.tsindex 9f8b3cd7..8d908762 100644--- a/apps/node-services/src/agent/agent-features/agent-memory/services.ts+++ b/apps/node-services/src/agent/agent-features/agent-memory/services.ts@@ -1,4 +1,3 @@-import type { AgentContextHost } from "../../executor/workspace.js";import type { ModelCall } from "../../../runtime-model-call.js";import type { AgentLogger } from "../../observability/agent-log.js";import type { TeamHubRuntimeStateClient } from "../../executor/teamhub-runtime-state-client.js";@@ -19,7 +18,6 @@ export interface AgentMemoryMaintenance {*/export interface AgentMemoryServicesOptions {readonly memory: MemoryClient;- readonly contextHost: Pick<AgentContextHost, "ensureAgentRoots">;readonly runtimeState: TeamHubRuntimeStateClient;readonly logger: Pick<AgentLogger, "log">;/**@@ -60,10 +58,7 @@ export interface AgentMemoryServices {export const createAgentMemoryServices = (options: AgentMemoryServicesOptions,): AgentMemoryServices => {- const projection = createMemoryProjection(- options.memory,- options.contextHost,- );+ const projection = createMemoryProjection(options.memory);let coordinator: AgentMemoryCoordinator | undefined;let started = false;let closed = false;diff --git a/apps/node-services/src/agent/executor/application.ts b/apps/node-services/src/agent/executor/application.tsindex d8ed66ff..2cacc504 100644--- a/apps/node-services/src/agent/executor/application.ts+++ b/apps/node-services/src/agent/executor/application.ts@@ -466,7 +466,6 @@ export const createAgentManagerApplication = (memoryClient && stateBackend.kind === "teamhub"? createAgentMemoryServices({memory: memoryClient,- contextHost: options.contextHost,runtimeState: stateBackend.client,logger: createAgentLogger({ component: "agent-memory" }),...(options.agentMemoryMaintenancediff --git a/apps/node-services/src/agent/executor/workspace.ts b/apps/node-services/src/agent/executor/workspace.tsindex b1f91a43..a8fec4ef 100644--- a/apps/node-services/src/agent/executor/workspace.ts+++ b/apps/node-services/src/agent/executor/workspace.ts@@ -32,14 +32,27 @@ export interface AgentContextRoots {export type RuntimeViewMappingKind = "inbox_view" | "memory" | "playground";-export interface RuntimeViewMapping {+interface RuntimeViewMount {readonly kind: RuntimeViewMappingKind;- readonly sourcePath: string;- readonly fileLinkRootPaths?: readonly string[];readonly targetPath: string;readonly access: "read_only" | "read_write";}+interface DirectoryViewMapping extends RuntimeViewMount {+ readonly sourcePath: string;+ readonly fileLinkRootPaths?: readonly string[];+ readonly inlineFiles?: never;+}++interface InlineViewMapping extends RuntimeViewMount {+ readonly kind: "memory";+ readonly access: "read_only";+ readonly inlineFiles: Readonly<Record<string, string>>;+ readonly sourcePath?: never;+}++export type RuntimeViewMapping = DirectoryViewMapping | InlineViewMapping;+export interface RuntimeViewPlan {readonly ref: ExecutionContextRef;readonly contextKey: ExecutionContextKey;@@ -50,8 +63,8 @@ export interface RuntimeViewPlan {}export interface StagedDocumentProjection {- readonly mapping: RuntimeViewMapping;- activate(): Promise<RuntimeViewMapping>;+ readonly mapping: DirectoryViewMapping;+ activate(): Promise<DirectoryViewMapping>;discard(): Promise<void>;release(): Promise<void>;}@@ -197,7 +210,7 @@ class FileSystemAgentContextHost implements AgentContextHost {stateRoot,path.join(stateRoot, currentDocument.documentId),);- const mapping: RuntimeViewMapping = Object.freeze({+ const mapping: DirectoryViewMapping = Object.freeze({kind: "inbox_view",sourcePath: scopeRoot,targetPath: path.posix.join(@@ -207,7 +220,7 @@ class FileSystemAgentContextHost implements AgentContextHost {access: "read_only",});let released = false;- const activate = (): Promise<RuntimeViewMapping> =>+ const activate = (): Promise<DirectoryViewMapping> =>this.withTail(this.agentTails, input.agentId, async () => {if (released) throw new Error("Document projection stage is released");await atomicWriteFile(diff --git a/apps/node-services/src/agent/runner-gateway/context-view-content.ts b/apps/node-services/src/agent/runner-gateway/context-view-content.tsindex 88055eb5..18e3c712 100644--- a/apps/node-services/src/agent/runner-gateway/context-view-content.ts+++ b/apps/node-services/src/agent/runner-gateway/context-view-content.ts@@ -75,8 +75,8 @@ export interface ContextViewSnapshotInput {* Serves Context View content to the Computer that runs the Context. A View is* named by the SHA-256 of its manifest bytes; the Computer fetches the manifest* and only the files it lacks, and verifies every file it writes. Files are- * read from their source when requested, so a source that changed since the- * snapshot is refused and the next snapshot names the new content.+ * read from their source when requested, so a directory source that changed+ * since the snapshot is refused. Inline memory stays with the published View.*/export interface ContextViewContent {snapshot(input: ContextViewSnapshotInput): Promise<ContextViewSnapshot>;@@ -90,11 +90,18 @@ export interface ContextViewContent {): Promise<Response>;}-interface PublishedFile {+interface DirectoryPublishedFile {readonly sourcePath: string;readonly sizeBytes: number;}+interface InlinePublishedFile {+ readonly text: string;+ readonly sizeBytes: number;+}++type PublishedFile = DirectoryPublishedFile | InlinePublishedFile;+interface PublishedView {readonly manifest: Uint8Array;readonly files: ReadonlyMap<string, PublishedFile>;@@ -214,21 +221,36 @@ export function createContextViewContent(options: {: [],);const mappingFiles: ContextViewFile[] = [];- for await (const source of walkDirectory({- root: await realDirectory(mapping.sourcePath),- relativeRoot: "",- skip: nested,- fileLinkRoots: mapping.fileLinkRootPaths- ? await Promise.all(- mapping.fileLinkRootPaths.map((root) => realpath(root)),- )- : undefined,- signal: input.signal,- })) {- const digest = await digestFile(- source.sourcePath,- source.relativePath,- );+ const sources = mapping.inlineFiles+ ? Object.entries(mapping.inlineFiles)+ .filter(([relativePath]) => !isNestedTarget(relativePath, nested))+ .map(([relativePath, text]) => ({ relativePath, text }))+ : walkDirectory({+ root: await realDirectory(mapping.sourcePath),+ relativeRoot: "",+ skip: nested,+ fileLinkRoots: mapping.fileLinkRootPaths+ ? await Promise.all(+ mapping.fileLinkRootPaths.map((root) => realpath(root)),+ )+ : undefined,+ signal: input.signal,+ });+ for await (const source of sources) {+ input.signal.throwIfAborted();+ const inline = "text" in source;+ const digest = inline+ ? {+ sha256: sha256Hex(source.text),+ size: Buffer.byteLength(source.text),+ executable: false,+ }+ : await digestFile(source.sourcePath, source.relativePath);+ const sizeBytes = Number(digest.size);+ if (sizeBytes > MAX_FILE_BYTES)+ throw new Error(+ `Context View file is invalid: ${source.relativePath}`,+ );const joined = path.posix.join(targetPath, source.relativePath);const existing = claimed.get(joined);if (existing !== undefined) {@@ -238,23 +260,28 @@ export function createContextViewContent(options: {}claimed.set(joined, digest.sha256);budget.fileCount += 1;- budget.totalBytes += Number(digest.size);+ budget.totalBytes += sizeBytes;if (budget.fileCount > MAX_FILE_COUNT ||budget.totalBytes > MAX_TOTAL_BYTES)throw new Error("Context View exceeds its file limits");- files.set(digest.sha256, {- sourcePath: source.sourcePath,- sizeBytes: Number(digest.size),- });+ const existingFile = files.get(digest.sha256);+ if (inline || !existingFile || !("text" in existingFile)) {+ files.set(+ digest.sha256,+ inline+ ? { text: source.text, sizeBytes }+ : { sourcePath: source.sourcePath, sizeBytes },+ );+ }mappingFiles.push({relative_path: source.relativePath,media_type:mediaTypeForExtension(path.posix.extname(source.relativePath).slice(1),) ?? "application/octet-stream",- size_bytes: Number(digest.size),+ size_bytes: sizeBytes,sha256: digest.sha256,...(digest.executable ? { executable: true } : {}),});@@ -333,13 +360,20 @@ export function createContextViewContent(options: {if (kind !== "files") return notFound();let file: PublishedFile | undefined;for (const view of views?.values() ?? []) {- file = view.files.get(id);- if (file) break;+ const candidate = view.files.get(id);+ if (candidate && "text" in candidate) {+ file = candidate;+ break;+ }+ file ??= candidate;}if (!file) return notFound();let bytes: Buffer;try {- bytes = (await readStable(file.sourcePath, id)).bytes;+ bytes =+ "text" in file+ ? Buffer.from(file.text)+ : (await readStable(file.sourcePath, id)).bytes;} catch {return changed();}@@ -361,6 +395,16 @@ interface SourceFile {readonly sourcePath: string;}+function isNestedTarget(+ relativePath: string,+ targets: readonly string[],+): boolean {+ return targets.some(+ (target) =>+ relativePath === target || relativePath.startsWith(`${target}/`),+ );+}+async function* walkDirectory(options: {readonly root: string;readonly relativeRoot: string;@@ -378,13 +422,7 @@ async function* walkDirectory(options: {const relativePath = options.relativeRoot? `${options.relativeRoot}/${entry.name}`: entry.name;- if (- options.skip.some(- (prefix) =>- relativePath === prefix || relativePath.startsWith(`${prefix}/`),- )- )- continue;+ if (isNestedTarget(relativePath, options.skip)) continue;const absolutePath = path.join(directory, entry.name);let sourcePath = absolutePath;let metadata = await lstat(absolutePath);diff --git a/apps/node-services/tests/agent/agent-features/agent-memory/executor-composition.test.ts b/apps/node-services/tests/agent/agent-features/agent-memory/executor-composition.test.tsindex 86b39d97..2c031455 100644--- a/apps/node-services/tests/agent/agent-features/agent-memory/executor-composition.test.ts+++ b/apps/node-services/tests/agent/agent-features/agent-memory/executor-composition.test.ts@@ -33,19 +33,16 @@ describe("Agent Memory executor composition", () => {throw new Error("stop before native execution");},);- const projection = createMemoryProjection(- {- read: async () => ({- revision: published ? 1 : 0,- summary: published ? "Orchard index" : "",- memory: published ? "Orchard decision" : "",- sessions: {},- cursors: {},- }),- commit: vi.fn(),- },- contextHost,- );+ const projection = createMemoryProjection({+ read: async () => ({+ revision: published ? 1 : 0,+ summary: published ? "Orchard index" : "",+ memory: published ? "Orchard decision" : "",+ sessions: {},+ cursors: {},+ }),+ commit: vi.fn(),+ });const silentLogger = {child() {return this;diff --git a/apps/node-services/tests/agent/agent-features/agent-memory/projection.test.ts b/apps/node-services/tests/agent/agent-features/agent-memory/projection.test.tsindex 868e7bac..e890c6d5 100644--- a/apps/node-services/tests/agent/agent-features/agent-memory/projection.test.ts+++ b/apps/node-services/tests/agent/agent-features/agent-memory/projection.test.ts@@ -1,357 +1,94 @@-import { createHash } from "node:crypto";-import {- lstat,- mkdir,- mkdtemp,- readFile,- readdir,- rm,- symlink,-} from "node:fs/promises";-import os from "node:os";-import path from "node:path";import { describe, expect, it, vi } from "vitest";import { createMemoryProjection } from "../../../../src/agent/agent-features/agent-memory/projection.js";import type { MemoryDocument } from "../../../../src/agent/agent-features/agent-memory/client.js";-import type { AgentContextHost } from "../../../../src/agent/executor/workspace.js";-describe("Agent memory projection", () => {- it("says and projects nothing before the first publication", async () => {- const ensureAgentRoots = vi.fn();- const projection = createMemoryProjection(- {- read: async () => ({- revision: 0,- summary: "",- memory: "",- sessions: {},- cursors: {},- }),- commit: vi.fn(),- },- { ensureAgentRoots },- );- const result = await projection.prepare("A", new AbortController().signal);- expect(result).toEqual({});- expect(ensureAgentRoots).not.toHaveBeenCalled();- });+const sessionKey = "a".repeat(64);- it("publishes independent immutable generations and converges concurrent preparations", async () => {- const root = await mkdtemp(path.join(os.tmpdir(), "agent-memory-"));- let memory = "original decision";- const key = "a".repeat(64);- const projection = createMemoryProjection(- {- read: async (agentId): Promise<MemoryDocument> => ({- revision: 1,- summary: `${agentId} index`,- memory,- sessions: {- [key]: {- context_key: "source",- thread_id: "thread",- through: 1,- updated_revision: 1,- summary: "source evidence",- raw_memory: "candidate",- },- },- cursors: {},- }),- commit: async () => {- throw new Error("projection must not mutate authority");- },+function documentWith(memory: string): MemoryDocument {+ return {+ revision: 1,+ summary: "index",+ memory,+ sessions: {+ [sessionKey]: {+ context_key: "source",+ thread_id: "thread",+ through: 1,+ updated_revision: 1,+ summary: "source evidence",+ raw_memory: "unpublished candidate",},- {- ensureAgentRoots: async (id) => ({ agentRoot: path.join(root, id) }),- } as Pick<AgentContextHost, "ensureAgentRoots">,- );- try {- const signal = new AbortController().signal;- const [first, same] = await Promise.all([- projection.prepare("A", signal),- projection.prepare("A", signal),- ]);- expect(first).toEqual(same);- expect(first.mapping).toMatchObject({- access: "read_only",- targetPath: "/workspace/agent-memory",- });- expect(first.summary).toBe("A index");- expect(- await readFile(- path.join(- first.mapping!.sourcePath,- "session_summaries",- `${key}.md`,- ),- "utf8",- ),- ).toBe("source evidence");- memory = "corrected decision";- const next = await projection.prepare("A", signal);- const other = await projection.prepare("B", signal);- expect(next.mapping!.sourcePath).not.toBe(first.mapping!.sourcePath);- expect(other.mapping!.sourcePath).toContain(path.join(root, "B"));- expect(- await readFile(- path.join(first.mapping!.sourcePath, "MEMORY.md"),- "utf8",- ),- ).toBe("original decision");- expect(- await readFile(- path.join(next.mapping!.sourcePath, "MEMORY.md"),- "utf8",- ),- ).toBe("corrected decision");- expect(- (- await readdir(path.join(root, "A", "agent-memory", "generations"))- ).some((name) => name.startsWith(".draft-")),- ).toBe(false);- } finally {- await rm(root, { recursive: true, force: true });- }- });+ },+ cursors: {},+ };+}- describe("generation reuse and writes", () => {- const sessionKey = (index: number) => index.toString(16).padStart(64, "0");- const documentWith = (- memory: string,- sessionCount = 0,- ): MemoryDocument => ({- revision: 1,- summary: "index",- memory,- sessions: Object.fromEntries(- Array.from({ length: sessionCount }, (_, index) => [- sessionKey(index + 1),- {- context_key: "source",- thread_id: "thread",- through: 1,- updated_revision: 1,- summary: `session ${index + 1}`,- raw_memory: "candidate",- },- ]),- ),- cursors: {},- });- const projectionFor = (root: string, document: () => MemoryDocument) =>- createMemoryProjection(- {- read: async () => document(),- commit: async () => {- throw new Error("projection must not mutate authority");- },- },- {- ensureAgentRoots: async (id) => ({- agentRoot: path.join(root, id),- }),- } as Pick<AgentContextHost, "ensureAgentRoots">,- );- const generationsOf = (root: string) =>- path.join(root, "A", "agent-memory", "generations");- const signal = () => new AbortController().signal;-- it("reuses an existing generation without writing or creating a draft", async () => {- const root = await mkdtemp(path.join(os.tmpdir(), "agent-memory-"));- try {- const projection = projectionFor(root, () => documentWith("stable", 3));- const first = await projection.prepare("A", signal());- const target = first.mapping!.sourcePath;- const before = await lstat(target);- const filesBefore = await readdir(- path.join(target, "session_summaries"),- );- const mtimesBefore = await Promise.all(- [- path.join(target, "MEMORY.md"),- ...filesBefore.map((name) =>- path.join(target, "session_summaries", name),- ),- ].map(async (file) => (await lstat(file)).mtimeMs),- );- await new Promise((resolve) => setTimeout(resolve, 20));-- const second = await projection.prepare("A", signal());- expect(second).toEqual(first);- const after = await lstat(target);- expect(after.ino).toBe(before.ino);- expect(- (await readdir(generationsOf(root))).filter((name) =>- name.startsWith(".draft-"),- ),- ).toEqual([]);- const mtimesAfter = await Promise.all(- [- path.join(target, "MEMORY.md"),- ...filesBefore.map((name) =>- path.join(target, "session_summaries", name),- ),- ].map(async (file) => (await lstat(file)).mtimeMs),- );- expect(mtimesAfter).toEqual(mtimesBefore);- } finally {- await rm(root, { recursive: true, force: true });- }- });-- it("publishes a changed document as a new generation with exact contents", async () => {- const root = await mkdtemp(path.join(os.tmpdir(), "agent-memory-"));- try {- let memory = "before";- const projection = projectionFor(root, () => documentWith(memory, 2));- const first = await projection.prepare("A", signal());- memory = "after";- const next = await projection.prepare("A", signal());- expect(next.mapping!.sourcePath).not.toBe(first.mapping!.sourcePath);- expect(- await readFile(- path.join(next.mapping!.sourcePath, "MEMORY.md"),- "utf8",- ),- ).toBe("after");- expect(- await readFile(- path.join(next.mapping!.sourcePath, "summary.md"),- "utf8",- ),- ).toBe("index");- expect(- (- await readdir(- path.join(next.mapping!.sourcePath, "session_summaries"),- )- ).sort(),- ).toEqual([`${sessionKey(1)}.md`, `${sessionKey(2)}.md`]);- expect(- await readFile(- path.join(- next.mapping!.sourcePath,- "session_summaries",- `${sessionKey(2)}.md`,- ),- "utf8",- ),- ).toBe("session 2");- } finally {- await rm(root, { recursive: true, force: true });- }+describe("Agent memory projection", () => {+ it("says and projects nothing before the first publication", async () => {+ const projection = createMemoryProjection({+ read: async () => ({+ revision: 0,+ summary: "",+ memory: "",+ sessions: {},+ cursors: {},+ }),+ commit: vi.fn(),});+ await expect(+ projection.prepare("A", new AbortController().signal),+ ).resolves.toEqual({});+ });- it("converges two concurrent preparations of a new document on one complete generation", async () => {- const root = await mkdtemp(path.join(os.tmpdir(), "agent-memory-"));- try {- const projection = projectionFor(root, () => documentWith("fresh", 4));- const [first, second] = await Promise.all([- projection.prepare("A", signal()),- projection.prepare("A", signal()),- ]);- expect(second).toEqual(first);- expect((await readdir(generationsOf(root))).sort()).toEqual([- first.mapping!.sourcePath.split(path.sep).at(-1),- ]);- expect(- await readFile(- path.join(first.mapping!.sourcePath, "MEMORY.md"),- "utf8",- ),- ).toBe("fresh");- expect(- (- await readdir(- path.join(first.mapping!.sourcePath, "session_summaries"),- )- ).length,- ).toBe(4);- } finally {- await rm(root, { recursive: true, force: true });- }+ it("pins only published content without mutating the authoritative document", async () => {+ let document = documentWith("first decision");+ const commit = vi.fn();+ const projection = createMemoryProjection({+ read: async () => document,+ commit,});+ const signal = new AbortController().signal;+ const first = await projection.prepare("A", signal);+ document = { ...documentWith("second decision"), summary: "new index" };+ const second = await projection.prepare("A", signal);- it("keeps only the current generation and the newest older one", async () => {- const root = await mkdtemp(path.join(os.tmpdir(), "agent-memory-"));- try {- let memory = "first";- const projection = projectionFor(root, () => documentWith(memory, 1));- const prepared: string[] = [];- for (const next of ["first", "second", "third", "fourth"]) {- memory = next;- const result = await projection.prepare("A", signal());- prepared.push(result.mapping!.sourcePath.split(path.sep).at(-1)!);- await new Promise((resolve) => setTimeout(resolve, 20));- }- // A deletion cut short leaves trash, never a partial generation.- await mkdir(path.join(generationsOf(root), ".trash-left"));- const inFlight = path.join(generationsOf(root), ".draft-in-flight");- await mkdir(inFlight);- memory = "fifth";- const current = await projection.prepare("A", signal());- expect((await readdir(generationsOf(root))).sort()).toEqual(- [- ".draft-in-flight",- prepared[3]!,- current.mapping!.sourcePath.split(path.sep).at(-1)!,- ].sort(),- );- expect(- await readFile(- path.join(current.mapping!.sourcePath, "MEMORY.md"),- "utf8",- ),- ).toBe("fifth");- } finally {- await rm(root, { recursive: true, force: true });- }+ expect(first).toEqual({+ summary: "index",+ mapping: {+ kind: "memory",+ targetPath: "/workspace/agent-memory",+ access: "read_only",+ inlineFiles: {+ "summary.md": "index",+ "MEMORY.md": "first decision",+ [`session_summaries/${sessionKey}.md`]: "source evidence",+ },+ },});-- it("does not reuse a symlink at the generation path", async () => {- const root = await mkdtemp(path.join(os.tmpdir(), "agent-memory-"));- try {- const memory = "linked";- const revision = createHash("sha256")- .update(- JSON.stringify({ "summary.md": "index", "MEMORY.md": memory }),- )- .digest("hex");- const elsewhere = path.join(root, "elsewhere");- await mkdir(elsewhere);- await mkdir(generationsOf(root), { recursive: true });- await symlink(elsewhere, path.join(generationsOf(root), revision));- const projection = projectionFor(root, () => documentWith(memory));- await expect(projection.prepare("A", signal())).rejects.toThrow();- expect(await readdir(elsewhere)).toEqual([]);- } finally {- await rm(root, { recursive: true, force: true });- }+ expect(Object.isFrozen(first.mapping!.inlineFiles)).toBe(true);+ expect(second).toMatchObject({+ summary: "new index",+ mapping: {+ inlineFiles: {+ "summary.md": "new index",+ "MEMORY.md": "second decision",+ },+ },});+ expect(commit).not.toHaveBeenCalled();+ });- it("writes every session summary of a large generation", async () => {- const root = await mkdtemp(path.join(os.tmpdir(), "agent-memory-"));- try {- const projection = projectionFor(root, () => documentWith("many", 50));- const result = await projection.prepare("A", signal());- const sessions = path.join(- result.mapping!.sourcePath,- "session_summaries",- );- const names = (await readdir(sessions)).sort();- expect(names).toHaveLength(50);- for (let index = 1; index <= 50; index++) {- expect(- await readFile(- path.join(sessions, `${sessionKey(index)}.md`),- "utf8",- ),- ).toBe(`session ${index}`);- }- } finally {- await rm(root, { recursive: true, force: true });- }+ it("refuses a session key that cannot name a file in the projection", async () => {+ const document = documentWith("decision");+ const projection = createMemoryProjection({+ read: async () => ({+ ...document,+ sessions: { "../outside": document.sessions[sessionKey]! },+ }),+ commit: vi.fn(),});+ await expect(+ projection.prepare("A", new AbortController().signal),+ ).rejects.toThrow("Invalid memory session key");});});diff --git a/apps/node-services/tests/agent/agent-features/agent-memory/services.test.ts b/apps/node-services/tests/agent/agent-features/agent-memory/services.test.tsindex 7903a5a6..417f4f52 100644--- a/apps/node-services/tests/agent/agent-features/agent-memory/services.test.ts+++ b/apps/node-services/tests/agent/agent-features/agent-memory/services.test.ts@@ -16,7 +16,6 @@ const fixture = (overrides: Partial<AgentMemoryServicesOptions> = {},): AgentMemoryServicesOptions => ({memory: { read: vi.fn(), commit: vi.fn() },- contextHost: { ensureAgentRoots: vi.fn() },runtimeState: {listContexts: async () => [],getWorkState: vi.fn(),diff --git a/apps/node-services/tests/agent/agent-features/builtin.test.ts b/apps/node-services/tests/agent/agent-features/builtin.test.tsindex 3b645f79..d4ccab73 100644--- a/apps/node-services/tests/agent/agent-features/builtin.test.ts+++ b/apps/node-services/tests/agent/agent-features/builtin.test.ts@@ -415,7 +415,6 @@ describe("createBuiltinAgentFeatures", () => {it("propagates the shared Memory services' late start() binding loudly", async () => {const services = createAgentMemoryServices({memory: { read: vi.fn(), commit: vi.fn() },- contextHost: { ensureAgentRoots: vi.fn() },runtimeState: {} as never,logger: logger(),});diff --git a/apps/node-services/tests/agent/executor/local-backend.test.ts b/apps/node-services/tests/agent/executor/local-backend.test.tsindex 90fe4b8d..db156fdd 100644--- a/apps/node-services/tests/agent/executor/local-backend.test.ts+++ b/apps/node-services/tests/agent/executor/local-backend.test.ts@@ -1,3 +1,7 @@+import { createHash } from "node:crypto";+import { mkdtemp, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";import { describe, expect, it, vi } from "vitest";import type {@@ -8,9 +12,12 @@ import type {import { createLocalContextRuntimeBackend } from "../../../src/agent/executor/local-backend.js";import type { ContextRuntimeBackendRequest } from "../../../src/agent/executor/activation.js";import { encodeExecutionContextRef } from "../../../src/agent/executor/context-ref.js";-import type {- ContextViewContent,- ContextViewSnapshotInput,+import { createMemoryProjection } from "../../../src/agent/agent-features/agent-memory/projection.js";+import {+ createContextViewContent,+ type ContextViewContent,+ type ContextViewManifest,+ type ContextViewSnapshotInput,} from "../../../src/agent/runner-gateway/context-view-content.js";import type { LocalRuntimeModelDefinition } from "../../../src/agent/runner-gateway/local-computer-management.js";import type {@@ -379,6 +386,115 @@ describe("Local Context Runtime backend", () => {expect(views.events.slice(-2)).toEqual(["release:c", "release:b"]);});+ it("starts the next Run with its activation memory after the shared generations disappear", async () => {+ const agentRoot = await mkdtemp(+ path.join(os.tmpdir(), "activation-memory-"),+ );+ const request = requestFixture();+ let published = "A";+ const projection = createMemoryProjection({+ read: async () => ({+ revision: 1,+ summary: `index ${published}`,+ memory: `decision ${published}`,+ sessions: {},+ cursors: {},+ }),+ commit: vi.fn(),+ });+ const prepare = () =>+ projection.prepare(request.ref.agentId, request.signal);+ const views = createContextViewContent({+ publicOrigin: "https://agent.example",+ signingKey: "k".repeat(32),+ isCurrentConnection: (id, epoch) => id === "computer-1" && epoch === 1,+ });+ const { backend, targets } = backendFixture(views);+ const url = views.contentUrl("computer-1", 1);+ const get = (kind: string, id: string) =>+ views.handle(+ url.slice(url.lastIndexOf("/") + 1),+ kind,+ id,+ new Request(`${url}/${kind}/${id}`),+ );+ const memoryFile = async (digest: string, relativePath: string) => {+ const response = await get("views", digest);+ expect(response.status).toBe(200);+ const manifest = (await response.json()) as ContextViewManifest;+ const mapping = manifest.mappings.find(+ (m) => m.target_path === "agent-memory",+ );+ expect(mapping?.access).toBe("read_only");+ return mapping!.files.find((f) => f.relative_path === relativePath)!;+ };+ try {+ const first = await prepare();+ const planA = { ...request.viewPlan, mappings: [first.mapping!] };+ const active = await backend.activate({ ...request, viewPlan: planA });+ try {+ await runOnce(active, "run-before-change");+ const digestA = targets.at(-1)!.contextViewRef.view_digest;+ expect(first.summary).toBe("index A");+ const fileA = await memoryFile(digestA, "MEMORY.md");++ published = "B";+ await prepare();+ published = "C";+ const latest = await prepare();+ // Force the observed missing-directory failure independently of mtime.+ await rm(path.join(agentRoot, "agent-memory", "generations"), {+ recursive: true,+ force: true,+ });++ await active.synchronize(planA);+ await runOnce(active, "run-after-change");+ expect(targets.at(-1)?.contextViewRef.view_digest).toBe(digestA);+ const delayed = await get("files", fileA.sha256);+ expect(delayed.status).toBe(200);+ const original = await delayed.text();+ expect(original).toBe("decision A");+ expect(createHash("sha256").update(original).digest("hex")).toBe(+ fileA.sha256,+ );+ const summaryA = await memoryFile(digestA, "summary.md");+ expect(await (await get("files", summaryA.sha256)).text()).toBe(+ first.summary,+ );++ const reactivated = await backend.activate({+ ...request,+ viewPlan: { ...request.viewPlan, mappings: [latest.mapping!] },+ });+ try {+ await runOnce(reactivated, "run-after-reactivation");+ const digestC = targets.at(-1)!.contextViewRef.view_digest;+ expect(digestC).not.toBe(digestA);+ const fileC = await memoryFile(digestC, "MEMORY.md");+ expect(await (await get("files", fileC.sha256)).text()).toBe(+ "decision C",+ );+ const summaryC = await memoryFile(digestC, "summary.md");+ expect(latest.summary).toBe("index C");+ expect(await (await get("files", summaryC.sha256)).text()).toBe(+ latest.summary,+ );+ await active.deactivate();+ expect((await get("views", digestA)).status).toBe(404);+ expect((await get("files", fileA.sha256)).status).toBe(404);+ expect((await get("views", digestC)).status).toBe(200);+ } finally {+ await reactivated.deactivate();+ }+ } finally {+ await active.deactivate();+ }+ } finally {+ await rm(agentRoot, { recursive: true, force: true });+ }+ });+it("releases the activation snapshot when the Runner is not ready", async () => {const views = viewContent(FIRST);const { backend } = backendFixture(views.content, async () => {diff --git a/apps/node-services/tests/agent/executor/workspace.test.ts b/apps/node-services/tests/agent/executor/workspace.test.tsindex b27fad4a..64bc6e92 100644--- a/apps/node-services/tests/agent/executor/workspace.test.ts+++ b/apps/node-services/tests/agent/executor/workspace.test.ts@@ -111,7 +111,7 @@ describe("AgentContextHost", () => {expect(plan.playgroundRootPath).toBeDefined();const documents = plan.mappings.find(({ kind }) => kind === "inbox_view",- )!.sourcePath;+ )!.sourcePath!;expect(plan.mappings.find(({ kind }) => kind === "playground"),).toMatchObject({ targetPath: "/workspace/playground" });@@ -182,7 +182,7 @@ describe("AgentContextHost", () => {),).toBe(false);for (const mapping of [...metaPlan.mappings, ...alterPlan.mappings]) {- await expectDirectory(mapping.sourcePath);+ await expectDirectory(mapping.sourcePath!);}const restored = await createAgentContextHost({ rootPath });