Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/assistant-history-discovery.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@sapiom/harness": patch
---

Discover retained Assistant history by Studio identity without starting a native runtime or requiring a Terminal conversation. Keep missing records distinct from incomplete or unavailable history.
9 changes: 9 additions & 0 deletions packages/harness/docs/assistant-history.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# Retained Assistant history

`GET /api/sessions/assistant-history?cwd=<absolute-workspace>` returns
`{ entries: AssistantHistoryEntry[] }`, ordered by latest retained activity.
It requires the current boot token and workspace/Assistant authority. Entries
use Studio IDs, including sessions whose Terminal never started, and initially
report `nativeResume: "unchecked"`. Listing never launches or queries native
runtimes. Missing, partial and unreadable checkpoints have distinct states.
Account changes during listing discard the result. Malformed metadata returns
503 rather than silently substituting a different conversation.

`GET /api/sessions/:id/assistant/record` returns `{ record: AssistantRecord }`
for the currently authorized Studio session and Assistant binding. Supply the
current boot token in `X-Harness-Token`. The server checks current Assistant
Expand Down
180 changes: 180 additions & 0 deletions packages/harness/src/core/assistant-history.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { AssistantHistory } from "./assistant-history.js";
import { AssistantRecordStore } from "./assistant-record-store.js";
import {
AssistantSessionStore,
type AssistantAssociation,
} from "./assistant-session-store.js";
import { OpenCodeAccessError } from "./opencode-host.js";
import type { HarnessSession } from "../shared/types.js";
import type { AssistantRecord } from "../shared/assistant-record.js";

let root: string,
cwd: string,
records: AssistantRecordStore,
sessions: HarnessSession[],
store: AssistantSessionStore,
history: AssistantHistory;
let bindings: Map<string, AssistantAssociation>;
const authorize = vi.fn();
const record = (binding: AssistantAssociation): AssistantRecord => ({
schemaVersion: 1,
binding: {
harnessSessionId: binding.harnessSessionId,
conversationId: binding.conversationId,
contextAuthorityScope: binding.contextAuthorityScope,
cwd: binding.cwd,
},
revision: 1,
capturedAt: "2026-09-14T10:00:00.000Z",
reconstructed: true,
turns: [],
turnCount: 0,
messageCount: 0,
limitations: [],
});
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), "assistant-discovery-"));
cwd = join(root, "project");
await mkdir(cwd);
store = new AssistantSessionStore(root);
records = new AssistantRecordStore(root);
bindings = new Map();
sessions = [];
for (const [index, id] of [
"studio-a",
"studio-b",
"terminal-only",
].entries()) {
sessions.push({
id,
cwd,
harness: "claude-code",
title: id,
status: "exited",
ready: false,
agentSessionId: null,
boundWorkflowPath: null,
terminalState: "not-started",
createdAt: "2026-09-14T09:00:00.000Z",
lastActiveAt: "2026-09-14T09:00:00.000Z",
});
if (index === 2) continue;
const binding = await store.associate(
{
harnessSessionId: id,
cwd,
contextAuthorityScope: String(index + 1).repeat(64),
},
String(index + 3).repeat(64),
async () => `ses_${index}`,
);
bindings.set(id, binding!);
await store.transition(id, 0, { lifecycle: "ended", execution: "paused" });
await records.write(record(binding!));
}
authorize
.mockReset()
.mockImplementation(async (id) => bindings.get(id) ?? null);
history = new AssistantHistory({
sessions: {
list: () => sessions,
get: (id) => sessions.find((s) => s.id === id),
},
authorize,
records,
lifecycle: { describe: async (id) => (await store.lifecycle(id))! },
});
});
afterEach(async () => {
await rm(root, { recursive: true, force: true });
});

it("discovers distinct same-folder Assistant identities with no Terminal vendor or native runtime", async () => {
const result = await history.list(cwd);
expect(result.map((entry) => entry.harnessSessionId)).toEqual([
"studio-a",
"studio-b",
]);
expect(result[0]).toMatchObject({
kind: "assistant",
history: "available",
nativeResume: "unchecked",
recordRevision: 1,
lifecycle: { lifecycle: "ended" },
});
expect(JSON.stringify(result)).not.toContain("contextAuthorityScope");
expect(JSON.stringify(result)).not.toContain("conversationId");
const other = join(root, "other");
await mkdir(other);
expect(await history.list(other)).toEqual([]);
});

it("distinguishes missing, partial and failed retained records", async () => {
const first = bindings.get("studio-a")!;
await records.write({
...record(first),
revision: 2,
limitations: ["private-parts-omitted"],
});
expect((await history.entry("studio-a"))?.history).toBe("partial");
const directory = join(
root,
"assistant-sessions",
"studio-a",
"bindings",
first.contextAuthorityScope,
);
await rm(join(directory, "record.json"));
await rm(join(directory, "record.json.previous"), { force: true });
expect((await history.entry("studio-a"))?.history).toBe("missing");
await writeFile(join(directory, "record.json"), "invalid");
expect((await history.entry("studio-a"))?.history).toBe("unavailable");
});

it("retains discovery after native data disappears", async () => {
await rm(join(root, "opencode"), { recursive: true, force: true });
expect((await history.list(cwd)).map((entry) => entry.history)).toEqual([
"available",
"available",
]);
});

