From b15f3ab43a9f3bbe47464cd1b5c475d768813a4a Mon Sep 17 00:00:00 2001 From: arumwu <75135621+arumwu@users.noreply.github.com> Date: Thu, 16 Jul 2026 06:33:02 +0800 Subject: [PATCH 1/2] Add multi-project workspace mode --- CONTRIBUTING.md | 2 +- README.md | 58 ++++++++++++++++++++++----------- SECURITY.md | 4 +-- examples/AGENTS.md | 8 ++--- package-lock.json | 4 +-- package.json | 2 +- src/cli.ts | 19 +++++++---- src/db.ts | 10 ++++++ src/git.ts | 66 +++++++++++++++++++++++++++++++------ src/index.ts | 8 ++++- src/mcp.ts | 21 ++++++++---- src/store.ts | 53 +++++++++++++++++++++--------- src/types.ts | 4 +++ tests/helpers.ts | 23 +++++++++++++ tests/workspace.test.ts | 72 +++++++++++++++++++++++++++++++++++++++++ 15 files changed, 288 insertions(+), 66 deletions(-) create mode 100644 tests/workspace.test.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5ffa269..914c8af 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -9,6 +9,6 @@ npm install npm run check ``` -Keep the v0.1 safety model intact: repository paths must remain fixed at server startup, Git calls must not use a shell or user-provided argument arrays, and new persistence paths must pass through redaction and sensitive-path filtering. +Keep the safety model intact: workspace paths must remain fixed at server startup, child working directories must remain inside that boundary, Git calls must not use a shell or user-provided argument arrays, and new persistence paths must pass through redaction and sensitive-path filtering. For behavior changes, add an integration test using a temporary Git repository. For new MCP tools, explain why the behavior cannot fit one of the existing ten tools; a small and predictable tool surface is a product constraint. diff --git a/README.md b/README.md index fb01e7d..ea65c0e 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,15 @@ # DevRelay -**DevRelay coordinates coding agents working on the same repository.** +**DevRelay coordinates coding agents working in the same repository or multi-project workspace.** It tracks active sessions, task leases, advisory file ownership, decisions, failed attempts, Git state, and handoffs so Codex, Claude Code, and other agents can continue each other's work without rebuilding context from scratch. > Not another chat memory. A local coordination layer for coding agents. -## What works in v0.1 +## What works in v0.2 -- Local-first SQLite storage inside the repository +- Local-first SQLite storage inside a repository or workspace +- Fixed non-Git workspace boundaries with child-repository Git context - MCP server with ten focused tools - Agent sessions and heartbeats - Expiring task leases @@ -52,11 +53,15 @@ Node.js 22.13 or newer is required. ## Quick start -Run these commands from any Git repository, or pass `--repo /absolute/path` before the subcommand. +Run these commands from a Git repository, or pin DevRelay to a larger workspace with `--repo /absolute/path` before the subcommand. ```bash -devrelay init -devrelay join --agent codex-01 --type codex --task "Implement OAuth callback" +devrelay --repo /workspaces/company init +devrelay --repo /workspaces/company join \ + --agent codex-01 \ + --type codex \ + --cwd products/api \ + --task "Implement OAuth callback" ``` The `join` command returns a session UUID. Use it for claims and event records: @@ -77,7 +82,7 @@ devrelay event \ --summary "Service account approach failed" \ --content "Normal user OAuth requires authorization-code flow" -devrelay context "Finish OAuth refresh flow" --budget 5000 +devrelay context "Finish OAuth refresh flow" --cwd products/api --budget 5000 devrelay handoff \ --session SESSION_UUID \ @@ -86,12 +91,12 @@ devrelay handoff \ ## Connect Codex -For a source checkout, register the built CLI and pin it to the repository the agents will coordinate: +For a source checkout, register the built CLI and pin it to the repository or workspace the agents will coordinate: ```bash codex mcp add devrelay -- \ node /absolute/path/to/devrelay/dist/cli.js \ - --repo /absolute/path/to/your/repository \ + --repo /absolute/path/to/your/workspace \ serve ``` @@ -103,7 +108,7 @@ command = "node" args = [ "/absolute/path/to/devrelay/dist/cli.js", "--repo", - "/absolute/path/to/your/repository", + "/absolute/path/to/your/workspace", "serve" ] ``` @@ -113,21 +118,37 @@ args = [ ```bash claude mcp add devrelay -- \ node /absolute/path/to/devrelay/dist/cli.js \ - --repo /absolute/path/to/your/repository \ + --repo /absolute/path/to/your/workspace \ serve ``` Then place the lifecycle rules from [`examples/AGENTS.md`](examples/AGENTS.md) in the repository's `AGENTS.md` or `CLAUDE.md`. +## Workspace mode + +A workspace may contain many independent Git repositories and non-Git projects: + +```text +/workspaces/company/ <- fixed DevRelay boundary +├── .devrelay/ <- shared workspace memory +├── products/api/.git/ +├── products/web/.git/ +└── research-notes/ +``` + +The MCP server remains fixed to `/workspaces/company`. Each `agent_join` and `build_context` call may include `working_directory`, such as `products/api`. DevRelay rejects directories outside the fixed workspace and obtains Git status from the child repository containing that working directory. + +Task and scope claims remain workspace-wide. In the example above, claim `products/api/src/**`, not only `src/**`, to avoid ambiguity between child projects. + ## MCP tools | Tool | Purpose | |---|---| -| `project_init` | Initialize or inspect project-local storage and its repository boundary | -| `agent_join` | Register an identified coding-agent session | +| `project_init` | Initialize or inspect workspace-local storage and its fixed boundary | +| `agent_join` | Register an agent session and its current workspace directory | | `agent_status` | Read coordination state and optionally heartbeat a session | | `claim_task` | Create or claim an expiring task lease | -| `claim_scope` | Claim repository-relative files or globs and receive overlap warnings | +| `claim_scope` | Claim workspace-relative files or globs and receive overlap warnings | | `record_event` | Record an attempt, result, issue, discovery, test, note, or completion | | `record_decision` | Record a structured decision and identify potential conflicts | | `search_memory` | Search events, decisions, and handoffs with SQLite FTS5 | @@ -136,7 +157,7 @@ Then place the lifecycle rules from [`examples/AGENTS.md`](examples/AGENTS.md) i ## Local data -Each coordinated repository owns its memory: +Each coordinated repository or workspace owns its memory: ```text .devrelay/ @@ -146,7 +167,7 @@ Each coordinated repository owns its memory: └── 2026-...-handoff.md ``` -`.devrelay/` is excluded from this repository's Git history by default. A team may choose to version redacted handoff exports, but the database should normally remain local. +`.devrelay/` is excluded from this repository's Git history by default. In a non-Git workspace it remains a hidden local directory. A team may choose to version redacted handoff exports, but the database should normally remain local. ## Coordination semantics @@ -158,8 +179,9 @@ Decision conflicts are also advisory. DevRelay flags related active decisions ba ## Security boundaries -- The repository root is resolved once when the server starts. -- MCP tools cannot select another repository path. +- The workspace root is resolved once when the server starts. +- Agent working directories must exist inside that fixed workspace. +- MCP tools cannot escape to another workspace path. - DevRelay does not expose arbitrary shell or test-command execution. - Git inspection uses fixed argument arrays without a shell. - `.env`, private keys, and credential-like paths are filtered. diff --git a/SECURITY.md b/SECURITY.md index 83b83f4..c4a192c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -16,11 +16,11 @@ DevRelay assumes coding agents and repository content may produce inaccurate or The v0.1 boundary is intentionally narrow: -- one fixed Git repository per server process +- one fixed repository or workspace boundary per server process - local SQLite and Markdown storage - no arbitrary shell command tool - fixed Git command argument arrays -- repository-relative scope paths only +- workspace-relative scope paths only - path traversal and absolute-path rejection - sensitive filename filtering - best-effort secret redaction before persistence diff --git a/examples/AGENTS.md b/examples/AGENTS.md index 213f9b6..ece9922 100644 --- a/examples/AGENTS.md +++ b/examples/AGENTS.md @@ -1,14 +1,14 @@ # DevRelay agent protocol -This repository uses DevRelay as shared coordination state for coding agents. +This repository or parent workspace uses DevRelay as shared coordination state for coding agents. ## Before editing -1. Call `agent_join` with a stable agent ID, agent type, and concise task summary. -2. Call `build_context` for the intended task. +1. Call `agent_join` with a stable agent ID, agent type, concise task summary, and the current `working_directory` inside the configured workspace. +2. Call `build_context` for the intended task and current `working_directory`. 3. Call `agent_status` and inspect active agents, task leases, and scope claims. 4. Call `claim_task` before taking an existing or new task. -5. Call `claim_scope` for the files or modules you expect to modify. +5. Call `claim_scope` for workspace-relative files or modules you expect to modify. 6. Stop and coordinate if DevRelay reports a task conflict or relevant scope overlap. ## During work diff --git a/package-lock.json b/package-lock.json index 43bc268..1e0371e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@arumwu/devrelay", - "version": "0.1.0", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@arumwu/devrelay", - "version": "0.1.0", + "version": "0.2.0", "license": "Apache-2.0", "dependencies": { "@modelcontextprotocol/sdk": "^1.29.0", diff --git a/package.json b/package.json index 1437728..9843323 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@arumwu/devrelay", - "version": "0.1.0", + "version": "0.2.0", "description": "Local-first coordination, handoffs, and shared project memory for coding agents.", "type": "module", "main": "./dist/index.js", diff --git a/src/cli.ts b/src/cli.ts index 822c66a..883316b 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -24,12 +24,12 @@ function withStore(repo: string, callback: (store: ProjectStore) => T): T { const program = new Command() .name("devrelay") .description("Local-first coordination and shared project memory for coding agents.") - .version("0.1.0") - .option("-r, --repo ", "Git repository to coordinate", process.cwd()); + .version("0.2.0") + .option("-r, --repo ", "Workspace or Git repository to coordinate", process.cwd()); program .command("init") - .description("Initialize .devrelay storage in the repository") + .description("Initialize .devrelay storage in the workspace") .option("--name ", "Project display name") .action((options: { name?: string }) => { const repo = program.opts<{ repo: string }>().repo; @@ -54,12 +54,14 @@ program .description("Register an agent session") .requiredOption("--agent ", "Stable agent identifier") .addOption(new Option("--type ", "Agent type").choices(["codex", "claude-code", "gemini-cli", "cursor", "cline", "other"]).default("other")) + .option("--cwd ", "Current directory inside the workspace") .option("--task ", "Current task summary") - .action((options: { agent: string; type: AgentType; task?: string }) => { + .action((options: { agent: string; type: AgentType; cwd?: string; task?: string }) => { const repo = program.opts<{ repo: string }>().repo; print(withStore(repo, (store) => store.joinAgent({ agentId: options.agent, agentType: options.type, + ...(options.cwd ? { workingDirectory: options.cwd } : {}), ...(options.task ? { taskSummary: options.task } : {}), }))); }); @@ -177,9 +179,14 @@ program .description("Compile a task-specific context pack") .argument("", "Task description") .option("--budget ", "Approximate token budget", "5000") - .action((task: string, options: { budget: string }) => { + .option("--cwd ", "Current directory inside the workspace") + .action((task: string, options: { budget: string; cwd?: string }) => { const repo = program.opts<{ repo: string }>().repo; - print(withStore(repo, (store) => store.buildContext({ task, tokenBudget: Number(options.budget) }))); + print(withStore(repo, (store) => store.buildContext({ + task, + tokenBudget: Number(options.budget), + ...(options.cwd ? { workingDirectory: options.cwd } : {}), + }))); }); program diff --git a/src/db.ts b/src/db.ts index 1550f23..4a6e6b3 100644 --- a/src/db.ts +++ b/src/db.ts @@ -20,6 +20,7 @@ CREATE TABLE IF NOT EXISTS sessions ( project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE, agent_id TEXT NOT NULL, agent_type TEXT NOT NULL, + working_path TEXT, branch TEXT NOT NULL, task_summary TEXT, status TEXT NOT NULL CHECK (status IN ('active', 'ended')), @@ -152,5 +153,14 @@ export function openDatabase(rootPath: string): DatabaseHandle { db.pragma("journal_mode = WAL"); db.pragma("foreign_keys = ON"); db.exec(SCHEMA); + const sessionColumns = db.pragma("table_info(sessions)") as Array<{ name: string }>; + if (!sessionColumns.some((column) => column.name === "working_path")) { + db.exec("ALTER TABLE sessions ADD COLUMN working_path TEXT"); + } + db.exec(` + UPDATE sessions + SET working_path = (SELECT root_path FROM projects WHERE projects.id = sessions.project_id) + WHERE working_path IS NULL + `); return { db, dataDir, dbPath }; } diff --git a/src/git.ts b/src/git.ts index 587c48f..7eca867 100644 --- a/src/git.ts +++ b/src/git.ts @@ -29,27 +29,74 @@ export function resolveRepositoryRoot(inputPath: string): string { if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) { throw new Error(`Repository directory does not exist: ${resolved}`); } - const root = runGit(resolved, ["rev-parse", "--show-toplevel"], true); + const root = tryResolveRepositoryRoot(resolved); if (!root) { throw new Error(`Not a Git repository: ${resolved}`); } - return fs.realpathSync(root); + return root; +} + +export function tryResolveRepositoryRoot(inputPath: string): string | null { + const resolved = path.resolve(inputPath); + if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) return null; + const root = runGit(resolved, ["rev-parse", "--show-toplevel"], true); + return root ? fs.realpathSync(root) : null; +} + +export function resolveWorkspaceRoot(inputPath: string): string { + const resolved = path.resolve(inputPath); + if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) { + throw new Error(`Workspace directory does not exist: ${resolved}`); + } + const realPath = fs.realpathSync(resolved); + return tryResolveRepositoryRoot(realPath) ?? realPath; +} + +export function resolveWorkingDirectory(workspaceRoot: string, inputPath?: string): string { + const candidate = inputPath + ? path.resolve(workspaceRoot, inputPath) + : workspaceRoot; + if (!fs.existsSync(candidate) || !fs.statSync(candidate).isDirectory()) { + throw new Error(`Working directory does not exist: ${candidate}`); + } + const realPath = fs.realpathSync(candidate); + const relative = path.relative(workspaceRoot, realPath); + if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) { + throw new Error(`Working directory is outside the DevRelay workspace: ${realPath}`); + } + return realPath; } export function captureGitSnapshot(rootPath: string): GitSnapshot { - const branch = runGit(rootPath, ["branch", "--show-current"], true) || "(detached)"; - const head = runGit(rootPath, ["rev-parse", "HEAD"], true) || null; - const rawStatus = runGit(rootPath, ["status", "--short", "--untracked-files=normal"], true); + const repositoryRoot = tryResolveRepositoryRoot(rootPath); + if (!repositoryRoot) { + return { + available: false, + repositoryRoot: null, + branch: "(no git repository)", + head: null, + status: [], + changedFiles: [], + diffStat: "", + recentCommit: null, + reason: "The selected working directory is not inside a Git repository.", + }; + } + const branch = runGit(repositoryRoot, ["branch", "--show-current"], true) || "(detached)"; + const head = runGit(repositoryRoot, ["rev-parse", "HEAD"], true) || null; + const rawStatus = runGit(repositoryRoot, ["status", "--short", "--untracked-files=normal"], true); const status = rawStatus ? rawStatus.split("\n") : []; - const rawChangedFiles = runGit(rootPath, ["diff", "--name-only", "HEAD"], true); - const untracked = runGit(rootPath, ["ls-files", "--others", "--exclude-standard"], true); + const rawChangedFiles = runGit(repositoryRoot, ["diff", "--name-only", "HEAD"], true); + const untracked = runGit(repositoryRoot, ["ls-files", "--others", "--exclude-standard"], true); const changedFiles = filterSafePaths( [...rawChangedFiles.split("\n"), ...untracked.split("\n")].filter(Boolean), ); - const diffStat = runGit(rootPath, ["diff", "--stat", "HEAD"], true); - const recentCommit = runGit(rootPath, ["log", "-1", "--pretty=format:%h %s"], true) || null; + const diffStat = runGit(repositoryRoot, ["diff", "--stat", "HEAD"], true); + const recentCommit = runGit(repositoryRoot, ["log", "-1", "--pretty=format:%h %s"], true) || null; return { + available: true, + repositoryRoot, branch, head, status: status.filter((line) => { @@ -59,5 +106,6 @@ export function captureGitSnapshot(rootPath: string): GitSnapshot { changedFiles, diffStat, recentCommit, + reason: null, }; } diff --git a/src/index.ts b/src/index.ts index e3071f2..58011ed 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,11 @@ export { createMcpServer, serveStdio } from "./mcp.js"; export { ProjectStore, scopePatternsMayOverlap } from "./store.js"; -export { captureGitSnapshot, resolveRepositoryRoot } from "./git.js"; +export { + captureGitSnapshot, + resolveRepositoryRoot, + resolveWorkingDirectory, + resolveWorkspaceRoot, + tryResolveRepositoryRoot, +} from "./git.js"; export { filterSafePaths, isSensitivePath, redactSecrets, redactStructured } from "./security.js"; export type * from "./types.js"; diff --git a/src/mcp.ts b/src/mcp.ts index a3adf96..23a510c 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -36,7 +36,7 @@ function registerTools(server: McpServer, store: ProjectStore): void { "project_init", { title: "Initialize or inspect DevRelay", - description: "Initialize project-local DevRelay storage and return the fixed repository boundary.", + description: "Initialize workspace-local DevRelay storage and return the fixed filesystem boundary.", inputSchema: {}, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }, }, @@ -47,21 +47,23 @@ function registerTools(server: McpServer, store: ProjectStore): void { "agent_join", { title: "Join an agent session", - description: "Register a coding agent session in this repository before claiming work.", + description: "Register a coding agent session and its current directory inside this workspace.", inputSchema: { agent_id: z.string().min(1).max(120), agent_type: z.enum(agentTypes), + working_directory: z.string().min(1).max(2_000).optional(), task_summary: z.string().max(2_000).optional(), metadata: z.record(z.string(), z.unknown()).optional(), }, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false }, }, - async ({ agent_id, agent_type, task_summary, metadata }) => { + async ({ agent_id, agent_type, working_directory, task_summary, metadata }) => { try { return response( store.joinAgent({ agentId: agent_id, agentType: agent_type as AgentType, + ...(working_directory ? { workingDirectory: working_directory } : {}), ...(task_summary ? { taskSummary: task_summary } : {}), ...(metadata ? { metadata } : {}), }), @@ -130,7 +132,7 @@ function registerTools(server: McpServer, store: ProjectStore): void { "claim_scope", { title: "Claim files or modules", - description: "Register advisory repository-relative file or glob claims and report overlaps.", + description: "Register advisory workspace-relative file or glob claims and report overlaps.", inputSchema: { session_id: z.string().uuid(), patterns: z.array(z.string().min(1).max(500)).min(1).max(50), @@ -264,12 +266,17 @@ function registerTools(server: McpServer, store: ProjectStore): void { inputSchema: { task: z.string().min(1).max(2_000), token_budget: z.number().int().min(500).max(20_000).default(5_000), + working_directory: z.string().min(1).max(2_000).optional(), }, annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }, }, - async ({ task, token_budget }) => { + async ({ task, token_budget, working_directory }) => { try { - return response(store.buildContext({ task, tokenBudget: token_budget })); + return response(store.buildContext({ + task, + tokenBudget: token_budget, + ...(working_directory ? { workingDirectory: working_directory } : {}), + })); } catch (error) { return failure(error); } @@ -309,7 +316,7 @@ function registerTools(server: McpServer, store: ProjectStore): void { } export function createMcpServer(store: ProjectStore): McpServer { - const server = new McpServer({ name: "devrelay", version: "0.1.0" }); + const server = new McpServer({ name: "devrelay", version: "0.2.0" }); registerTools(server, store); return server; } diff --git a/src/store.ts b/src/store.ts index 2d3127c..1102cb5 100644 --- a/src/store.ts +++ b/src/store.ts @@ -4,7 +4,11 @@ import path from "node:path"; import type Database from "better-sqlite3"; import { minimatch } from "minimatch"; import { openDatabase } from "./db.js"; -import { captureGitSnapshot, resolveRepositoryRoot } from "./git.js"; +import { + captureGitSnapshot, + resolveWorkingDirectory, + resolveWorkspaceRoot, +} from "./git.js"; import { assertSafeRelativePattern, filterSafePaths, @@ -15,6 +19,7 @@ import { import type { AgentType, EventType, + GitSnapshot, ProjectRecord, ScopeClaimRecord, SearchResult, @@ -34,6 +39,7 @@ interface SessionRow { project_id: string; agent_id: string; agent_type: AgentType; + working_path: string; branch: string; task_summary: string | null; status: "active" | "ended"; @@ -138,6 +144,7 @@ function mapSession(row: SessionRow): SessionRecord { projectId: row.project_id, agentId: row.agent_id, agentType: row.agent_type, + workingPath: row.working_path, branch: row.branch, taskSummary: row.task_summary, status: row.status, @@ -213,6 +220,12 @@ function truncate(value: string, maxChars: number): string { return `${value.slice(0, Math.max(0, maxChars - 24))}\n…[context truncated]`; } +function workspaceChangedFiles(workspaceRoot: string, snapshot: GitSnapshot): string[] { + if (!snapshot.repositoryRoot) return []; + const prefix = path.relative(workspaceRoot, snapshot.repositoryRoot).replaceAll(path.sep, "/"); + return snapshot.changedFiles.map((file) => (prefix ? `${prefix}/${file}` : file)); +} + export class ProjectStore { readonly rootPath: string; readonly dataDir: string; @@ -221,7 +234,7 @@ export class ProjectStore { private readonly db: Database.Database; constructor(inputPath: string, projectName?: string) { - this.rootPath = resolveRepositoryRoot(inputPath); + this.rootPath = resolveWorkspaceRoot(inputPath); const handle = openDatabase(this.rootPath); this.db = handle.db; this.dataDir = handle.dataDir; @@ -253,7 +266,7 @@ export class ProjectStore { private requireSession(sessionId: string): SessionRecord { const row = this.db .prepare( - "SELECT id, project_id, agent_id, agent_type, branch, task_summary, status, started_at, last_seen_at, ended_at FROM sessions WHERE id = ? AND project_id = ?", + "SELECT id, project_id, agent_id, agent_type, working_path, branch, task_summary, status, started_at, last_seen_at, ended_at FROM sessions WHERE id = ? AND project_id = ?", ) .get(sessionId, this.project.id) as SessionRow | undefined; if (!row) throw new Error(`Unknown agent session: ${sessionId}`); @@ -303,9 +316,10 @@ export class ProjectStore { return { project: this.project, database: this.dbPath, + mode: snapshot.available ? "repository" : "workspace", git: snapshot, security: { - repositoryBoundary: this.rootPath, + workspaceBoundary: this.rootPath, arbitraryShellCommands: false, secretRedaction: true, }, @@ -315,6 +329,7 @@ export class ProjectStore { joinAgent(input: { agentId: string; agentType: AgentType; + workingDirectory?: string; taskSummary?: string; metadata?: Record; }): SessionRecord { @@ -322,19 +337,21 @@ export class ProjectStore { if (!VALID_AGENT_TYPES.has(input.agentType)) throw new Error(`Unsupported agent type: ${input.agentType}`); const timestamp = now(); const sessionId = randomUUID(); - const branch = captureGitSnapshot(this.rootPath).branch; + const workingPath = resolveWorkingDirectory(this.rootPath, input.workingDirectory); + const branch = captureGitSnapshot(workingPath).branch; const taskSummary = input.taskSummary ? redactSecrets(input.taskSummary) : null; this.db .prepare( `INSERT INTO sessions - (id, project_id, agent_id, agent_type, branch, task_summary, status, metadata_json, started_at, last_seen_at) - VALUES (?, ?, ?, ?, ?, ?, 'active', ?, ?, ?)`, + (id, project_id, agent_id, agent_type, working_path, branch, task_summary, status, metadata_json, started_at, last_seen_at) + VALUES (?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?)`, ) .run( sessionId, this.project.id, redactSecrets(input.agentId.trim()), input.agentType, + workingPath, branch, taskSummary, JSON.stringify(redactStructured(input.metadata ?? {})), @@ -345,7 +362,7 @@ export class ProjectStore { sessionId, eventType: "agent_joined", summary: `${input.agentId} joined on ${branch}`, - content: taskSummary ?? "Agent joined without a task summary.", + content: `${taskSummary ?? "Agent joined without a task summary."}\nWorking directory: ${path.relative(this.rootPath, workingPath) || "."}`, }); return this.requireSession(sessionId); } @@ -376,7 +393,7 @@ export class ProjectStore { const timestamp = now(); const sessions = this.db .prepare( - "SELECT id, project_id, agent_id, agent_type, branch, task_summary, status, started_at, last_seen_at, ended_at FROM sessions WHERE project_id = ? AND status = 'active' ORDER BY last_seen_at DESC", + "SELECT id, project_id, agent_id, agent_type, working_path, branch, task_summary, status, started_at, last_seen_at, ended_at FROM sessions WHERE project_id = ? AND status = 'active' ORDER BY last_seen_at DESC", ) .all(this.project.id) as SessionRow[]; const tasks = this.db @@ -737,7 +754,7 @@ export class ProjectStore { })); } - buildContext(input: { task: string; tokenBudget?: number }): Record { + buildContext(input: { task: string; tokenBudget?: number; workingDirectory?: string }): Record { if (!input.task.trim()) throw new Error("Context task cannot be empty."); const tokenBudget = input.tokenBudget ?? 5000; if (!Number.isInteger(tokenBudget) || tokenBudget < 500 || tokenBudget > 20_000) { @@ -750,6 +767,8 @@ export class ProjectStore { openTasks: TaskRecord[]; activeScopeClaims: ScopeClaimRecord[]; }; + const workingPath = resolveWorkingDirectory(this.rootPath, input.workingDirectory); + status.git = captureGitSnapshot(workingPath); const related = this.searchMemory(input.task, 20); const activeDecisions = this.db .prepare( @@ -763,7 +782,7 @@ export class ProjectStore { .all(this.project.id) as EventRow[]; const sections = [ - `# DevRelay Context Pack\n\nTask: ${redactSecrets(input.task)}\nProject: ${this.project.name}\nRepository: ${this.rootPath}`, + `# DevRelay Context Pack\n\nTask: ${redactSecrets(input.task)}\nWorkspace: ${this.project.name}\nBoundary: ${this.rootPath}\nWorking directory: ${workingPath}`, `## Git snapshot\n\n${JSON.stringify(status.git, null, 2)}`, `## Active agents\n\n${JSON.stringify(status.activeSessions, null, 2)}`, `## Open tasks and leases\n\n${JSON.stringify(status.openTasks, null, 2)}`, @@ -796,7 +815,8 @@ export class ProjectStore { }): Record { const session = this.requireActiveSession(input.sessionId); if (input.taskId) this.requireTask(input.taskId); - const snapshot = captureGitSnapshot(this.rootPath); + const snapshot = captureGitSnapshot(session.workingPath); + const changedFiles = workspaceChangedFiles(this.rootPath, snapshot); const timestamp = now(); const id = randomUUID(); const events = this.db @@ -833,6 +853,9 @@ export class ProjectStore { Created: ${timestamp} Agent: ${session.agentId} (${session.agentType}) +Workspace: ${this.rootPath} +Working directory: ${session.workingPath} +Git repository: ${snapshot.repositoryRoot ?? "Not available"} Branch: ${snapshot.branch} Commit: ${snapshot.head ?? "No commit yet"} @@ -846,7 +869,7 @@ ${ownedTasks.map((task) => `- [${task.status}] ${task.title}`).join("\n") || "No ## Files changed -${snapshot.changedFiles.map((file) => `- ${file}`).join("\n") || "No safe changed files detected."} +${changedFiles.map((file) => `- ${file}`).join("\n") || "No safe changed files detected."} ## Git diff summary @@ -895,7 +918,7 @@ Read this handoff, call build_context for the next task, then claim the task and body, snapshot.head, snapshot.branch, - JSON.stringify(snapshot.changedFiles), + JSON.stringify(changedFiles), timestamp, ); this.appendSearchDocument("handoff", id, title, body, timestamp); @@ -918,7 +941,7 @@ Read this handoff, call build_context for the next task, then claim the task and eventType: "handoff_created", summary: title, content: `Handoff written to ${path.relative(this.rootPath, filePath)}.`, - files: snapshot.changedFiles, + files: changedFiles, }); return { id, title, body, filePath, git: snapshot, sessionEnded: input.endSession ?? true }; } diff --git a/src/types.ts b/src/types.ts index 4cd2a00..1700242 100644 --- a/src/types.ts +++ b/src/types.ts @@ -22,12 +22,15 @@ export type EventType = | "task_completed"; export interface GitSnapshot { + available: boolean; + repositoryRoot: string | null; branch: string; head: string | null; status: string[]; changedFiles: string[]; diffStat: string; recentCommit: string | null; + reason: string | null; } export interface ProjectRecord { @@ -42,6 +45,7 @@ export interface SessionRecord { projectId: string; agentId: string; agentType: AgentType; + workingPath: string; branch: string; taskSummary: string | null; status: "active" | "ended"; diff --git a/tests/helpers.ts b/tests/helpers.ts index 3d8e1a4..1fadbbd 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -27,3 +27,26 @@ export function createTestRepository(): string { export function removeTestRepository(root: string): void { fs.rmSync(root, { recursive: true, force: true }); } + +export function createTestWorkspace(): { root: string; repository: string } { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "devrelay-workspace-test-")); + const repository = path.join(root, "project-a"); + fs.mkdirSync(repository); + const run = (args: string[]) => { + const result = spawnSync("git", ["-C", repository, ...args], { encoding: "utf8" }); + if (result.status !== 0) throw new Error(result.stderr); + }; + run(["init", "-b", "main"]); + fs.writeFileSync(path.join(repository, "README.md"), "# Nested fixture\n", "utf8"); + run(["add", "README.md"]); + run([ + "-c", + "user.name=DevRelay Tests", + "-c", + "user.email=devrelay@example.invalid", + "commit", + "-m", + "initial nested fixture", + ]); + return { root: fs.realpathSync(root), repository: fs.realpathSync(repository) }; +} diff --git a/tests/workspace.test.ts b/tests/workspace.test.ts new file mode 100644 index 0000000..0486f28 --- /dev/null +++ b/tests/workspace.test.ts @@ -0,0 +1,72 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { ProjectStore } from "../src/store.js"; +import { createTestWorkspace, removeTestRepository } from "./helpers.js"; + +describe("workspace mode", () => { + let root: string; + let repository: string; + let store: ProjectStore; + + beforeEach(() => { + const fixture = createTestWorkspace(); + root = fixture.root; + repository = fixture.repository; + store = new ProjectStore(root, "multi-project-workspace"); + }); + + afterEach(() => { + store.close(); + removeTestRepository(root); + }); + + it("coordinates a non-Git workspace while using session-specific child Git state", () => { + const initialized = store.initSummary() as { + mode: string; + git: { available: boolean }; + security: { workspaceBoundary: string }; + }; + expect(initialized.mode).toBe("workspace"); + expect(initialized.git.available).toBe(false); + expect(initialized.security.workspaceBoundary).toBe(root); + + const session = store.joinAgent({ + agentId: "codex-workspace", + agentType: "codex", + workingDirectory: "project-a", + taskSummary: "Edit the nested repository", + }); + expect(session.workingPath).toBe(repository); + expect(session.branch).toBe("main"); + + fs.mkdirSync(path.join(repository, "src")); + fs.writeFileSync(path.join(repository, "src", "index.ts"), "export const ready = true;\n"); + + const context = store.buildContext({ + task: "Finish project A", + workingDirectory: repository, + tokenBudget: 2_000, + }) as { context: string }; + expect(context.context).toContain(`"repositoryRoot": "${repository}"`); + expect(context.context).toContain("src/index.ts"); + + const handoff = store.createHandoff({ + sessionId: session.id, + title: "Nested repository handoff", + }) as { body: string; git: { available: boolean } }; + expect(handoff.git.available).toBe(true); + expect(handoff.body).toContain("project-a/src/index.ts"); + }); + + it("rejects a session working directory outside the fixed workspace", () => { + expect(() => + store.joinAgent({ + agentId: "outside-agent", + agentType: "other", + workingDirectory: os.tmpdir(), + }), + ).toThrow(/outside the DevRelay workspace/); + }); +}); From 41a5f6678375fc39e8750a88ae458a4cf05c8311 Mon Sep 17 00:00:00 2001 From: arumwu <75135621+arumwu@users.noreply.github.com> Date: Thu, 16 Jul 2026 06:41:31 +0800 Subject: [PATCH 2/2] Rename DevRelay to AgentRelay --- .gitignore | 1 + LICENSE | 2 +- README.md | 64 ++++++++++++++++++++++------------------- SECURITY.md | 12 ++++---- examples/AGENTS.md | 10 +++---- package-lock.json | 10 +++---- package.json | 14 ++++----- src/cli.ts | 8 +++--- src/db.ts | 18 ++++++++++-- src/git.ts | 2 +- src/mcp.ts | 6 ++-- src/store.ts | 2 +- tests/helpers.ts | 12 ++++---- tests/mcp.test.ts | 2 +- tests/store.test.ts | 2 +- tests/workspace.test.ts | 20 ++++++++++++- 16 files changed, 111 insertions(+), 74 deletions(-) diff --git a/.gitignore b/.gitignore index 2ebc3fb..3b1390a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ node_modules/ dist/ coverage/ +.agentrelay/ .devrelay/ *.log .DS_Store diff --git a/LICENSE b/LICENSE index 4c1fd86..13a81c8 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2026 DevRelay contributors + Copyright 2026 AgentRelay contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/README.md b/README.md index ea65c0e..5ccc072 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,14 @@ -# DevRelay +# AgentRelay -**DevRelay coordinates coding agents working in the same repository or multi-project workspace.** +## One project. Multiple AI agents. Zero repeated work. + +**Let AI continue where another AI stopped.** It tracks active sessions, task leases, advisory file ownership, decisions, failed attempts, Git state, and handoffs so Codex, Claude Code, and other agents can continue each other's work without rebuilding context from scratch. > Not another chat memory. A local coordination layer for coding agents. -## What works in v0.2 +## What works in v0.3 - Local-first SQLite storage inside a repository or workspace - Fixed non-Git workspace boundaries with child-repository Git context @@ -39,11 +41,11 @@ Agent B joins ## Install from source -DevRelay is not published to npm yet. +AgentRelay is not published to npm yet. ```bash -git clone https://github.com/arumwu/devrelay.git -cd devrelay +git clone https://github.com/arumwu/agentrelay.git +cd agentrelay npm install npm run build npm link @@ -53,11 +55,11 @@ Node.js 22.13 or newer is required. ## Quick start -Run these commands from a Git repository, or pin DevRelay to a larger workspace with `--repo /absolute/path` before the subcommand. +Run these commands from a Git repository, or pin AgentRelay to a larger workspace with `--repo /absolute/path` before the subcommand. ```bash -devrelay --repo /workspaces/company init -devrelay --repo /workspaces/company join \ +agentrelay --repo /workspaces/company init +agentrelay --repo /workspaces/company join \ --agent codex-01 \ --type codex \ --cwd products/api \ @@ -67,24 +69,24 @@ devrelay --repo /workspaces/company join \ The `join` command returns a session UUID. Use it for claims and event records: ```bash -devrelay claim-task \ +agentrelay claim-task \ --session SESSION_UUID \ --title "Implement OAuth callback" \ --description "Validate callback and exchange tokens" -devrelay claim-scope \ +agentrelay claim-scope \ --session SESSION_UUID \ --pattern "src/auth/**" -devrelay event \ +agentrelay event \ --session SESSION_UUID \ --type attempt \ --summary "Service account approach failed" \ --content "Normal user OAuth requires authorization-code flow" -devrelay context "Finish OAuth refresh flow" --cwd products/api --budget 5000 +agentrelay context "Finish OAuth refresh flow" --cwd products/api --budget 5000 -devrelay handoff \ +agentrelay handoff \ --session SESSION_UUID \ --title "OAuth implementation handoff" ``` @@ -94,8 +96,8 @@ devrelay handoff \ For a source checkout, register the built CLI and pin it to the repository or workspace the agents will coordinate: ```bash -codex mcp add devrelay -- \ - node /absolute/path/to/devrelay/dist/cli.js \ +codex mcp add agentrelay -- \ + node /absolute/path/to/agentrelay/dist/cli.js \ --repo /absolute/path/to/your/workspace \ serve ``` @@ -103,10 +105,10 @@ codex mcp add devrelay -- \ Equivalent `config.toml`: ```toml -[mcp_servers.devrelay] +[mcp_servers.agentrelay] command = "node" args = [ - "/absolute/path/to/devrelay/dist/cli.js", + "/absolute/path/to/agentrelay/dist/cli.js", "--repo", "/absolute/path/to/your/workspace", "serve" @@ -116,8 +118,8 @@ args = [ ## Connect Claude Code ```bash -claude mcp add devrelay -- \ - node /absolute/path/to/devrelay/dist/cli.js \ +claude mcp add agentrelay -- \ + node /absolute/path/to/agentrelay/dist/cli.js \ --repo /absolute/path/to/your/workspace \ serve ``` @@ -129,14 +131,14 @@ Then place the lifecycle rules from [`examples/AGENTS.md`](examples/AGENTS.md) i A workspace may contain many independent Git repositories and non-Git projects: ```text -/workspaces/company/ <- fixed DevRelay boundary -├── .devrelay/ <- shared workspace memory +/workspaces/company/ <- fixed AgentRelay boundary +├── .agentrelay/ <- shared workspace memory ├── products/api/.git/ ├── products/web/.git/ └── research-notes/ ``` -The MCP server remains fixed to `/workspaces/company`. Each `agent_join` and `build_context` call may include `working_directory`, such as `products/api`. DevRelay rejects directories outside the fixed workspace and obtains Git status from the child repository containing that working directory. +The MCP server remains fixed to `/workspaces/company`. Each `agent_join` and `build_context` call may include `working_directory`, such as `products/api`. AgentRelay rejects directories outside the fixed workspace and obtains Git status from the child repository containing that working directory. Task and scope claims remain workspace-wide. In the example above, claim `products/api/src/**`, not only `src/**`, to avoid ambiguity between child projects. @@ -160,29 +162,31 @@ Task and scope claims remain workspace-wide. In the example above, claim `produc Each coordinated repository or workspace owns its memory: ```text -.devrelay/ -├── devrelay.db +.agentrelay/ +├── agentrelay.db ├── events.jsonl └── handoffs/ └── 2026-...-handoff.md ``` -`.devrelay/` is excluded from this repository's Git history by default. In a non-Git workspace it remains a hidden local directory. A team may choose to version redacted handoff exports, but the database should normally remain local. +`.agentrelay/` is excluded from this repository's Git history by default. In a non-Git workspace it remains a hidden local directory. A team may choose to version redacted handoff exports, but the database should normally remain local. + +When upgrading from the former DevRelay name, the first AgentRelay startup automatically renames `.devrelay/` to `.agentrelay/` and `devrelay.db` to `agentrelay.db` when the new paths do not already exist. ## Coordination semantics -Task leases are exclusive while active. If a second agent requests the same task, DevRelay returns a conflict with the current owner and expiry. +Task leases are exclusive while active. If a second agent requests the same task, AgentRelay returns a conflict with the current owner and expiry. -Scope claims are advisory. DevRelay warns when file or glob patterns may overlap, but it does not pretend it can prevent an agent from editing files outside MCP. Agents and hooks should treat warnings as a coordination stop. +Scope claims are advisory. AgentRelay warns when file or glob patterns may overlap, but it does not pretend it can prevent an agent from editing files outside MCP. Agents and hooks should treat warnings as a coordination stop. -Decision conflicts are also advisory. DevRelay flags related active decisions based on task, title, and scope overlap; a human or agent must explicitly supersede the old decision. +Decision conflicts are also advisory. AgentRelay flags related active decisions based on task, title, and scope overlap; a human or agent must explicitly supersede the old decision. ## Security boundaries - The workspace root is resolved once when the server starts. - Agent working directories must exist inside that fixed workspace. - MCP tools cannot escape to another workspace path. -- DevRelay does not expose arbitrary shell or test-command execution. +- AgentRelay does not expose arbitrary shell or test-command execution. - Git inspection uses fixed argument arrays without a shell. - `.env`, private keys, and credential-like paths are filtered. - Common API keys, tokens, passwords, cookies, and bearer headers are redacted before storage. diff --git a/SECURITY.md b/SECURITY.md index c4a192c..8c59fc6 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,7 +2,7 @@ ## Supported versions -DevRelay is pre-1.0 software. Security fixes are applied to the latest released version. +AgentRelay is pre-1.0 software. Security fixes are applied to the latest released version. ## Reporting a vulnerability @@ -12,7 +12,7 @@ Include the affected version, operating system, reproduction steps, security imp ## Threat model -DevRelay assumes coding agents and repository content may produce inaccurate or adversarial text. Stored memory is treated as context, not executable instructions. +AgentRelay assumes coding agents and repository content may produce inaccurate or adversarial text. Stored memory is treated as context, not executable instructions. The v0.1 boundary is intentionally narrow: @@ -25,12 +25,12 @@ The v0.1 boundary is intentionally narrow: - sensitive filename filtering - best-effort secret redaction before persistence -Secret redaction is defense in depth, not a substitute for avoiding secret input. Users should not intentionally send credentials to DevRelay. +Secret redaction is defense in depth, not a substitute for avoiding secret input. Users should not intentionally send credentials to AgentRelay. ## Out of scope for v0.1 -- hostile local users with filesystem access to `.devrelay/` +- hostile local users with filesystem access to `.agentrelay/` - full-disk compromise -- malicious changes to the DevRelay executable or dependencies +- malicious changes to the AgentRelay executable or dependencies - perfect detection of every possible credential format -- enforcing scope claims against tools that bypass DevRelay +- enforcing scope claims against tools that bypass AgentRelay diff --git a/examples/AGENTS.md b/examples/AGENTS.md index ece9922..1b15d7c 100644 --- a/examples/AGENTS.md +++ b/examples/AGENTS.md @@ -1,6 +1,6 @@ -# DevRelay agent protocol +# AgentRelay agent protocol -This repository or parent workspace uses DevRelay as shared coordination state for coding agents. +This repository or parent workspace uses AgentRelay as shared coordination state for coding agents. ## Before editing @@ -9,7 +9,7 @@ This repository or parent workspace uses DevRelay as shared coordination state f 3. Call `agent_status` and inspect active agents, task leases, and scope claims. 4. Call `claim_task` before taking an existing or new task. 5. Call `claim_scope` for workspace-relative files or modules you expect to modify. -6. Stop and coordinate if DevRelay reports a task conflict or relevant scope overlap. +6. Stop and coordinate if AgentRelay reports a task conflict or relevant scope overlap. ## During work @@ -17,7 +17,7 @@ This repository or parent workspace uses DevRelay as shared coordination state f - Record important discoveries, tests, results, and blockers with `record_event`. - Record failed attempts with `event_type: attempt`, including the reason and retry condition. - Record durable architecture choices with `record_decision`. -- Never store secrets, credentials, raw `.env` values, or private keys in DevRelay. +- Never store secrets, credentials, raw `.env` values, or private keys in AgentRelay. ## Before ending or handing off @@ -26,4 +26,4 @@ This repository or parent workspace uses DevRelay as shared coordination state f 3. Call `create_handoff`; allow it to end the session unless work is continuing immediately. 4. Confirm the handoff includes changed files, test status, failed attempts, blockers, and the recommended next action. -DevRelay claims are coordination signals, not filesystem locks. Do not edit through an active overlapping claim without explicit coordination. +AgentRelay claims are coordination signals, not filesystem locks. Do not edit through an active overlapping claim without explicit coordination. diff --git a/package-lock.json b/package-lock.json index 1e0371e..75a673a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { - "name": "@arumwu/devrelay", - "version": "0.2.0", + "name": "@arumwu/agentrelay", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "@arumwu/devrelay", - "version": "0.2.0", + "name": "@arumwu/agentrelay", + "version": "0.3.0", "license": "Apache-2.0", "dependencies": { "@modelcontextprotocol/sdk": "^1.29.0", @@ -16,7 +16,7 @@ "zod": "^4.4.3" }, "bin": { - "devrelay": "dist/cli.js" + "agentrelay": "dist/cli.js" }, "devDependencies": { "@types/better-sqlite3": "^7.6.13", diff --git a/package.json b/package.json index 9843323..d2b1b6e 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { - "name": "@arumwu/devrelay", - "version": "0.2.0", - "description": "Local-first coordination, handoffs, and shared project memory for coding agents.", + "name": "@arumwu/agentrelay", + "version": "0.3.0", + "description": "One project. Multiple AI agents. Zero repeated work.", "type": "module", "main": "./dist/index.js", "types": "./dist/index.d.ts", @@ -12,7 +12,7 @@ } }, "bin": { - "devrelay": "dist/cli.js" + "agentrelay": "dist/cli.js" }, "files": [ "dist", @@ -40,12 +40,12 @@ "license": "Apache-2.0", "repository": { "type": "git", - "url": "git+https://github.com/arumwu/devrelay.git" + "url": "git+https://github.com/arumwu/agentrelay.git" }, "bugs": { - "url": "https://github.com/arumwu/devrelay/issues" + "url": "https://github.com/arumwu/agentrelay/issues" }, - "homepage": "https://github.com/arumwu/devrelay#readme", + "homepage": "https://github.com/arumwu/agentrelay#readme", "dependencies": { "@modelcontextprotocol/sdk": "^1.29.0", "better-sqlite3": "^12.11.1", diff --git a/src/cli.ts b/src/cli.ts index 883316b..4a85aea 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -22,14 +22,14 @@ function withStore(repo: string, callback: (store: ProjectStore) => T): T { } const program = new Command() - .name("devrelay") + .name("agentrelay") .description("Local-first coordination and shared project memory for coding agents.") - .version("0.2.0") + .version("0.3.0") .option("-r, --repo ", "Workspace or Git repository to coordinate", process.cwd()); program .command("init") - .description("Initialize .devrelay storage in the workspace") + .description("Initialize .agentrelay storage in the workspace") .option("--name ", "Project display name") .action((options: { name?: string }) => { const repo = program.opts<{ repo: string }>().repo; @@ -43,7 +43,7 @@ program program .command("serve") - .description("Run the DevRelay MCP server over stdio") + .description("Run the AgentRelay MCP server over stdio") .action(async () => { const repo = program.opts<{ repo: string }>().repo; await serveStdio(new ProjectStore(repo)); diff --git a/src/db.ts b/src/db.ts index 4a6e6b3..dcb751b 100644 --- a/src/db.ts +++ b/src/db.ts @@ -145,9 +145,23 @@ export interface DatabaseHandle { } export function openDatabase(rootPath: string): DatabaseHandle { - const dataDir = path.join(rootPath, ".devrelay"); + const legacyDataDir = path.join(rootPath, ".devrelay"); + const dataDir = path.join(rootPath, ".agentrelay"); + if (!fs.existsSync(dataDir) && fs.existsSync(legacyDataDir)) { + fs.renameSync(legacyDataDir, dataDir); + } fs.mkdirSync(path.join(dataDir, "handoffs"), { recursive: true, mode: 0o700 }); - const dbPath = path.join(dataDir, "devrelay.db"); + const legacyDbPath = path.join(dataDir, "devrelay.db"); + const dbPath = path.join(dataDir, "agentrelay.db"); + if (!fs.existsSync(dbPath) && fs.existsSync(legacyDbPath)) { + fs.renameSync(legacyDbPath, dbPath); + for (const suffix of ["-wal", "-shm"]) { + const legacySidecar = `${legacyDbPath}${suffix}`; + if (fs.existsSync(legacySidecar)) { + fs.renameSync(legacySidecar, `${dbPath}${suffix}`); + } + } + } const db = new Database(dbPath); fs.chmodSync(dbPath, 0o600); db.pragma("journal_mode = WAL"); diff --git a/src/git.ts b/src/git.ts index 7eca867..11398e8 100644 --- a/src/git.ts +++ b/src/git.ts @@ -62,7 +62,7 @@ export function resolveWorkingDirectory(workspaceRoot: string, inputPath?: strin const realPath = fs.realpathSync(candidate); const relative = path.relative(workspaceRoot, realPath); if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) { - throw new Error(`Working directory is outside the DevRelay workspace: ${realPath}`); + throw new Error(`Working directory is outside the AgentRelay workspace: ${realPath}`); } return realPath; } diff --git a/src/mcp.ts b/src/mcp.ts index 23a510c..e66ca3d 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -35,8 +35,8 @@ function registerTools(server: McpServer, store: ProjectStore): void { server.registerTool( "project_init", { - title: "Initialize or inspect DevRelay", - description: "Initialize workspace-local DevRelay storage and return the fixed filesystem boundary.", + title: "Initialize or inspect AgentRelay", + description: "Initialize workspace-local AgentRelay storage and return the fixed filesystem boundary.", inputSchema: {}, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }, }, @@ -316,7 +316,7 @@ function registerTools(server: McpServer, store: ProjectStore): void { } export function createMcpServer(store: ProjectStore): McpServer { - const server = new McpServer({ name: "devrelay", version: "0.2.0" }); + const server = new McpServer({ name: "agentrelay", version: "0.3.0" }); registerTools(server, store); return server; } diff --git a/src/store.ts b/src/store.ts index 1102cb5..b3c009f 100644 --- a/src/store.ts +++ b/src/store.ts @@ -782,7 +782,7 @@ export class ProjectStore { .all(this.project.id) as EventRow[]; const sections = [ - `# DevRelay Context Pack\n\nTask: ${redactSecrets(input.task)}\nWorkspace: ${this.project.name}\nBoundary: ${this.rootPath}\nWorking directory: ${workingPath}`, + `# AgentRelay Context Pack\n\nTask: ${redactSecrets(input.task)}\nWorkspace: ${this.project.name}\nBoundary: ${this.rootPath}\nWorking directory: ${workingPath}`, `## Git snapshot\n\n${JSON.stringify(status.git, null, 2)}`, `## Active agents\n\n${JSON.stringify(status.activeSessions, null, 2)}`, `## Open tasks and leases\n\n${JSON.stringify(status.openTasks, null, 2)}`, diff --git a/tests/helpers.ts b/tests/helpers.ts index 1fadbbd..9e4570f 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -4,7 +4,7 @@ import os from "node:os"; import path from "node:path"; export function createTestRepository(): string { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "devrelay-test-")); + const root = fs.mkdtempSync(path.join(os.tmpdir(), "agentrelay-test-")); const run = (args: string[]) => { const result = spawnSync("git", ["-C", root, ...args], { encoding: "utf8" }); if (result.status !== 0) throw new Error(result.stderr); @@ -14,9 +14,9 @@ export function createTestRepository(): string { run(["add", "README.md"]); run([ "-c", - "user.name=DevRelay Tests", + "user.name=AgentRelay Tests", "-c", - "user.email=devrelay@example.invalid", + "user.email=agentrelay@example.invalid", "commit", "-m", "initial fixture", @@ -29,7 +29,7 @@ export function removeTestRepository(root: string): void { } export function createTestWorkspace(): { root: string; repository: string } { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "devrelay-workspace-test-")); + const root = fs.mkdtempSync(path.join(os.tmpdir(), "agentrelay-workspace-test-")); const repository = path.join(root, "project-a"); fs.mkdirSync(repository); const run = (args: string[]) => { @@ -41,9 +41,9 @@ export function createTestWorkspace(): { root: string; repository: string } { run(["add", "README.md"]); run([ "-c", - "user.name=DevRelay Tests", + "user.name=AgentRelay Tests", "-c", - "user.email=devrelay@example.invalid", + "user.email=agentrelay@example.invalid", "commit", "-m", "initial nested fixture", diff --git a/tests/mcp.test.ts b/tests/mcp.test.ts index 983b185..d8db04d 100644 --- a/tests/mcp.test.ts +++ b/tests/mcp.test.ts @@ -21,7 +21,7 @@ describe("MCP surface", () => { it("advertises the ten coordination tools and accepts a join call", async () => { const server = createMcpServer(store); - const client = new Client({ name: "devrelay-test-client", version: "1.0.0" }); + const client = new Client({ name: "agentrelay-test-client", version: "1.0.0" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); await server.connect(serverTransport); await client.connect(clientTransport); diff --git a/tests/store.test.ts b/tests/store.test.ts index 61f3699..908b031 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -113,7 +113,7 @@ describe("ProjectStore multi-agent workflow", () => { task: "Finish OAuth callback", tokenBudget: 2_000, }) as { context: string; estimatedTokens: number }; - expect(context.context).toContain("DevRelay Context Pack"); + expect(context.context).toContain("AgentRelay Context Pack"); expect(context.context).toContain("Service account OAuth failed"); expect(context.context).not.toContain("do-not-capture"); expect(context.estimatedTokens).toBeLessThanOrEqual(2_000); diff --git a/tests/workspace.test.ts b/tests/workspace.test.ts index 0486f28..4591186 100644 --- a/tests/workspace.test.ts +++ b/tests/workspace.test.ts @@ -67,6 +67,24 @@ describe("workspace mode", () => { agentType: "other", workingDirectory: os.tmpdir(), }), - ).toThrow(/outside the DevRelay workspace/); + ).toThrow(/outside the AgentRelay workspace/); + }); + + it("migrates legacy DevRelay storage without changing project identity", () => { + const projectId = store.project.id; + store.close(); + const newDirectory = path.join(root, ".agentrelay"); + const legacyDirectory = path.join(root, ".devrelay"); + fs.renameSync(newDirectory, legacyDirectory); + fs.renameSync( + path.join(legacyDirectory, "agentrelay.db"), + path.join(legacyDirectory, "devrelay.db"), + ); + + store = new ProjectStore(root); + + expect(store.project.id).toBe(projectId); + expect(fs.existsSync(path.join(root, ".agentrelay", "agentrelay.db"))).toBe(true); + expect(fs.existsSync(legacyDirectory)).toBe(false); }); });