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:
1 parent
ba3719fad9
commit
4e98ef8658
8 files changed
+1875
No files matched your search
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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";
|
||||
@@ -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`);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user