it("discards a read whose binding changes before it returns", async () => {
authorize
.mockResolvedValueOnce(bindings.get("studio-a"))
.mockResolvedValueOnce({
...bindings.get("studio-a"),
contextAuthorityScope: "f".repeat(64),
});
await expect(history.entry("studio-a")).rejects.toBeInstanceOf(
OpenCodeAccessError,
);
});

it("checks earlier entries again after reading the rest of a history list", async () => {
let calls = 0;
authorize.mockImplementation(async (id) => {
const binding = bindings.get(id) ?? null;
if (id !== "studio-a") return binding;
calls++;
return calls < 3
? binding
: { ...binding, contextAuthorityScope: "f".repeat(64) };
});
await expect(history.list(cwd)).rejects.toBeInstanceOf(OpenCodeAccessError);
});

it("omits unauthorized entries and surfaces corrupt lifecycle metadata", async () => {
authorize.mockRejectedValue(new OpenCodeAccessError("expired"));
expect(await history.list(cwd)).toEqual([]);
authorize.mockImplementation(async (id) => bindings.get(id) ?? null);
await writeFile(
join(root, "assistant-sessions", "studio-a", "lifecycle.json"),
"corrupt",
);
await expect(history.list(cwd)).rejects.toThrow();
});
134 changes: 134 additions & 0 deletions packages/harness/src/core/assistant-history.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import { realpath } from "node:fs/promises";
import { isAbsolute } from "node:path";
import type { AssistantHistoryEntry } from "../shared/assistant-history.js";
import type { HarnessSession } from "../shared/types.js";
import type { AssistantRecordStore } from "./assistant-record-store.js";
import type { AssistantAssociation } from "./assistant-session-store.js";
import type { AssistantLifecycleCoordinator } from "./assistant-lifecycle.js";
import { OpenCodeAccessError } from "./opencode-host.js";

interface Options {
sessions: {
list(): HarnessSession[];
get(id: string): HarnessSession | undefined;
};
authorize: (id: string) => Promise<AssistantAssociation | null>;
records: Pick<AssistantRecordStore, "read">;
lifecycle: Pick<AssistantLifecycleCoordinator, "describe">;
}

/** Metadata-only discovery. Native availability is checked separately for a selected entry. */
export class AssistantHistory {
constructor(private readonly options: Options) {}

async entry(id: string): Promise<AssistantHistoryEntry | null> {
return (await this.read(id))?.entry ?? null;
}

private async read(
id: string,
): Promise<{
entry: AssistantHistoryEntry;
binding: AssistantAssociation;
} | null> {
const session = this.options.sessions.get(id);
if (!session) return null;
const binding = await this.options.authorize(id);
if (!binding) return null;
const lifecycle = await this.options.lifecycle.describe(id);
let history: AssistantHistoryEntry["history"] = "unavailable";
let recordRevision: number | null = null;
let updatedAt = session.lastActiveAt;
try {
const { harnessSessionId, contextAuthorityScope, conversationId, cwd } =
binding;
const record = await this.options.records.read({
harnessSessionId,
contextAuthorityScope,
conversationId,
cwd,
});
history = !record
? "missing"
: record.limitations.length ||
record.turns.some((turn) => turn.incomplete)
? "partial"
: "available";
recordRevision = record?.revision ?? null;
updatedAt = record?.capturedAt ?? updatedAt;
} catch {
// Storage failure is distinct from an authorized binding with no checkpoint.
}
if (
JSON.stringify(await this.options.authorize(id)) !==
JSON.stringify(binding)
)
throw new OpenCodeAccessError("Assistant binding changed");
const current = this.options.sessions.get(id);
if (!current || current.cwd !== session.cwd)
throw new OpenCodeAccessError("Workspace changed");
return {
binding,
entry: {
kind: "assistant",
harnessSessionId: id,
title: current.title,
cwd: binding.cwd,
createdAt: current.createdAt,
updatedAt,
lifecycle,
history,
nativeResume: "unchecked",
recordRevision,
},
};
}

async list(cwd: string): Promise<AssistantHistoryEntry[]> {
if (!isAbsolute(cwd) || cwd.length > 4096)
throw new OpenCodeAccessError("Workspace unavailable");
const canonical = await realpath(cwd);
const sessions = this.options.sessions.list();
const entries: {
entry: AssistantHistoryEntry;
binding: AssistantAssociation;
}[] = [];
// Bound filesystem concurrency when a workspace has a long history.
for (let offset = 0; offset < sessions.length; offset += 8) {
const page = await Promise.allSettled(
sessions.slice(offset, offset + 8).map(async (session) => {
try {
if ((await realpath(session.cwd)) !== canonical) return null;
const entry = await this.read(session.id);
return entry?.entry.cwd === canonical ? entry : null;
} catch (error) {
if (
error instanceof OpenCodeAccessError ||
(error as NodeJS.ErrnoException).code === "ENOENT"
)
return null;
throw error;
}
}),
);
for (const result of page) {
if (result.status === "rejected") throw result.reason;
if (result.value) entries.push(result.value);
}
}
// Revalidate the complete result after IO for the other entries. No old
// authority's titles or existence may escape on a mid-list account change.
for (const { entry, binding: previous } of entries) {
const binding = await this.options.authorize(entry.harnessSessionId);
if (!binding || JSON.stringify(binding) !== JSON.stringify(previous))
throw new OpenCodeAccessError("Assistant access changed");
}
return entries
.map(({ entry }) => entry)
.sort(
(a, b) =>
b.updatedAt.localeCompare(a.updatedAt) ||
a.harnessSessionId.localeCompare(b.harnessSessionId),
);
}
}
Loading
Loading