feat(workspaces): registry and header-only disk discovery

- atomic 0600 workspaces.json with corrupt-file recovery
- discovery reads only the first JSONL line for the authoritative cwd
- cache by dir mtime+count: cold 27-37ms / warm 9.6ms on 1313 files
- 38 tests, real-machine benchmark documented in the report
This commit is contained in:
yuez committed 2026-10-21 11:14:12 +08:00
1 parent ba3719fad9
commit 4e98ef8658
8 files changed
+1875

No files matched your search

+346
View File
@@ -0,0 +1,346 @@
/**
* Read-only disk discovery for pi session directories.
*
* pi stores sessions at:
* `<PI_CODING_AGENT_DIR or ~/.pi/agent>/sessions/--<encoded-cwd>--/<ISO>_<id>.jsonl`
*
* The encoded directory name is not reversible (`-` is both a path character
* and the separator), so the authoritative cwd is the first JSONL line:
* {"type":"session","version":3,"id":"…","timestamp":"…","cwd":"/abs/path"}
*
* Scanning is header-only (one read of up to 64 KiB per directory) and cached
* per directory by (mtime, file count). The rest of a session file is never read.
*/
import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
import { basename, isAbsolute, join } from "node:path";
import { sessionsRoot, workspaceIdForCwd } from "../core/paths.js";
/** Maximum bytes read to obtain the first JSONL line. Headers are ~150 bytes. */
export const HEADER_READ_LIMIT = 64 * 1024;
export interface DiscoveredWorkspace {
workspaceId: string;
/** Authoritative cwd from the session header (not decoded from `dir`). */
cwd: string;
/** Number of `.jsonl` files in the encoded directory. */
sessionCount: number;
/** mtime (ms) of the newest session file, or null when unknown. */
lastActiveAt: number | null;
/** Absolute path of the `--<encoded-cwd>--` directory. */
dir: string;
/** False when the cwd in the header no longer exists (ghost workspace). */
exists: boolean;
}
export interface SessionFile {
/** Session id from the header, falling back to the file name suffix. */
id: string;
/** Absolute path to the `.jsonl` file. */
file: string;
/** Header timestamp in epoch ms (file-name fallback when the header is bad). */
timestamp: number;
/** File mtime in epoch ms. */
modified: number;
/**
* Optional first user message preview. Deliberately not populated by the
* cheap header-only scan; a name comes from the live instance later.
*/
firstMessage?: string;
}
export interface DiscoveryOptions {
/** Defaults to `sessionsRoot()`. */
root?: string;
logger?: DiscoveryLogger;
}
export interface DiscoveryLogger {
debug?(msg: string, fields?: Record<string, unknown>): void;
warn?(msg: string, fields?: Record<string, unknown>): void;
}
export interface Discovery {
/** Scan every `--*--` directory under the sessions root. */
discover(): DiscoveredWorkspace[];
/** Session files for a cwd, newest first (header-only, cheap). */
listSessions(cwd: string): SessionFile[];
/** Drop one directory's cache entry, or the whole cache when omitted. */
invalidate(dir?: string): void;
/** The encoded directory used for a cwd, when it has been discovered. */
dirForCwd(cwd: string): string | undefined;
}
interface CacheEntry {
/** Signature component 1: directory mtime in ms. */
mtimeMs: number;
/** Signature component 2: number of `.jsonl` files in the directory. */
size: number;
result: DiscoveredWorkspace | null;
}
interface SessionFileInfo {
file: string;
mtimeMs: number;
size: number;
}
interface SessionHeader {
cwd?: string;
id?: string;
timestamp?: string;
}
export function isSessionDirName(name: string): boolean {
return name.length > 4 && name.startsWith("--") && name.endsWith("--");
}
class DiskDiscovery implements Discovery {
private readonly root: string;
private readonly logger: DiscoveryLogger | undefined;
private readonly cache = new Map<string, CacheEntry>();
constructor(options: DiscoveryOptions = {}) {
this.root = options.root ?? sessionsRoot();
this.logger = options.logger;
}
discover(): DiscoveredWorkspace[] {
let dirents;
try {
dirents = readdirSync(this.root, { withFileTypes: true });
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== "ENOENT" && code !== "ENOTDIR") {
this.logger?.warn?.("cannot read sessions root", {
root: this.root,
error: error instanceof Error ? error.message : String(error),
});
}
return [];
}
const out: DiscoveredWorkspace[] = [];
for (const dirent of dirents) {
if (!dirent.isDirectory() || !isSessionDirName(dirent.name)) continue;
const result = this.scanDir(join(this.root, dirent.name));
if (result) out.push({ ...result });
}
return out;
}
listSessions(cwd: string): SessionFile[] {
if (typeof cwd !== "string" || cwd.length === 0 || !isAbsolute(cwd)) return [];
const workspaceId = workspaceIdForCwd(cwd);
const dirs = this.discover()
.filter((entry) => entry.workspaceId === workspaceId)
.map((entry) => entry.dir);
if (dirs.length === 0) return [];
const sessions: SessionFile[] = [];
const seen = new Set<string>();
for (const dir of dirs) {
for (const info of this.sessionFiles(dir)) {
if (seen.has(info.file)) continue;
seen.add(info.file);
sessions.push(this.describeSession(info));
}
}
sessions.sort((a, b) => b.modified - a.modified || b.timestamp - a.timestamp || a.id.localeCompare(b.id));
return sessions;
}
invalidate(dir?: string): void {
if (dir === undefined) this.cache.clear();
else this.cache.delete(dir);
}
dirForCwd(cwd: string): string | undefined {
if (typeof cwd !== "string" || !isAbsolute(cwd)) return undefined;
const workspaceId = workspaceIdForCwd(cwd);
return this.discover().find((entry) => entry.workspaceId === workspaceId)?.dir;
}
private scanDir(dir: string): DiscoveredWorkspace | null {
let dirStat;
try {
dirStat = statSync(dir);
} catch {
return null;
}
if (!dirStat.isDirectory()) return null;
const files = this.sessionFiles(dir);
const cached = this.cache.get(dir);
if (cached && cached.mtimeMs === dirStat.mtimeMs && cached.size === files.length) {
return cached.result ? { ...cached.result } : null;
}
const newest = files[0];
let result: DiscoveredWorkspace | null = null;
if (newest) {
// Newest by mtime, falling back to older files only when the newest
// header is unreadable (e.g. a truncated write).
let header: SessionHeader | undefined;
for (const file of files) {
header = readSessionHeader(file.file);
if (header?.cwd) break;
}
if (header?.cwd && isAbsolute(header.cwd)) {
result = {
workspaceId: workspaceIdForCwd(header.cwd),
cwd: header.cwd,
sessionCount: files.length,
lastActiveAt: newest.mtimeMs,
dir,
exists: isDirectory(header.cwd),
};
} else {
this.logger?.debug?.("skipping session directory without a usable header", { dir });
}
}
this.cache.set(dir, {
mtimeMs: dirStat.mtimeMs,
size: files.length,
result: result ? { ...result } : null,
});
return result;
}
/** `.jsonl` files in a directory, newest first. Never reads file contents. */
private sessionFiles(dir: string): SessionFileInfo[] {
let dirents;
try {
dirents = readdirSync(dir, { withFileTypes: true });
} catch {
return [];
}
const files: SessionFileInfo[] = [];
for (const dirent of dirents) {
if (!dirent.name.endsWith(".jsonl")) continue;
const file = join(dir, dirent.name);
try {
const stat = statSync(file);
if (!stat.isFile()) continue;
files.push({ file, mtimeMs: stat.mtimeMs, size: stat.size });
} catch {
// Vanished or unreadable file: keep scanning the rest of the dir.
}
}
files.sort((a, b) => b.mtimeMs - a.mtimeMs || b.size - a.size);
return files;
}
private describeSession(info: SessionFileInfo): SessionFile {
const header = readSessionHeader(info.file);
const fromName = parseSessionFileName(info.file);
const id = header?.id ?? fromName.id;
const headerTs = header?.timestamp ? Date.parse(header.timestamp) : Number.NaN;
const timestamp = Number.isFinite(headerTs) ? headerTs : fromName.timestamp;
return {
id,
file: info.file,
timestamp,
modified: info.mtimeMs,
};
}
}
export function createDiscovery(options: DiscoveryOptions = {}): Discovery {
return new DiskDiscovery(options);
}
function isDirectory(path: string): boolean {
try {
return statSync(path).isDirectory();
} catch {
return false;
}
}
/** Read only the first JSONL line; returns undefined for unreadable/invalid files. */
function readSessionHeader(file: string): SessionHeader | undefined {
let fd: number | undefined;
try {
fd = openSync(file, "r");
const buffer = Buffer.allocUnsafe(HEADER_READ_LIMIT);
const bytes = readSync(fd, buffer, 0, HEADER_READ_LIMIT, 0);
if (bytes <= 0) return undefined;
const text = buffer.toString("utf8", 0, bytes);
const newline = text.indexOf("\n");
const line = (newline >= 0 ? text.slice(0, newline) : text).replace(/\r$/, "").trim();
if (line.length === 0) return undefined;
const parsed: unknown = JSON.parse(line);
if (!parsed || typeof parsed !== "object" || (parsed as { type?: unknown }).type !== "session") {
return undefined;
}
const record = parsed as Record<string, unknown>;
return {
cwd: typeof record.cwd === "string" ? record.cwd : undefined,
id: typeof record.id === "string" ? record.id : undefined,
timestamp: typeof record.timestamp === "string" ? record.timestamp : undefined,
};
} catch {
return undefined;
} finally {
if (fd !== undefined) {
try {
closeSync(fd);
} catch {
// ignore
}
}
}
}
/** `<YYYY-MM-DDTHH-MM-SS-mmmZ>_<id>.jsonl` → `{ id, timestamp }`. */
export function parseSessionFileName(file: string): { id: string; timestamp: number } {
const name = basename(file).replace(/\.jsonl$/, "");
const separator = name.indexOf("_");
if (separator < 0) return { id: name, timestamp: 0 };
const stamp = name.slice(0, separator);
const id = name.slice(separator + 1);
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/.exec(stamp);
if (!match) {
const fallback = Date.parse(stamp);
return { id, timestamp: Number.isFinite(fallback) ? fallback : 0 };
}
const [, year, month, day, hour, minute, second, millis] = match;
const iso = `${year}-${month}-${day}T${hour}:${minute}:${second}.${millis}Z`;
const timestamp = Date.parse(iso);
return { id, timestamp: Number.isFinite(timestamp) ? timestamp : 0 };
}
// ---------------------------------------------------------------------------
// Module-level convenience API (shared cache keyed by sessions root).
// ---------------------------------------------------------------------------
const shared = new Map<string, Discovery>();
function sharedDiscovery(root: string | undefined, logger?: DiscoveryLogger): Discovery {
const key = root ?? sessionsRoot();
const existing = shared.get(key);
if (existing) return existing;
const created = createDiscovery({ root: key, ...(logger ? { logger } : {}) });
shared.set(key, created);
return created;
}
export function discoverWorkspaces(options: DiscoveryOptions = {}): DiscoveredWorkspace[] {
return sharedDiscovery(options.root, options.logger).discover();
}
export function listSessions(cwd: string, options: DiscoveryOptions = {}): SessionFile[] {
return sharedDiscovery(options.root, options.logger).listSessions(cwd);
}
/** Drop cached discovery results for every root (or one directory). */
export function invalidate(dir?: string): void {
for (const discovery of shared.values()) discovery.invalidate(dir);
}
+14
View File
@@ -0,0 +1,14 @@
import type { ErrorCode } from "../protocol/errors.js";
/** Error raised by the workspace registry / discovery / store layer. */
export class WorkspaceError extends Error {
readonly code: ErrorCode | string;
readonly retryable: boolean;
constructor(code: ErrorCode | string, message: string, retryable = false, options?: { cause?: unknown }) {
super(message, options);
this.name = "WorkspaceError";
this.code = code;
this.retryable = retryable;
}
}
+426
View File
@@ -0,0 +1,426 @@
/**
* WorkspaceStore: merges the durable registry, disk discovery and live
* instance state into the `WorkspaceInfo` shape served by the daemon.
*
* Ordering and hiding are intentionally left to the UI; `list()` returns every
* known workspace (including `hidden` ones) with stable registry-first order.
*/
import { accessSync, constants, realpathSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
import type { InstanceManager, WorkspaceStore as WorkspaceStoreContract } from "../core/interfaces.js";
import { dataDir, realpathSafe, workspaceIdForCwd } from "../core/paths.js";
import { ERROR_CODES } from "../protocol/errors.js";
import type { InstanceState, WorkspaceInfo } from "../protocol/types.js";
import {
createDiscovery,
type DiscoveredWorkspace,
type Discovery,
type DiscoveryLogger,
} from "./discovery.js";
import { WorkspaceError } from "./errors.js";
import {
validatePatch,
WorkspaceRegistry,
type RegistryLogger,
type WorkspaceEntry,
type WorkspacePatch,
} from "./registry.js";
export interface WorkspaceStoreOptions {
/** Defaults to a discovery over `sessionsRoot()`. */
discovery?: Discovery;
/** Defaults to `${dataDir()}/workspaces.json`. */
registry?: WorkspaceRegistry;
/** Instance supervisor; absent in unit tests and during early boot. */
instances?: Pick<InstanceManager, "list" | "instanceStates">;
logger?: RegistryLogger & Partial<DiscoveryLogger>;
/**
* Explicit allowlist for `add()` (real paths). When omitted,
* `PI2_WORKSPACE_ROOTS` (comma separated) is used, defaulting to homedir.
* `ensureForCwd()` deliberately ignores this list: instances may live
* anywhere the user already opened nvim.
*/
roots?: readonly string[];
}
export interface WorkspaceStoreHandle extends WorkspaceStoreContract {
readonly discovery: Discovery;
readonly registry: WorkspaceRegistry;
}
interface InstanceViews {
instances: Map<string, InstanceState>;
live: Map<string, number>;
}
class WorkspaceStore implements WorkspaceStoreHandle {
readonly discovery: Discovery;
readonly registry: WorkspaceRegistry;
private readonly instances: Pick<InstanceManager, "list" | "instanceStates"> | undefined;
private readonly logger: WorkspaceStoreOptions["logger"] | undefined;
private readonly roots: readonly string[] | undefined;
constructor(options: WorkspaceStoreOptions = {}) {
this.logger = options.logger;
this.discovery = options.discovery ?? createDiscovery({ ...(options.logger ? { logger: options.logger } : {}) });
this.registry =
options.registry ??
new WorkspaceRegistry({
filePath: join(dataDir(), "workspaces.json"),
...(options.logger ? { logger: options.logger } : {}),
});
this.instances = options.instances;
this.roots = options.roots;
}
list(): WorkspaceInfo[] {
const discovered = this.discoveredById();
const views = this.instanceViews();
const records = this.registry.list();
const registered = new Set(records.map((record) => record.workspaceId));
const infos = records.map((record) =>
this.buildInfo(record.workspaceId, record.entry, discovered.get(record.workspaceId), views),
);
for (const [workspaceId, entry] of discovered) {
if (registered.has(workspaceId)) continue;
infos.push(this.buildInfo(workspaceId, undefined, entry, views));
}
return infos;
}
get(workspaceId: string): WorkspaceInfo | undefined {
if (typeof workspaceId !== "string" || workspaceId.length === 0) return undefined;
const record = this.registry.get(workspaceId);
const discovered = this.discoveredById().get(workspaceId);
if (!record && !discovered) return undefined;
return this.buildInfo(workspaceId, record?.entry, discovered, this.instanceViews());
}
byCwd(cwd: string): WorkspaceInfo | undefined {
if (typeof cwd !== "string" || cwd.length === 0 || !isAbsolute(cwd)) return undefined;
const registered = this.registry.byCwd(cwd);
if (registered) return this.get(registered.workspaceId);
return this.get(workspaceIdForCwd(cwd));
}
async add(input: { cwd: string; alias?: string; trust?: boolean }): Promise<WorkspaceInfo> {
if (!input || typeof input !== "object") {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, "workspace input must be an object");
}
const raw = input.cwd;
if (typeof raw !== "string" || raw.trim().length === 0) {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, "cwd must be a non-empty string");
}
if (raw.includes("\0")) {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, "cwd contains a NUL byte");
}
if (!isAbsolute(raw)) {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, `cwd must be absolute: ${raw}`);
}
if (input.alias !== undefined && typeof input.alias !== "string") {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, "alias must be a string");
}
if (input.trust !== undefined && typeof input.trust !== "boolean") {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, "trust must be a boolean");
}
const roots = this.allowlist();
let real: string;
try {
real = realpathSync(raw);
} catch (error) {
throw mapFsError(error, raw);
}
// Check the canonical path: symlinks inside the allowlist must not escape it.
this.assertAllowed(real, roots);
let stat;
try {
stat = statSync(real);
} catch (error) {
throw mapFsError(error, real);
}
if (!stat.isDirectory()) {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, `not a directory: ${real}`);
}
try {
accessSync(real, constants.R_OK | constants.W_OK | constants.X_OK);
} catch (error) {
throw new WorkspaceError(ERROR_CODES.FORBIDDEN, `directory is not readable and writable: ${real}`, false, {
cause: error,
});
}
await this.registry.ensureForCwd(real);
const patch: WorkspacePatch = {};
if (input.alias !== undefined) {
const alias = input.alias.trim();
patch.alias = alias.length > 0 ? alias : null;
}
if (input.trust !== undefined) patch.trusted = input.trust;
if (Object.keys(patch).length > 0) {
await this.registry.update(workspaceIdForCwd(real), patch);
}
return this.requireInfo(workspaceIdForCwd(real));
}
async update(workspaceId: string, patch: WorkspacePatch): Promise<WorkspaceInfo> {
if (typeof workspaceId !== "string" || workspaceId.length === 0) {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, "workspaceId is required");
}
validatePatch(patch);
let record = this.registry.get(workspaceId);
if (!record) {
const discovered = this.discoveredById().get(workspaceId);
if (!discovered) {
throw new WorkspaceError(ERROR_CODES.NOT_FOUND, `unknown workspace: ${workspaceId}`);
}
// Ghost workspaces have no directory to realpath, but user intent
// (pin/hide/trust) must still be persistable.
record = await this.registry.ensureForCwd(discovered.cwd, { allowMissing: true });
}
await this.registry.update(record.workspaceId, patch);
return this.requireInfo(record.workspaceId);
}
async remove(workspaceId: string): Promise<void> {
if (typeof workspaceId !== "string" || workspaceId.length === 0) {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, "workspaceId is required");
}
// Registry only: session files are never touched. Discovered-only
// workspaces simply have nothing to remove.
await this.registry.remove(workspaceId);
}
async refresh(workspaceId?: string): Promise<void> {
if (workspaceId === undefined) {
this.discovery.invalidate();
} else {
const cwd = this.registry.get(workspaceId)?.entry.cwd;
const dir = (cwd ? this.discovery.dirForCwd(cwd) : undefined) ?? this.discoveredById().get(workspaceId)?.dir;
if (dir) this.discovery.invalidate(dir);
else this.discovery.invalidate();
}
// Pick up external edits to workspaces.json as well as session files.
this.registry.load();
}
async ensureForCwd(cwd: string): Promise<WorkspaceInfo> {
const record = await this.registry.ensureForCwd(cwd);
return this.requireInfo(record.workspaceId);
}
// ------------------------------------------------------------------
private requireInfo(workspaceId: string): WorkspaceInfo {
const info = this.get(workspaceId);
if (!info) {
throw new WorkspaceError(ERROR_CODES.INTERNAL, `workspace disappeared after write: ${workspaceId}`);
}
return info;
}
private discoveredById(): Map<string, DiscoveredWorkspace> {
const merged = new Map<string, DiscoveredWorkspace>();
let entries: DiscoveredWorkspace[];
try {
entries = this.discovery.discover();
} catch (error) {
this.logger?.warn("workspace discovery failed", {
error: error instanceof Error ? error.message : String(error),
});
return merged;
}
for (const entry of entries) {
const previous = merged.get(entry.workspaceId);
if (!previous) {
merged.set(entry.workspaceId, { ...entry });
continue;
}
// Two encoded directories can resolve to the same canonical cwd.
const lastActiveAt =
previous.lastActiveAt === null
? entry.lastActiveAt
: entry.lastActiveAt === null
? previous.lastActiveAt
: Math.max(previous.lastActiveAt, entry.lastActiveAt);
merged.set(entry.workspaceId, {
...previous,
sessionCount: previous.sessionCount + entry.sessionCount,
lastActiveAt,
exists: previous.exists || entry.exists,
// Prefer the directory with more sessions for listSessions().
dir: entry.sessionCount > previous.sessionCount ? entry.dir : previous.dir,
cwd: entry.sessionCount > previous.sessionCount ? entry.cwd : previous.cwd,
});
}
return merged;
}
private buildInfo(
workspaceId: string,
entry: WorkspaceEntry | undefined,
discovered: DiscoveredWorkspace | undefined,
views: InstanceViews,
): WorkspaceInfo {
const cwd = entry?.cwd ?? discovered?.cwd ?? "";
const alias = entry?.alias ?? null;
return {
workspaceId,
cwd,
name: alias ?? (basename(cwd) || cwd),
alias,
pinned: entry?.pinned ?? false,
hidden: entry?.hidden ?? false,
trusted: entry?.trusted ?? false,
exists: discovered?.exists ?? isDirectory(cwd),
sessionCount: discovered?.sessionCount ?? 0,
liveCount: views.live.get(workspaceId) ?? 0,
lastActiveAt: discovered?.lastActiveAt ?? null,
instance: views.instances.get(workspaceId) ?? null,
};
}
private instanceViews(): InstanceViews {
const instances = new Map<string, InstanceState>();
const live = new Map<string, number>();
const listed = this.callInstances("list");
const states = this.callInstances("instanceStates") ?? listed ?? [];
for (const state of listed ?? states) {
if (state && typeof state.workspaceId === "string") instances.set(state.workspaceId, state);
}
for (const state of states) {
if (!state || typeof state.workspaceId !== "string") continue;
const count = liveCountOf(state);
live.set(state.workspaceId, Math.max(live.get(state.workspaceId) ?? 0, count));
}
return { instances, live };
}
private callInstances(method: "list" | "instanceStates"): InstanceState[] | undefined {
if (!this.instances) return undefined;
try {
const fn = this.instances[method];
const result = fn.call(this.instances);
return Array.isArray(result) ? result : [];
} catch (error) {
this.logger?.warn(`instance manager ${method}() failed`, {
error: error instanceof Error ? error.message : String(error),
});
return undefined;
}
}
private allowlist(): string[] {
const configured = this.roots;
if (configured !== undefined) {
return configured.map((root) => canonicalRoot(root)).filter((root): root is string => root.length > 0);
}
return rootsFromEnv(process.env.PI2_WORKSPACE_ROOTS);
}
private assertAllowed(candidate: string, roots: readonly string[]): void {
if (roots.some((root) => isWithin(root, candidate))) return;
throw new WorkspaceError(
ERROR_CODES.FORBIDDEN,
`workspace path is outside the allowed roots: ${candidate}`,
);
}
}
export function createWorkspaceStore(options: WorkspaceStoreOptions = {}): WorkspaceStoreHandle {
return new WorkspaceStore(options);
}
export function rootsFromEnv(raw: string | undefined, fallback: string = homedir()): string[] {
const parts = (raw ?? "")
.split(",")
.map((part) => part.trim())
.filter((part) => part.length > 0);
if (parts.length === 0) parts.push(fallback);
return parts.map((part) => canonicalRoot(part)).filter((part) => part.length > 0);
}
/** Expand `~`, resolve relative roots against cwd, and canonicalise when possible. */
function canonicalRoot(root: string): string {
if (typeof root !== "string") return "";
let value = root.trim();
if (value.length === 0 || value.includes("\0")) return "";
if (value === "~") value = homedir();
else if (value.startsWith("~/")) value = join(homedir(), value.slice(2));
return realpathSafe(resolve(value));
}
function isWithin(root: string, candidate: string): boolean {
if (root.length === 0) return false;
const rel = relative(root, candidate);
if (rel === "") return true;
if (isAbsolute(rel)) return false;
return rel !== ".." && !rel.startsWith(`..${sep}`);
}
function isDirectory(path: string): boolean {
if (!path || !isAbsolute(path)) return false;
try {
return statSync(path).isDirectory();
} catch {
return false;
}
}
/** InstanceState does not (yet) declare sessions; support the shapes in the wild. */
function liveCountOf(state: InstanceState): number {
const extended = state as InstanceState & {
sessions?: unknown;
sessionCount?: unknown;
liveCount?: unknown;
};
if (Array.isArray(extended.sessions)) return extended.sessions.length;
if (typeof extended.sessionCount === "number" && Number.isFinite(extended.sessionCount)) {
return Math.max(0, extended.sessionCount);
}
if (typeof extended.sessions === "number" && Number.isFinite(extended.sessions)) {
return Math.max(0, extended.sessions);
}
if (typeof extended.liveCount === "number" && Number.isFinite(extended.liveCount)) {
return Math.max(0, extended.liveCount);
}
return 0;
}
function mapFsError(error: unknown, path: string): WorkspaceError {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
const detail = error instanceof Error ? error.message : String(error);
if (code === "ENOENT" || code === "ENOTDIR") {
return new WorkspaceError(ERROR_CODES.NOT_FOUND, `path does not exist: ${path}`, false, { cause: error });
}
if (code === "EACCES" || code === "EPERM") {
return new WorkspaceError(ERROR_CODES.FORBIDDEN, `path is not accessible: ${path}`, false, {
cause: error,
});
}
return new WorkspaceError(ERROR_CODES.BAD_REQUEST, `invalid path ${path}: ${detail}`, false, {
cause: error,
});
}
export { createDiscovery } from "./discovery.js";
export { WorkspaceError } from "./errors.js";
export {
canonicalizeCwd,
WorkspaceRegistry,
type WorkspaceEntry,
type WorkspacePatch,
type WorkspaceRecord,
} from "./registry.js";
export type { DiscoveredWorkspace, Discovery, SessionFile } from "./discovery.js";
+343
View File
@@ -0,0 +1,343 @@
/**
* Durable workspace registry (`${dataDir()}/workspaces.json`).
*
* The registry stores user intent (alias, pin, hidden, trust) keyed by the
* canonical `workspaceId = sha256(realpath(cwd)).slice(0, 16)`. Disk discovery
* is deliberately kept separate: the registry never scans session files.
*
* The file is written atomically (tmp file + rename) with mode 0600. A corrupt
* file is moved aside to `workspaces.json.bak` and the registry starts empty.
*/
import { randomUUID } from "node:crypto";
import { readFileSync, realpathSync, renameSync } from "node:fs";
import { chmod, mkdir, open, rename, rm } from "node:fs/promises";
import { basename, dirname, isAbsolute, join } from "node:path";
import { z } from "zod";
import { dataDir, realpathSafe, workspaceIdForCwd } from "../core/paths.js";
import { ERROR_CODES } from "../protocol/errors.js";
import { WorkspaceError } from "./errors.js";
export { WorkspaceError } from "./errors.js";
const entrySchema = z.object({
cwd: z.string().min(1),
alias: z.string().min(1).optional(),
pinned: z.boolean(),
hidden: z.boolean(),
trusted: z.boolean(),
createdAt: z.number(),
updatedAt: z.number(),
});
const fileSchema = z.object({
version: z.literal(1),
workspaces: z.record(entrySchema),
});
export interface WorkspaceEntry {
cwd: string;
alias?: string;
pinned: boolean;
hidden: boolean;
trusted: boolean;
createdAt: number;
updatedAt: number;
}
export interface WorkspaceRecord {
workspaceId: string;
entry: WorkspaceEntry;
}
export type WorkspacePatch = Partial<{
alias: string | null;
pinned: boolean;
hidden: boolean;
trusted: boolean;
}>;
export interface RegistryLogger {
warn(msg: string, fields?: Record<string, unknown>): void;
debug?(msg: string, fields?: Record<string, unknown>): void;
}
export interface RegistryOptions {
/** Defaults to `${dataDir()}/workspaces.json`. */
filePath?: string;
logger?: RegistryLogger;
now?: () => number;
}
/**
* Canonicalise a cwd; rejects relative paths. Missing directories throw unless
* `allowMissing` is set (used when persisting metadata for a ghost workspace).
*/
export function canonicalizeCwd(cwd: string, options: { allowMissing?: boolean } = {}): string {
if (typeof cwd !== "string" || cwd.trim().length === 0) {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, "cwd must be a non-empty string");
}
if (cwd.includes("\0")) {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, "cwd contains a NUL byte");
}
if (!isAbsolute(cwd)) {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, `cwd must be absolute: ${cwd}`);
}
if (options.allowMissing) return realpathSafe(cwd);
try {
return realpathSync(cwd);
} catch (error) {
throw mapFsError(error, cwd);
}
}
function mapFsError(error: unknown, cwd: string): WorkspaceError {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
const detail = error instanceof Error ? error.message : String(error);
if (code === "ENOENT" || code === "ENOTDIR") {
return new WorkspaceError(ERROR_CODES.NOT_FOUND, `cwd does not exist: ${cwd}`, false, { cause: error });
}
if (code === "EACCES" || code === "EPERM") {
return new WorkspaceError(ERROR_CODES.FORBIDDEN, `cwd is not accessible: ${cwd}`, false, {
cause: error,
});
}
return new WorkspaceError(ERROR_CODES.BAD_REQUEST, `invalid cwd ${cwd}: ${detail}`, false, {
cause: error,
});
}
function cloneEntry(entry: WorkspaceEntry): WorkspaceEntry {
return { ...entry };
}
function isErrno(error: unknown): NodeJS.ErrnoException {
return error as NodeJS.ErrnoException;
}
export class WorkspaceRegistry {
readonly filePath: string;
private readonly logger: RegistryLogger | undefined;
private readonly now: () => number;
private readonly entries = new Map<string, WorkspaceEntry>();
/** Serialises writes so concurrent CRUD calls cannot interleave renames. */
private saveChain: Promise<void> = Promise.resolve();
constructor(options: RegistryOptions = {}) {
this.filePath = options.filePath ?? join(dataDir(), "workspaces.json");
this.logger = options.logger;
this.now = options.now ?? Date.now;
this.load();
}
/** (Re)load from disk. Corrupt content is backed up and treated as empty. */
load(): void {
this.entries.clear();
let raw: string;
try {
raw = readFileSync(this.filePath, "utf8");
} catch (error) {
if (isErrno(error).code === "ENOENT") return;
this.handleCorrupt(`read failed: ${isErrno(error).message}`);
return;
}
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch (error) {
this.handleCorrupt(`invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
return;
}
const result = fileSchema.safeParse(parsed);
if (!result.success) {
this.handleCorrupt(result.error.issues.map((issue) => issue.message).join("; "));
return;
}
for (const [workspaceId, entry] of Object.entries(result.data.workspaces)) {
this.entries.set(workspaceId, cloneEntry(entry));
}
}
list(): WorkspaceRecord[] {
return [...this.entries].map(([workspaceId, entry]) => ({
workspaceId,
entry: cloneEntry(entry),
}));
}
get(workspaceId: string): WorkspaceRecord | undefined {
const entry = this.entries.get(workspaceId);
return entry ? { workspaceId, entry: cloneEntry(entry) } : undefined;
}
byCwd(cwd: string): WorkspaceRecord | undefined {
if (typeof cwd !== "string" || !isAbsolute(cwd)) return undefined;
const id = workspaceIdForCwd(cwd);
const direct = this.get(id);
if (direct) return direct;
const canonical = realpathSafe(cwd);
for (const [workspaceId, entry] of this.entries) {
if (entry.cwd === cwd || entry.cwd === canonical) {
return { workspaceId, entry: cloneEntry(entry) };
}
}
return undefined;
}
/**
* Return the record for a cwd, creating it when absent. Idempotent:
* `createdAt` and all user metadata are preserved for existing entries.
*/
async ensureForCwd(cwd: string, options: { allowMissing?: boolean } = {}): Promise<WorkspaceRecord> {
const canonical = canonicalizeCwd(cwd, options);
const workspaceId = workspaceIdForCwd(canonical);
const existing = this.entries.get(workspaceId);
if (existing) return { workspaceId, entry: cloneEntry(existing) };
const timestamp = this.now();
const entry: WorkspaceEntry = {
cwd: canonical,
pinned: false,
hidden: false,
trusted: false,
createdAt: timestamp,
updatedAt: timestamp,
};
this.entries.set(workspaceId, entry);
await this.persist();
return { workspaceId, entry: cloneEntry(entry) };
}
async update(workspaceId: string, patch: WorkspacePatch): Promise<WorkspaceRecord> {
validatePatch(patch);
const entry = this.entries.get(workspaceId);
if (!entry) {
throw new WorkspaceError(ERROR_CODES.NOT_FOUND, `unknown workspace: ${workspaceId}`);
}
if (patch.alias !== undefined) {
const alias = patch.alias === null ? "" : patch.alias.trim();
if (alias.length === 0) delete entry.alias;
else entry.alias = alias;
}
if (patch.pinned !== undefined) entry.pinned = patch.pinned;
if (patch.hidden !== undefined) entry.hidden = patch.hidden;
if (patch.trusted !== undefined) entry.trusted = patch.trusted;
entry.updatedAt = this.now();
await this.persist();
return { workspaceId, entry: cloneEntry(entry) };
}
/** Removes the registry entry only; session files on disk are untouched. */
async remove(workspaceId: string): Promise<boolean> {
const existed = this.entries.delete(workspaceId);
if (existed) await this.persist();
return existed;
}
/** Force a write of the current in-memory registry. */
async save(): Promise<void> {
await this.persist();
}
private persist(): Promise<void> {
const next = this.saveChain.then(() => this.writeFile());
// Keep the chain alive after a failed write; callers still see the error.
this.saveChain = next.catch(() => undefined);
return next;
}
private async writeFile(): Promise<void> {
const payload = {
version: 1 as const,
workspaces: Object.fromEntries(
[...this.entries].map(([workspaceId, entry]) => [workspaceId, cloneEntry(entry)]),
),
};
const data = `${JSON.stringify(payload, null, 2)}\n`;
const dir = dirname(this.filePath);
const tmp = join(dir, `.${basename(this.filePath)}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`);
try {
await mkdir(dir, { recursive: true, mode: 0o700 });
const handle = await open(tmp, "w", 0o600);
try {
await handle.writeFile(data, "utf8");
await handle.sync();
} finally {
await handle.close();
}
await chmod(tmp, 0o600);
await rename(tmp, this.filePath);
// A rename replaces the inode, but enforce the mode even on odd umasks.
await chmod(this.filePath, 0o600);
} catch (error) {
await rm(tmp, { force: true }).catch(() => undefined);
throw new WorkspaceError(
ERROR_CODES.INTERNAL,
`failed to write workspace registry ${this.filePath}: ${
error instanceof Error ? error.message : String(error)
}`,
false,
{ cause: error },
);
}
}
private handleCorrupt(reason: string): void {
this.entries.clear();
const backup = `${this.filePath}.bak`;
let backedUp = false;
try {
// rename replaces an existing backup on POSIX.
renameSync(this.filePath, backup);
backedUp = true;
} catch (error) {
// Best effort: still start empty even if the backup could not be made.
this.logger?.warn("could not back up corrupt workspace registry", {
file: this.filePath,
backup,
reason: error instanceof Error ? error.message : String(error),
});
}
const message = "workspace registry is corrupt; starting empty";
if (this.logger) {
this.logger.warn(message, {
file: this.filePath,
backup: backedUp ? backup : null,
reason,
});
} else {
console.warn(`[workspaces] ${message}`, { file: this.filePath, backup: backedUp ? backup : null, reason });
}
}
}
export function validatePatch(patch: WorkspacePatch): void {
if (!patch || typeof patch !== "object" || Array.isArray(patch)) {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, "workspace patch must be an object");
}
const allowed = new Set(["alias", "pinned", "hidden", "trusted"]);
for (const key of Object.keys(patch)) {
if (!allowed.has(key)) {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, `unknown workspace field: ${key}`);
}
}
if (patch.alias !== undefined && patch.alias !== null && typeof patch.alias !== "string") {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, "alias must be a string or null");
}
for (const key of ["pinned", "hidden", "trusted"] as const) {
const value = patch[key];
if (value !== undefined && typeof value !== "boolean") {
throw new WorkspaceError(ERROR_CODES.BAD_REQUEST, `${key} must be a boolean`);
}
}
}
+240
View File
@@ -0,0 +1,240 @@
import { mkdirSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { workspaceIdForCwd } from "../../src/core/paths.js";
import { createDiscovery } from "../../src/workspaces/discovery.js";
import { cleanup, encodedDirName, makeSandbox, sessionHeader, writeSessionDir } from "./helpers.js";
describe("workspace disk discovery", () => {
let sandbox: string;
let root: string;
beforeEach(() => {
sandbox = makeSandbox("pi2d-discovery-");
root = join(sandbox, "agent", "sessions");
mkdirSync(root, { recursive: true });
});
afterEach(() => cleanup(sandbox));
it("returns nothing when the sessions root is missing", () => {
const discovery = createDiscovery({ root: join(sandbox, "nope") });
expect(discovery.discover()).toEqual([]);
expect(discovery.listSessions("/tmp")).toEqual([]);
});
it("uses the header cwd as authoritative for dashed and unicode paths", () => {
// A path where '-' is both a literal path character and the encoded separator.
const project = join(sandbox, "weird-dir", "日本語", "sub-dir");
mkdirSync(project, { recursive: true });
// Deliberately misleading directory name: it cannot be reversed.
writeSessionDir(root, "--definitely-not-weird-dir--", [
{ name: "2026-10-10T06-40-33-032Z_a.jsonl", cwd: project, id: "session-a" },
]);
const [entry] = createDiscovery({ root }).discover();
expect(entry).toMatchObject({
cwd: project,
workspaceId: workspaceIdForCwd(project),
sessionCount: 1,
exists: true,
dir: join(root, "--definitely-not-weird-dir--"),
});
expect(entry?.lastActiveAt).toBeTypeOf("number");
});
it("selects the newest file by mtime, not by file name", () => {
const oldProject = join(sandbox, "old-project");
const newProject = join(sandbox, "new-project");
mkdirSync(oldProject);
mkdirSync(newProject);
writeSessionDir(root, encodedDirName(newProject), [
{
name: "2026-12-31T23-59-59-999Z_lexicographically-newest.jsonl",
cwd: oldProject,
id: "old",
mtime: new Date("2026-01-01T00:00:00.000Z"),
},
{
name: "2000-01-01T00-00-00-000Z_actually-newest.jsonl",
cwd: newProject,
id: "new",
mtime: new Date("2026-06-01T00:00:00.000Z"),
},
]);
const [entry] = createDiscovery({ root }).discover();
expect(entry?.cwd).toBe(newProject);
expect(entry?.sessionCount).toBe(2);
expect(entry?.lastActiveAt).toBe(Date.parse("2026-06-01T00:00:00.000Z"));
});
it("keeps ghost workspaces flagged instead of dropping them", () => {
const gone = join(sandbox, "deleted-project");
writeSessionDir(root, encodedDirName(gone), [
{ name: "2026-10-10T06-40-33-032Z_ghost.jsonl", cwd: gone, id: "ghost" },
]);
const [entry] = createDiscovery({ root }).discover();
expect(entry).toMatchObject({ cwd: gone, exists: false, sessionCount: 1 });
});
it("skips directories with no session files and ignores non-jsonl files", () => {
mkdirSync(join(root, "--empty--"));
writeSessionDir(root, "--only-noise--", []);
writeFileSync(join(root, "--only-noise--", "notes.txt"), "not a session");
writeSessionDir(root, "--real--", [
{ name: "2026-10-10T06-40-33-032Z_real.jsonl", cwd: sandbox, id: "real" },
]);
expect(createDiscovery({ root }).discover()).toHaveLength(1);
});
it("never parses past the first line", () => {
const dir = writeSessionDir(root, encodedDirName(sandbox), [
{
name: "2026-10-10T06-40-33-032Z_header.jsonl",
cwd: sandbox,
id: "header",
body: "this is not json at all\n{}]\n",
},
]);
const discovery = createDiscovery({ root });
expect(discovery.discover()[0]?.cwd).toBe(sandbox);
expect(discovery.listSessions(sandbox)[0]?.id).toBe("header");
expect(statSync(join(dir, "2026-10-10T06-40-33-032Z_header.jsonl")).isFile()).toBe(true);
});
it("serves a cache hit without re-reading the header", () => {
const dir = writeSessionDir(root, encodedDirName(sandbox), [
{ name: "2026-10-10T06-40-33-032Z_cached.jsonl", cwd: sandbox, id: "cached" },
]);
const file = join(dir, "2026-10-10T06-40-33-032Z_cached.jsonl");
const discovery = createDiscovery({ root });
expect(discovery.discover()[0]?.cwd).toBe(sandbox);
// Corrupt the header in place (directory mtime and file count unchanged).
writeFileSync(file, `${JSON.stringify({ type: "not-a-session", cwd: "/definitely/wrong" })}\n`);
// Still served from cache: the header was not read again.
expect(discovery.discover()[0]?.cwd).toBe(sandbox);
// Explicit invalidation forces a re-read and the header is now unusable.
discovery.invalidate();
expect(discovery.discover()).toEqual([]);
});
it("detects newly created session files via the directory signature", () => {
const dir = writeSessionDir(root, encodedDirName(sandbox), [
{ name: "2026-10-10T06-40-33-032Z_one.jsonl", cwd: sandbox, id: "one" },
]);
const discovery = createDiscovery({ root });
expect(discovery.discover()[0]?.sessionCount).toBe(1);
writeFileSync(
join(dir, "2026-10-11T06-40-33-032Z_two.jsonl"),
`${sessionHeader(sandbox, "two")}\n`,
);
expect(discovery.discover()[0]?.sessionCount).toBe(2);
expect(discovery.listSessions(sandbox)).toHaveLength(2);
});
it("invalidates a single directory when asked", () => {
const other = join(sandbox, "other");
mkdirSync(other);
const dirA = writeSessionDir(root, encodedDirName(sandbox), [
{ name: "2026-10-10T06-40-33-032Z_a.jsonl", cwd: sandbox, id: "a" },
]);
writeSessionDir(root, encodedDirName(other), [
{ name: "2026-10-10T06-40-33-032Z_b.jsonl", cwd: other, id: "b" },
]);
const discovery = createDiscovery({ root });
expect(discovery.discover()).toHaveLength(2);
discovery.invalidate(dirA);
// Both still discoverable; the cache entry for A was dropped and rebuilt.
expect(discovery.discover()).toHaveLength(2);
});
it("lists sessions from the header only, newest first", () => {
const dir = writeSessionDir(root, encodedDirName(sandbox), [
{
name: "2026-01-01T00-00-00-000Z_old.jsonl",
cwd: sandbox,
id: "header-old",
timestamp: "2026-01-01T00:00:00.000Z",
mtime: new Date("2026-01-02T00:00:00.000Z"),
body: "garbage that must never be parsed\n",
},
{
name: "2026-02-02T00-00-00-000Z_new.jsonl",
cwd: sandbox,
id: "header-new",
timestamp: "2026-02-02T00:00:00.000Z",
mtime: new Date("2026-02-03T00:00:00.000Z"),
},
]);
const sessions = createDiscovery({ root }).listSessions(sandbox);
expect(sessions.map((s) => s.id)).toEqual(["header-new", "header-old"]);
expect(sessions[0]).toMatchObject({
file: join(dir, "2026-02-02T00-00-00-000Z_new.jsonl"),
timestamp: Date.parse("2026-02-02T00:00:00.000Z"),
modified: Date.parse("2026-02-03T00:00:00.000Z"),
});
expect(sessions.every((s) => s.firstMessage === undefined)).toBe(true);
});
it("falls back to the file name when a header is unreadable", () => {
const dir = writeSessionDir(root, encodedDirName(sandbox), [
{ name: "2026-03-01T00-00-00-000Z_good.jsonl", cwd: sandbox, id: "good" },
]);
const broken = join(dir, "2026-03-04T05-06-07-008Z_fallback-id.jsonl");
writeFileSync(broken, "not a session header\n");
// Newer mtime so the fallback entry is first.
utimesSync(broken, new Date("2026-03-05T00:00:00.000Z"), new Date("2026-03-05T00:00:00.000Z"));
const sessions = createDiscovery({ root }).listSessions(sandbox);
expect(sessions).toHaveLength(2);
expect(sessions.find((s) => s.id === "fallback-id")).toMatchObject({
id: "fallback-id",
timestamp: Date.parse("2026-03-04T05:06:07.008Z"),
});
});
it("returns no sessions for unknown cwds", () => {
writeSessionDir(root, encodedDirName(sandbox), [
{ name: "2026-10-10T06-40-33-032Z_a.jsonl", cwd: sandbox, id: "a" },
]);
expect(createDiscovery({ root }).listSessions(join(sandbox, "unknown"))).toEqual([]);
});
it("defaults the root to PI_CODING_AGENT_DIR/sessions", () => {
const agent = join(sandbox, "custom-agent");
const sessions = join(agent, "sessions");
mkdirSync(sessions, { recursive: true });
writeSessionDir(sessions, encodedDirName(sandbox), [
{ name: "2026-10-10T06-40-33-032Z_env.jsonl", cwd: sandbox, id: "env" },
]);
const previous = process.env.PI_CODING_AGENT_DIR;
process.env.PI_CODING_AGENT_DIR = agent;
try {
expect(createDiscovery().discover()).toHaveLength(1);
} finally {
if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR;
else process.env.PI_CODING_AGENT_DIR = previous;
}
});
it("ignores a vanished directory gracefully", () => {
const dir = writeSessionDir(root, encodedDirName(sandbox), [
{ name: "2026-10-10T06-40-33-032Z_a.jsonl", cwd: sandbox, id: "a" },
]);
const discovery = createDiscovery({ root });
expect(discovery.discover()).toHaveLength(1);
rmSync(dir, { recursive: true, force: true });
discovery.invalidate();
expect(discovery.discover()).toEqual([]);
});
});
+48
View File
@@ -0,0 +1,48 @@
import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
export interface SessionSpec {
/** File name inside the encoded session directory. */
name: string;
/** cwd written into the session header (authoritative). */
cwd: string;
id?: string;
timestamp?: string;
/** Extra JSONL lines appended after the header (never parsed by discovery). */
body?: string;
/** File mtime, used to test newest-file selection. */
mtime?: Date | number;
}
export function makeSandbox(prefix = "pi2d-ws-"): string {
return mkdtempSync(join(tmpdir(), prefix));
}
export function cleanup(dir: string | undefined): void {
if (dir) rmSync(dir, { recursive: true, force: true });
}
/** Mimics pi's `--<cwd with slashes replaced by dashes>--` directory naming. */
export function encodedDirName(cwd: string): string {
return `--${cwd.replace(/^\/+/, "").replace(/\//g, "-")}--`;
}
export function sessionHeader(cwd: string, id: string, timestamp = "2026-10-10T06:40:33.032Z"): string {
return JSON.stringify({ type: "session", version: 3, id, timestamp, cwd });
}
/** Creates an encoded sessions directory with real-looking JSONL files. */
export function writeSessionDir(root: string, dirName: string, files: SessionSpec[]): string {
const dir = join(root, dirName);
mkdirSync(dir, { recursive: true });
for (const file of files) {
const id = file.id ?? "01a00000-0000-7000-8000-000000000000";
const timestamp = file.timestamp ?? "2026-10-10T06:40:33.032Z";
const body = file.body ?? '{"type":"message","id":"m1","message":{"role":"user","content":"hi"}}\n';
const path = join(dir, file.name);
writeFileSync(path, `${sessionHeader(file.cwd, id, timestamp)}\n${body}`);
if (file.mtime !== undefined) utimesSync(path, file.mtime, file.mtime);
}
return dir;
}
+177
View File
@@ -0,0 +1,177 @@
import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { workspaceIdForCwd } from "../../src/core/paths.js";
import { WorkspaceError, WorkspaceRegistry } from "../../src/workspaces/registry.js";
import { cleanup, makeSandbox } from "./helpers.js";
describe("workspace registry", () => {
let sandbox: string;
let file: string;
let project: string;
beforeEach(() => {
sandbox = makeSandbox("pi2d-registry-");
file = join(sandbox, "data", "workspaces.json");
project = join(sandbox, "project");
mkdirSync(project, { recursive: true });
});
afterEach(() => cleanup(sandbox));
it("defaults to dataDir()/workspaces.json", async () => {
const previous = process.env.PI2_DATA_DIR;
process.env.PI2_DATA_DIR = join(sandbox, "xdg-data");
try {
const registry = new WorkspaceRegistry();
await registry.ensureForCwd(project);
expect(registry.filePath).toBe(join(sandbox, "xdg-data", "workspaces.json"));
expect(existsSync(registry.filePath)).toBe(true);
} finally {
if (previous === undefined) delete process.env.PI2_DATA_DIR;
else process.env.PI2_DATA_DIR = previous;
}
});
it("serialises concurrent writes without losing entries", async () => {
const other = join(sandbox, "other");
mkdirSync(other);
const registry = new WorkspaceRegistry({ filePath: file });
await Promise.all([registry.ensureForCwd(project), registry.ensureForCwd(other)]);
expect(registry.list()).toHaveLength(2);
expect(new WorkspaceRegistry({ filePath: file }).list()).toHaveLength(2);
});
it("starts empty when the file does not exist", () => {
const registry = new WorkspaceRegistry({ filePath: file });
expect(registry.list()).toEqual([]);
expect(registry.get("nope")).toBeUndefined();
});
it("writes atomically with mode 0600 and leaves no temp files behind", async () => {
const registry = new WorkspaceRegistry({ filePath: file });
const record = await registry.ensureForCwd(project);
expect(existsSync(file)).toBe(true);
expect(statSync(file).mode & 0o777).toBe(0o600);
expect(readdirSync(join(sandbox, "data")).filter((n) => n.includes(".tmp"))).toEqual([]);
const parsed = JSON.parse(readFileSync(file, "utf8")) as {
version: number;
workspaces: Record<string, { cwd: string; trusted: boolean }>;
};
expect(parsed.version).toBe(1);
expect(parsed.workspaces[record.workspaceId]?.cwd).toBe(record.entry.cwd);
expect(parsed.workspaces[record.workspaceId]?.trusted).toBe(false);
});
it("forces 0600 even when a pre-existing file was world readable", async () => {
const registry = new WorkspaceRegistry({ filePath: file });
await registry.ensureForCwd(project);
chmodSync(file, 0o644);
expect(statSync(file).mode & 0o777).toBe(0o644);
await registry.update(workspaceIdForCwd(project), { pinned: true });
expect(statSync(file).mode & 0o777).toBe(0o600);
});
it("backs up a corrupt registry and starts empty", () => {
mkdirSync(join(sandbox, "data"), { recursive: true });
const corrupt = '{"version":1,"workspaces":{"broken":';
writeFileSync(file, corrupt);
const warnings: string[] = [];
const registry = new WorkspaceRegistry({
filePath: file,
logger: { warn: (msg) => warnings.push(msg) },
});
expect(registry.list()).toEqual([]);
expect(readFileSync(`${file}.bak`, "utf8")).toBe(corrupt);
expect(warnings.some((w) => w.includes("corrupt"))).toBe(true);
});
it("rejects malformed-but-valid JSON as corrupt", () => {
mkdirSync(join(sandbox, "data"), { recursive: true });
writeFileSync(file, JSON.stringify({ version: 2, workspaces: {} }));
const registry = new WorkspaceRegistry({ filePath: file });
expect(registry.list()).toEqual([]);
expect(existsSync(`${file}.bak`)).toBe(true);
});
it("supports CRUD and persists across instances", async () => {
const registry = new WorkspaceRegistry({ filePath: file });
const real = await registry.ensureForCwd(project);
expect(real.workspaceId).toBe(workspaceIdForCwd(project));
expect(real.entry.createdAt).toBeGreaterThan(0);
const byCwd = registry.byCwd(project);
expect(byCwd?.workspaceId).toBe(real.workspaceId);
const updated = await registry.update(real.workspaceId, {
alias: " My Project ",
pinned: true,
hidden: true,
trusted: true,
});
expect(updated.entry).toMatchObject({
alias: "My Project",
pinned: true,
hidden: true,
trusted: true,
});
const reloaded = new WorkspaceRegistry({ filePath: file });
expect(reloaded.get(real.workspaceId)?.entry).toMatchObject({
cwd: real.entry.cwd,
alias: "My Project",
pinned: true,
hidden: true,
trusted: true,
});
const cleared = await reloaded.update(real.workspaceId, { alias: null });
expect(cleared.entry.alias).toBeUndefined();
await reloaded.remove(real.workspaceId);
expect(reloaded.get(real.workspaceId)).toBeUndefined();
expect(new WorkspaceRegistry({ filePath: file }).list()).toEqual([]);
});
it("does not change createdAt or duplicate entries on repeated ensureForCwd", async () => {
const registry = new WorkspaceRegistry({ filePath: file });
const first = await registry.ensureForCwd(project);
const second = await registry.ensureForCwd(project);
expect(second.workspaceId).toBe(first.workspaceId);
expect(second.entry.createdAt).toBe(first.entry.createdAt);
expect(registry.list()).toHaveLength(1);
});
it("rejects relative and missing cwds", async () => {
const registry = new WorkspaceRegistry({ filePath: file });
await expect(registry.ensureForCwd("relative/path")).rejects.toBeInstanceOf(WorkspaceError);
await expect(registry.ensureForCwd("relative/path")).rejects.toMatchObject({ code: "E_BAD_REQUEST" });
await expect(registry.ensureForCwd(join(sandbox, "missing"))).rejects.toMatchObject({
code: "E_NOT_FOUND",
});
expect(registry.list()).toEqual([]);
});
it("canonicalises symlinks to one workspace", async () => {
const { symlinkSync, realpathSync } = await import("node:fs");
const link = join(sandbox, "link");
symlinkSync(project, link);
const registry = new WorkspaceRegistry({ filePath: file });
const a = await registry.ensureForCwd(project);
const b = await registry.ensureForCwd(link);
expect(b.workspaceId).toBe(a.workspaceId);
expect(b.entry.cwd).toBe(realpathSync(project));
expect(registry.list()).toHaveLength(1);
});
});
+281
View File
@@ -0,0 +1,281 @@
import { existsSync, mkdirSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { workspaceIdForCwd } from "../../src/core/paths.js";
import type { InstanceManager } from "../../src/core/interfaces.js";
import type { InstanceState } from "../../src/protocol/types.js";
import { createDiscovery } from "../../src/workspaces/discovery.js";
import { createWorkspaceStore } from "../../src/workspaces/index.js";
import { WorkspaceRegistry } from "../../src/workspaces/registry.js";
import { cleanup, encodedDirName, makeSandbox, sessionHeader, writeSessionDir } from "./helpers.js";
type FakeInstanceState = InstanceState & { sessions?: unknown[]; sessionCount?: number };
function fakeInstances(listed: FakeInstanceState[], connected = listed): InstanceManager {
return {
list: () => listed,
instanceStates: () => connected,
} as unknown as InstanceManager;
}
function instance(workspaceId: string, overrides: Partial<FakeInstanceState> = {}): FakeInstanceState {
return {
workspaceId,
instanceId: `i-${workspaceId.slice(0, 4)}`,
status: "ready",
nvimPid: 4242,
pluginVersion: "1.8.0",
hasUI: true,
attachedClients: 1,
listenAddr: null,
startedAt: Date.now(),
...overrides,
};
}
describe("workspace store", () => {
let sandbox: string;
let sessions: string;
let dataFile: string;
let allowRoot: string;
let projectA: string;
let projectB: string;
let projectGhost: string;
beforeEach(() => {
sandbox = makeSandbox("pi2d-store-");
sessions = join(sandbox, "agent", "sessions");
dataFile = join(sandbox, "data", "workspaces.json");
allowRoot = join(sandbox, "code");
projectA = join(allowRoot, "alpha");
projectB = join(allowRoot, "beta");
projectGhost = join(allowRoot, "ghost");
for (const dir of [sessions, allowRoot, projectA, projectB, projectGhost]) mkdirSync(dir, { recursive: true });
writeSessionDir(sessions, encodedDirName(projectA), [
{ name: "2026-10-10T06-40-33-032Z_a1.jsonl", cwd: projectA, id: "a1" },
{ name: "2026-10-11T06-40-33-032Z_a2.jsonl", cwd: projectA, id: "a2" },
]);
writeSessionDir(sessions, encodedDirName(projectB), [
{ name: "2026-10-12T06-40-33-032Z_b1.jsonl", cwd: projectB, id: "b1" },
]);
writeSessionDir(sessions, encodedDirName(projectGhost), [
{ name: "2026-10-13T06-40-33-032Z_g1.jsonl", cwd: projectGhost, id: "g1" },
]);
rmSync(projectGhost, { recursive: true, force: true });
});
afterEach(() => cleanup(sandbox));
function setup(opts: Parameters<typeof createWorkspaceStore>[0] = {}) {
const discovery = createDiscovery({ root: sessions });
const registry = new WorkspaceRegistry({ filePath: dataFile });
const store = createWorkspaceStore({ discovery, registry, roots: [allowRoot], ...opts });
return { store, discovery, registry };
}
it("merges registry entries with disk discovery and instance state", async () => {
const aId = workspaceIdForCwd(projectA);
const { store, registry } = setup({
instances: fakeInstances([instance(aId, { sessions: [{}, {}, {}] })]),
});
await registry.ensureForCwd(projectA);
await store.update(aId, { alias: "Alpha", pinned: true, trusted: true });
const all = store.list();
expect(all).toHaveLength(3);
const a = store.get(aId);
expect(a).toMatchObject({
workspaceId: aId,
cwd: projectA,
name: "Alpha",
alias: "Alpha",
pinned: true,
hidden: false,
trusted: true,
exists: true,
sessionCount: 2,
liveCount: 3,
});
expect(a?.instance).toMatchObject({ workspaceId: aId, instanceId: `i-${aId.slice(0, 4)}` });
const b = store.byCwd(projectB);
expect(b).toMatchObject({
workspaceId: workspaceIdForCwd(projectB),
name: "beta",
alias: null,
trusted: false,
exists: true,
sessionCount: 1,
liveCount: 0,
instance: null,
});
const ghost = store.get(workspaceIdForCwd(projectGhost));
expect(ghost).toMatchObject({ exists: false, sessionCount: 1, lastActiveAt: expect.any(Number) });
});
it("keeps hidden entries in list(); the UI decides ordering", async () => {
const { store } = setup();
const bId = workspaceIdForCwd(projectB);
await store.update(bId, { hidden: true, pinned: true, alias: "Bee" });
expect(store.list().find((w) => w.workspaceId === bId)).toMatchObject({
hidden: true,
pinned: true,
alias: "Bee",
});
expect(store.get(bId)?.hidden).toBe(true);
});
it("adds existing, readable, writable directories inside the allowlist", async () => {
const { store, registry } = setup();
const info = await store.add({ cwd: projectA, alias: " Alpha ", trust: true });
expect(info).toMatchObject({
workspaceId: workspaceIdForCwd(projectA),
alias: "Alpha",
trusted: true,
pinned: false,
hidden: false,
});
expect(registry.list()).toHaveLength(1);
const again = await store.add({ cwd: projectA, alias: "Renamed" });
expect(again.workspaceId).toBe(info.workspaceId);
expect(again.alias).toBe("Renamed");
expect(again.trusted).toBe(true);
expect(registry.list()).toHaveLength(1);
});
it("rejects paths outside the allowlist with E_FORBIDDEN", async () => {
const outside = join(sandbox, "outside");
mkdirSync(outside);
const { store } = setup();
await expect(store.add({ cwd: outside })).rejects.toMatchObject({
code: "E_FORBIDDEN",
name: "WorkspaceError",
});
await expect(store.add({ cwd: sandbox })).rejects.toMatchObject({ code: "E_FORBIDDEN" });
});
it("rejects symlinks that escape the allowlist", async () => {
const outside = join(sandbox, "outside");
mkdirSync(outside);
const link = join(allowRoot, "escape");
symlinkSync(outside, link);
const { store } = setup();
await expect(store.add({ cwd: link })).rejects.toMatchObject({ code: "E_FORBIDDEN" });
});
it("honours PI2_WORKSPACE_ROOTS (comma separated) when no explicit roots are given", async () => {
const outside = join(sandbox, "outside");
mkdirSync(outside);
const previous = process.env.PI2_WORKSPACE_ROOTS;
process.env.PI2_WORKSPACE_ROOTS = `${join(sandbox, "nope")}, ${allowRoot}`;
try {
const { store } = setup({ roots: undefined });
await expect(store.add({ cwd: projectB })).resolves.toMatchObject({ cwd: projectB });
await expect(store.add({ cwd: outside })).rejects.toMatchObject({ code: "E_FORBIDDEN" });
} finally {
if (previous === undefined) delete process.env.PI2_WORKSPACE_ROOTS;
else process.env.PI2_WORKSPACE_ROOTS = previous;
}
});
it("validates relative, missing and non-directory paths", async () => {
const file = join(allowRoot, "file.txt");
writeFileSync(file, "x");
const { store } = setup();
await expect(store.add({ cwd: "relative/project" })).rejects.toMatchObject({ code: "E_BAD_REQUEST" });
await expect(store.add({ cwd: join(allowRoot, "missing") })).rejects.toMatchObject({
code: "E_NOT_FOUND",
});
await expect(store.add({ cwd: file })).rejects.toMatchObject({ code: "E_BAD_REQUEST" });
});
it("makes ensureForCwd idempotent without applying the allowlist (instance connects)", async () => {
const outside = join(sandbox, "outside");
mkdirSync(outside);
const { store, registry } = setup();
const first = await store.ensureForCwd(projectA);
const second = await store.ensureForCwd(projectA);
expect(second.workspaceId).toBe(first.workspaceId);
expect(registry.list()).toHaveLength(1);
const external = await store.ensureForCwd(outside);
expect(external.cwd).toBe(outside);
expect(external.trusted).toBe(false);
await expect(store.ensureForCwd("relative")).rejects.toMatchObject({ code: "E_BAD_REQUEST" });
});
it("updates discovered-only workspaces by registering them first", async () => {
const { store, registry } = setup();
const bId = workspaceIdForCwd(projectB);
expect(registry.get(bId)).toBeUndefined();
const updated = await store.update(bId, { pinned: true, trusted: true });
expect(updated).toMatchObject({ workspaceId: bId, pinned: true, trusted: true });
expect(registry.get(bId)?.entry.cwd).toBe(projectB);
await expect(store.update("0000000000000000", { pinned: true })).rejects.toMatchObject({
code: "E_NOT_FOUND",
});
});
it("removes only the registry entry and leaves session files on disk", async () => {
const { store, registry } = setup();
const info = await store.add({ cwd: projectA, alias: "Alpha", trust: true });
const sessionDir = join(sessions, encodedDirName(projectA));
expect(readdirSync(sessionDir)).toHaveLength(2);
await store.remove(info.workspaceId);
expect(registry.get(info.workspaceId)).toBeUndefined();
expect(existsSync(sessionDir)).toBe(true);
expect(readdirSync(sessionDir)).toHaveLength(2);
// The workspace reappears from disk discovery, but without registry metadata.
const after = store.get(info.workspaceId);
expect(after).toMatchObject({ exists: true, sessionCount: 2, trusted: false });
expect(after?.alias).toBeNull();
await expect(store.remove("0000000000000000")).resolves.toBeUndefined();
});
it("refresh() picks up new session files", async () => {
const { store } = setup();
const aId = workspaceIdForCwd(projectA);
expect(store.get(aId)?.sessionCount).toBe(2);
writeFileSync(
join(sessions, encodedDirName(projectA), "2026-10-14T06-40-33-032Z_a3.jsonl"),
`${sessionHeader(projectA, "a3")}\n`,
);
await store.refresh(aId);
expect(store.get(aId)?.sessionCount).toBe(3);
await store.refresh();
expect(store.list()).toHaveLength(3);
});
it("tolerates a missing instance manager", () => {
const { store } = setup({ instances: undefined });
expect(store.list().every((w) => w.liveCount === 0 && w.instance === null)).toBe(true);
});
it("counts live sessions from instanceStates() even when list() has a stopped instance", async () => {
const aId = workspaceIdForCwd(projectA);
const listed = [instance(aId, { status: "stopped" })];
const connected = [instance(aId, { sessionCount: 2 })];
const { store } = setup({ instances: fakeInstances(listed, connected) });
const info = store.get(aId);
expect(info?.instance).toMatchObject({ status: "stopped" });
expect(info?.liveCount).toBe(2);
});
});