Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(ui): edit project AGENTS.md from the workbench (#381)

Call White051d3a7edfc7
diff --git a/tests/test_project_agents_md.py b/tests/test_project_agents_md.py
new file mode 100644
index 000000000..3831ea8e6
--- /dev/null
+++ b/tests/test_project_agents_md.py
@@ -0,0 +1,142 @@
+"""Unit tests for vibe.project_agents_md — AGENTS.md read fallback + the
+CLAUDE.md symlink reconciliation that backs the workbench editor."""
+
+import os
+from pathlib import Path
+
+from vibe.project_agents_md import read_agents_md, save_agents_md
+
+
+# --- read_agents_md -------------------------------------------------------
+
+
+def test_read_empty_dir_returns_empty(tmp_path: Path):
+ result = read_agents_md(tmp_path)
+ assert result == {
+ "content": "",
+ "source": "none",
+ "symlinked": False,
+ "claude_is_regular_file": False,
+ }
+
+
+def test_read_falls_back_to_claude(tmp_path: Path):
+ (tmp_path / "CLAUDE.md").write_text("from claude", encoding="utf-8")
+ result = read_agents_md(tmp_path)
+ assert result["content"] == "from claude"
+ assert result["source"] == "claude"
+ assert result["claude_is_regular_file"] is True
+ assert result["symlinked"] is False
+
+
+def test_read_prefers_agents_over_claude(tmp_path: Path):
+ (tmp_path / "AGENTS.md").write_text("from agents", encoding="utf-8")
+ (tmp_path / "CLAUDE.md").write_text("from claude", encoding="utf-8")
+ result = read_agents_md(tmp_path)
+ assert result["content"] == "from agents"
+ assert result["source"] == "agents"
+
+
+# --- save_agents_md: symlink ON ------------------------------------------
+
+
+def test_save_creates_symlink_on_empty_dir(tmp_path: Path):
+ result = save_agents_md(tmp_path, "hello", symlink=True)
+ agents = tmp_path / "AGENTS.md"
+ claude = tmp_path / "CLAUDE.md"
+ assert agents.read_text(encoding="utf-8") == "hello"
+ assert claude.is_symlink()
+ assert os.readlink(claude) == "AGENTS.md" # relative, sibling target
+ assert claude.read_text(encoding="utf-8") == "hello" # resolves to AGENTS.md
+ assert result["symlinked"] is True
+ assert result["migrated"] is False
+ assert result["symlink_error"] is None
+
+
+def test_save_migrates_real_claude_file(tmp_path: Path):
+ # A pre-existing real CLAUDE.md: its content was read into the editor, so
+ # saving with symlink on replaces it with a link and reports migrated.
+ (tmp_path / "CLAUDE.md").write_text("legacy claude", encoding="utf-8")
+ result = save_agents_md(tmp_path, "unified", symlink=True)
+ claude = tmp_path / "CLAUDE.md"
+ assert (tmp_path / "AGENTS.md").read_text(encoding="utf-8") == "unified"
+ assert claude.is_symlink()
+ assert claude.read_text(encoding="utf-8") == "unified"
+ assert result["migrated"] is True
+ assert result["claude_is_regular_file"] is False
+
+
+def test_save_symlink_is_idempotent(tmp_path: Path):
+ save_agents_md(tmp_path, "v1", symlink=True)
+ result = save_agents_md(tmp_path, "v2", symlink=True)
+ claude = tmp_path / "CLAUDE.md"
+ assert claude.is_symlink()
+ assert claude.read_text(encoding="utf-8") == "v2"
+ assert result["symlinked"] is True
+ assert result["migrated"] is False # already linked, not a fresh migration
+
+
+def test_save_repoints_foreign_symlink(tmp_path: Path):
+ # CLAUDE.md symlinked to something else gets re-pointed at AGENTS.md.
+ (tmp_path / "other.md").write_text("other", encoding="utf-8")
+ os.symlink("other.md", tmp_path / "CLAUDE.md")
+ result = save_agents_md(tmp_path, "content", symlink=True)
+ claude = tmp_path / "CLAUDE.md"
+ assert os.readlink(claude) == "AGENTS.md"
+ assert result["symlinked"] is True
+ assert result["migrated"] is False # it was a symlink, not a real file
+
+
+# --- save_agents_md: symlink OFF -----------------------------------------
+
+
+def test_save_off_removes_managed_symlink(tmp_path: Path):
+ save_agents_md(tmp_path, "x", symlink=True)
+ assert (tmp_path / "CLAUDE.md").is_symlink()
+ result = save_agents_md(tmp_path, "x", symlink=False)
+ assert not (tmp_path / "CLAUDE.md").exists()
+ assert (tmp_path / "AGENTS.md").read_text(encoding="utf-8") == "x"
+ assert result["symlinked"] is False
+
+
+def test_save_off_never_deletes_real_claude(tmp_path: Path):
+ (tmp_path / "CLAUDE.md").write_text("keep me", encoding="utf-8")
+ result = save_agents_md(tmp_path, "agents body", symlink=False)
+ claude = tmp_path / "CLAUDE.md"
+ assert claude.is_file() and not claude.is_symlink()
+ assert claude.read_text(encoding="utf-8") == "keep me" # untouched
+ assert (tmp_path / "AGENTS.md").read_text(encoding="utf-8") == "agents body"
+ assert result["claude_is_regular_file"] is True
+ assert result["symlinked"] is False
+
+
+def test_save_off_keeps_foreign_symlink(tmp_path: Path):
+ # Toggling off must not delete a CLAUDE.md symlink pointing somewhere else —
+ # only the CLAUDE.md -> AGENTS.md link this feature manages.
+ (tmp_path / "other.md").write_text("shared instructions", encoding="utf-8")
+ os.symlink("other.md", tmp_path / "CLAUDE.md")
+ result = save_agents_md(tmp_path, "agents body", symlink=False)
+ claude = tmp_path / "CLAUDE.md"
+ assert claude.is_symlink()
+ assert os.readlink(claude) == "other.md" # foreign link untouched
+ assert result["symlinked"] is False
+
+
+def test_save_preserves_claude_when_symlink_fails(tmp_path: Path, monkeypatch):
+ # If os.symlink fails (e.g. unprivileged Windows), the original CLAUDE.md
+ # must survive and no temp artifact should be left behind.
+ (tmp_path / "CLAUDE.md").write_text("keep me on failure", encoding="utf-8")
+
+ def _boom(*_args, **_kwargs):
+ raise OSError("operation not permitted")
+
+ monkeypatch.setattr(os, "symlink", _boom)
+ result = save_agents_md(tmp_path, "new agents body", symlink=True)
+ claude = tmp_path / "CLAUDE.md"
+ assert (tmp_path / "AGENTS.md").read_text(encoding="utf-8") == "new agents body"
+ assert claude.is_file() and not claude.is_symlink() # original preserved
+ assert claude.read_text(encoding="utf-8") == "keep me on failure"
+ assert result["symlink_error"] is not None
+ assert result["symlinked"] is False
+ assert result["migrated"] is False
+ assert not (tmp_path / "CLAUDE.md.vrtmp").exists() # temp cleaned up
diff --git a/ui/src/components/ui/editor-dialog.tsx b/ui/src/components/ui/editor-dialog.tsx
index a9d0a456f..27e00af79 100644
--- a/ui/src/components/ui/editor-dialog.tsx
+++ b/ui/src/components/ui/editor-dialog.tsx
@@ -1,6 +1,7 @@
import * as React from 'react';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { Loader2 } from 'lucide-react';
import { Dialog, DialogContent, DialogDescription, DialogTitle } from './dialog';
import { SegmentedRadio } from './segmented';
@@ -19,14 +20,26 @@ export interface EditorDialogProps {
description?: string;
/** Current text; the modal edits a private draft seeded from this on open. */
value: string;
- /** Commit the edited text. Called on Save, just before the modal closes. */
- onSave: (value: string) => void;
+ /** Commit the edited text. Called on Save. May return a promise — while it is
+ * pending the dialog shows a saving state and stays open; it closes on
+ * resolve and stays open on reject so the in-progress draft isn't lost. */
+ onSave: (value: string) => void | Promise<void>;
placeholder?: string;
/** Show the Edit/Preview toggle + Markdown preview (default true). */
markdownPreview?: boolean;
/** Optional left-aligned footer node derived from the live draft (e.g. a
* token/char count). */
footerHint?: (draft: string) => React.ReactNode;
+ /** When false, an outside click or Esc won't close the dialog — only the
+ * explicit Cancel / Save / X. Guards a long edit against an accidental
+ * dismiss. Defaults to true. */
+ dismissable?: boolean;
+ /** Optional banner rendered above the editor body, e.g. a "loaded from a
+ * fallback file" hint. */
+ notice?: React.ReactNode;
+ /** Optional full-width row rendered in the footer above the action buttons,
+ * e.g. a related toggle. */
+ footerSlot?: React.ReactNode;
}
// Generic full-size text editor in a modal: a large monospace textarea with an
@@ -44,10 +57,14 @@ export const EditorDialog: React.FC<EditorDialogProps> = ({
placeholder,
markdownPreview = true,
footerHint,
+ dismissable = true,
+ notice,
+ footerSlot,
}) => {
const { t } = useTranslation();
const [draft, setDraft] = useState(value);
const [mode, setMode] = useState<EditorMode>('edit');
+ const [saving, setSaving] = useState(false);
// Reseed the draft (and reset to edit mode) each time the modal opens, so a
// cancelled edit never leaks into the next open and an external change to
@@ -56,13 +73,27 @@ export const EditorDialog: React.FC<EditorDialogProps> = ({
if (open) {
setDraft(value);
setMode('edit');
+ setSaving(false);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
const handleSave = () => {
- onSave(draft);
- onClose();
+ const result = onSave(draft);
+ if (result instanceof Promise) {
+ // Async commit (e.g. persisting to a backend): show progress and keep the
+ // dialog open on failure so the draft isn't lost.
+ setSaving(true);
+ result.then(
+ () => {
+ setSaving(false);
+ onClose();
+ },
+ () => setSaving(false),
+ );
+ } else {
+ onClose();
+ }
};
const showPreview = markdownPreview && mode === 'preview';
@@ -71,10 +102,15 @@ export const EditorDialog: React.FC<EditorDialogProps> = ({
<Dialog
open={open}
onOpenChange={(next) => {
- if (!next) onClose();
+ // Never close mid-save; respect the non-dismissable opt-out.
+ if (!next && !saving) onClose();
}}
>
- <DialogContent className="flex h-[82vh] w-[92vw] max-w-[920px] flex-col gap-0 overflow-hidden p-0">
+ <DialogContent
+ className="flex h-[82vh] w-[92vw] max-w-[920px] flex-col gap-0 overflow-hidden p-0"
+ onInteractOutside={dismissable ? undefined : (e) => e.preventDefault()}
+ onEscapeKeyDown={dismissable ? undefined : (e) => e.preventDefault()}
+ >
{/* Header — title + optional subtitle. pr-12 leaves room for the
Dialog's built-in close X (absolute, top-right). */}
<div className="flex flex-col gap-1 border-b border-border px-5 py-4 pr-12">
@@ -86,6 +122,13 @@ export const EditorDialog: React.FC<EditorDialogProps> = ({
)}
</div>
+ {/* Optional notice banner (e.g. content loaded from a fallback file). */}
+ {notice && (
+ <div className="border-b border-border bg-surface-2 px-5 py-2 text-[12px] leading-relaxed text-muted">
+ {notice}
+ </div>
+ )}
+
{/* Toolbar — Edit/Preview toggle + Markdown hint (preview-capable only). */}
{markdownPreview && (
<div className="flex items-center justify-between gap-3 border-b border-border px-5 py-2.5">
@@ -132,16 +175,20 @@ export const EditorDialog: React.FC<EditorDialogProps> = ({
)}
</div>
- {/* Footer — optional draft-derived hint + actions. */}
- <div className="flex items-center justify-between gap-3 border-t border-border px-5 py-3">
- <span className="text-[11px] text-muted">{footerHint?.(draft)}</span>
- <div className="flex items-center gap-2">
- <Button type="button" variant="outline" size="sm" onClick={onClose}>
- {t('common.cancel')}
- </Button>
- <Button type="button" variant="brand" size="sm" onClick={handleSave}>
- {t('common.save')}
- </Button>
+ {/* Footer — optional slot (e.g. a toggle) above the draft hint + actions. */}
+ <div className="flex flex-col gap-3 border-t border-border px-5 py-3">
+ {footerSlot && <div>{footerSlot}</div>}
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-[11px] text-muted">{footerHint?.(draft)}</span>
+ <div className="flex items-center gap-2">
+ <Button type="button" variant="outline" size="sm" onClick={onClose} disabled={saving}>
+ {t('common.cancel')}
+ </Button>
+ <Button type="button" variant="brand" size="sm" onClick={handleSave} disabled={saving}>
+ {saving && <Loader2 className="size-3.5 animate-spin" />}
+ {t('common.save')}
+ </Button>
+ </div>
</div>
</div>
</DialogContent>
diff --git a/ui/src/components/workbench/ProjectAgentsMdDialog.tsx b/ui/src/components/workbench/ProjectAgentsMdDialog.tsx
new file mode 100644
index 000000000..4540d027d
--- /dev/null
+++ b/ui/src/components/workbench/ProjectAgentsMdDialog.tsx
@@ -0,0 +1,120 @@
+import * as React from 'react';
+import { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Loader2 } from 'lucide-react';
+
+import { useApi } from '../../context/ApiContext';
+import type { WorkbenchProject } from '../../context/ApiContext';
+import { useToast } from '../../context/ToastContext';
+import { EditorDialog } from '../ui/editor-dialog';
+import { Switch } from '../ui/switch';
+import { Dialog, DialogContent, DialogTitle } from '../ui/dialog';
+
+type AgentsMdData = {
+ content: string;
+ source: 'agents' | 'claude' | 'none';
+ symlinked: boolean;
+ claude_is_regular_file: boolean;
+};
+
+// Edit a project's AGENTS.md from the workbench. AGENTS.md is the canonical
+// agent-instructions file; CLAUDE.md is the legacy name, so the editor reads
+// AGENTS.md (falling back to CLAUDE.md when it's missing) and offers a "migrate
+// CLAUDE.md into AGENTS.md + keep them in sync via a symlink" toggle. Content
+// is fetched before the editor opens so EditorDialog seeds its draft from the
+// real file rather than an empty string.
+export const ProjectAgentsMdDialog: React.FC<{
+ project: WorkbenchProject;
+ open: boolean;
+ onClose: () => void;
+}> = ({ project, open, onClose }) => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
+ const [data, setData] = useState<AgentsMdData | null>(null);
+ const [symlink, setSymlink] = useState(true);
+
+ useEffect(() => {
+ if (!open) {
+ setData(null);
+ return;
+ }
+ let cancelled = false;
+ api.getProjectAgentsMd(project.id).then(
+ (loaded) => {
+ if (cancelled) return;
+ setData(loaded);
+ // Default the migration toggle on (recommended), EXCEPT when a separate
+ // real CLAUDE.md sits alongside an existing AGENTS.md: there a default-on
+ // save would silently replace CLAUDE.md content the editor never showed,
+ // so that case is an explicit opt-in.
+ const separateRealClaude = loaded.claude_is_regular_file && loaded.source !== 'claude';
+ setSymlink(!separateRealClaude);
+ },
+ () => {
+ // The shared apiFetch layer already surfaced the error toast.
+ if (cancelled) return;
+ onClose();
+ },
+ );
+ return () => {
+ cancelled = true;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open, project.id]);
+
+ if (!open) return null;
+
+ // Brief load before the editor opens so its draft seeds from the real file.
+ if (!data) {
+ return (
+ <Dialog open onOpenChange={(next) => !next && onClose()}>
+ <DialogContent className="flex max-w-sm items-center gap-3">
+ <DialogTitle className="sr-only">{t('agentsMd.title')}</DialogTitle>
+ <Loader2 className="size-4 animate-spin text-muted" />
+ <span className="text-[13px] text-muted">{t('agentsMd.loading')}</span>
+ </DialogContent>
+ </Dialog>
+ );
+ }
+
+ return (
+ <EditorDialog
+ open
+ onClose={onClose}
+ dismissable={false}
+ title={t('agentsMd.title')}
+ description={t('agentsMd.description')}
+ value={data.content}
+ placeholder={t('agentsMd.placeholder')}
+ notice={data.source === 'claude' ? t('agentsMd.loadedFromClaude') : undefined}
+ footerSlot={
+ <div className="flex items-start gap-2.5">
+ <Switch
+ checked={symlink}
+ onCheckedChange={setSymlink}
+ label={t('agentsMd.symlinkToggle')}
+ className="mt-0.5"
+ />
+ <span className="text-[12px] leading-relaxed text-foreground">
+ {t('agentsMd.symlinkToggle')}
+ {symlink && data.claude_is_regular_file && (
+ <span className="mt-0.5 block text-[11px] text-gold">
+ {t('agentsMd.symlinkMigrateWarning')}
+ </span>
+ )}
+ </span>
+ </div>
+ }
+ onSave={async (content) => {
+ // A failed save rejects here: the apiFetch layer shows the error toast,
+ // and EditorDialog keeps the dialog open so the in-progress draft isn't lost.
+ const res = await api.saveProjectAgentsMd(project.id, { content, symlink });
+ showToast(
+ res.symlink_error ? t('agentsMd.savedSymlinkFailed') : t('agentsMd.saved'),
+ res.symlink_error ? 'warning' : 'success',
+ );
+ }}
+ />
+ );
+};
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsx
index 202a05eed..71594cbde 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx
@@ -9,6 +9,7 @@ import {
ChevronDown,
ChevronRight,
Ellipsis,
+ FileText,
Folder,
FolderOpen,
FolderPlus,
@@ -31,6 +32,7 @@ import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Markdown } from '../ui/markdown';
import { NewProjectDialog } from './NewProjectDialog';
+import { ProjectAgentsMdDialog } from './ProjectAgentsMdDialog';
interface CapabilityNavItem {
to: string;
@@ -224,6 +226,7 @@ const ProjectRow: React.FC<{
const [renaming, setRenaming] = useState(false);
const [renameDraft, setRenameDraft] = useState(project.display_name);
const [menuOpen, setMenuOpen] = useState(false);
+ const [agentsMdOpen, setAgentsMdOpen] = useState(false);
const renameInputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
@@ -316,6 +319,17 @@ const ProjectRow: React.FC<{
<Pencil className="size-3 text-muted" />
{t('workbench.projectRename')}
</button>
+ <button
+ type="button"
+ onClick={() => {
+ setMenuOpen(false);
+ setAgentsMdOpen(true);
+ }}
+ className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04]"
+ >
+ <FileText className="size-3 text-muted" />
+ {t('workbench.projectEditAgents')}
+ </button>
<button
type="button"
onClick={async () => {
@@ -413,6 +427,12 @@ const ProjectRow: React.FC<{
)}
</div>
)}
+
+ <ProjectAgentsMdDialog
+ project={project}
+ open={agentsMdOpen}
+ onClose={() => setAgentsMdOpen(false)}
+ />
</div>
);
};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 452a5b3e9..91a714bce 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -99,6 +99,16 @@ export type ApiContextType = {
createProject: (payload: { folder_path: string; display_name?: string }) => Promise<WorkbenchProject>;
updateProject: (projectId: string, payload: { display_name?: string; folder_path?: string }) => Promise<WorkbenchProject>;
archiveProject: (projectId: string) => Promise<WorkbenchProject>;
+ getProjectAgentsMd: (projectId: string) => Promise<{
+ content: string;
+ source: 'agents' | 'claude' | 'none';
+ symlinked: boolean;
+ claude_is_regular_file: boolean;
+ }>;
+ saveProjectAgentsMd: (
+ projectId: string,
+ payload: { content: string; symlink: boolean },
+ ) => Promise<{ ok: boolean; symlinked: boolean; claude_is_regular_file: boolean; migrated: boolean; symlink_error: string | null }>;
listSessions: (params?: { projectId?: string; status?: 'active' | 'archived' | 'all'; limit?: number; beforeId?: string }) => Promise<{ sessions: WorkbenchSession[]; next_before_id: string | null }>;
createSession: (payload: WorkbenchSessionCreate) => Promise<WorkbenchSession>;
getSession: (sessionId: string) => Promise<WorkbenchSession>;
@@ -1142,6 +1152,19 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
return res.json();
},
archiveProject: (projectId) => deleteJson(`/api/projects/${encodeURIComponent(projectId)}`),
+ getProjectAgentsMd: (projectId) =>
+ getJson(`/api/projects/${encodeURIComponent(projectId)}/agents-md`),
+ saveProjectAgentsMd: async (projectId, payload) => {
+ const res = await apiFetch(`/api/projects/${encodeURIComponent(projectId)}/agents-md`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+ if (!res.ok) {
+ await handleApiError(res, `PUT /api/projects/${projectId}/agents-md`);
+ }
+ return res.json();
+ },
listSessions: (params) => {
const search = new URLSearchParams();
if (params?.projectId) search.set('project_id', params.projectId);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index d4f0a68f1..9aa27a663 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -461,6 +461,7 @@
"addSession": "New session in this project",
"projectActions": "Project actions",
"projectRename": "Rename",
+ "projectEditAgents": "Edit AGENTS.md",
"projectArchive": "Archive",
"projectArchiveConfirm": "Archive project \"{{name}}\"? Session history is preserved; it just stops showing in the sidebar.",
"projectRenamePlaceholder": "New name",
@@ -1358,6 +1359,17 @@
"markdownHint": "Markdown supported",
"previewEmpty": "Nothing to preview yet."
},
+ "agentsMd": {
+ "title": "Edit AGENTS.md",
+ "description": "Edit this project's AGENTS.md — the project-level instructions handed to the agent.",
+ "placeholder": "Write this project's AGENTS.md in Markdown…",
+ "loading": "Loading…",
+ "loadedFromClaude": "This project has no AGENTS.md yet — loaded CLAUDE.md's content as a starting point. Saving will write AGENTS.md.",
+ "symlinkToggle": "Migrate CLAUDE.md into AGENTS.md and symlink them to stay in sync (recommended)",
+ "symlinkMigrateWarning": "The current CLAUDE.md file will be deleted and replaced with a symlink to AGENTS.md.",
+ "saved": "AGENTS.md saved",
+ "savedSymlinkFailed": "AGENTS.md saved, but the symlink could not be created."
+ },
"skills": {
"title": "Skills",
"subtitle": "Manage global and project skills across your agent backends · powered by askill.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index ca6ed1bb5..c8b08b579 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -461,6 +461,7 @@
"addSession": "在该项目新建会话",
"projectActions": "项目操作",
"projectRename": "重命名",
+ "projectEditAgents": "编辑 AGENTS.md",
"projectArchive": "归档",
"projectArchiveConfirm": "确定归档项目「{{name}}」?会话历史会保留,侧栏不再显示。",
"projectRenamePlaceholder": "新名字",
@@ -1357,6 +1358,17 @@
"markdownHint": "支持 Markdown",
"previewEmpty": "暂无可预览内容。"
},
+ "agentsMd": {
+ "title": "编辑 AGENTS.md",
+ "description": "编辑此项目的 AGENTS.md —— 交给 Agent 的项目级指令文件。",
+ "placeholder": "用 Markdown 写下这个项目的 AGENTS.md…",
+ "loading": "加载中…",
+ "loadedFromClaude": "本项目还没有 AGENTS.md,已载入 CLAUDE.md 的内容作为起点;保存后会写入 AGENTS.md。",
+ "symlinkToggle": "将 CLAUDE.md 迁移至 AGENTS.md 并创建软链接同步二者(推荐)",
+ "symlinkMigrateWarning": "当前的 CLAUDE.md 文件将被删除,并替换为指向 AGENTS.md 的软链接。",
+ "saved": "AGENTS.md 已保存",
+ "savedSymlinkFailed": "AGENTS.md 已保存,但软链接创建失败。"
+ },
"skills": {
"title": "技能",
"subtitle": "跨各 Agent 后端管理全局与项目级技能 · 基于 askill。",
diff --git a/vibe/project_agents_md.py b/vibe/project_agents_md.py
new file mode 100644
index 000000000..4cea7d240
--- /dev/null
+++ b/vibe/project_agents_md.py
@@ -0,0 +1,120 @@
+"""Read/write a project's ``AGENTS.md`` with a ``CLAUDE.md`` fallback.
+
+The workbench lets a user edit the project-level ``AGENTS.md`` straight from the
+Web UI. ``AGENTS.md`` is the canonical agent-instructions file; ``CLAUDE.md`` is
+the legacy / Claude-specific name. To keep both tool families working off one
+source of truth, the editor offers an optional "migrate ``CLAUDE.md`` into
+``AGENTS.md`` and symlink them" toggle:
+
+- **Read** prefers ``AGENTS.md``; when it is missing it falls back to the
+ ``CLAUDE.md`` content so an existing project is not shown an empty editor.
+- **Save** always writes ``AGENTS.md``. When the symlink toggle is on, it makes
+ ``CLAUDE.md`` a symlink pointing at ``AGENTS.md`` — *replacing a real
+ ``CLAUDE.md`` file if present*. That is safe because the file's content was
+ already read into the editor (and thus written into ``AGENTS.md``) before the
+ replacement, so the two are unified rather than losing data.
+
+The functions here are deliberately pure filesystem helpers that operate on an
+already-resolved project directory, so the HTTP layer only handles project-id
+resolution and the symlink reconciliation stays unit-testable in isolation.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+AGENTS_FILENAME = "AGENTS.md"
+CLAUDE_FILENAME = "CLAUDE.md"
+
+
+def _claude_points_to_agents(claude: Path) -> bool:
+ """True when ``CLAUDE.md`` is a symlink that resolves to the sibling
+ ``AGENTS.md`` (the state the toggle maintains)."""
+ if not claude.is_symlink():
+ return False
+ try:
+ target = os.readlink(claude)
+ except OSError:
+ return False
+ resolved = (claude.parent / target).resolve()
+ return resolved == (claude.parent / AGENTS_FILENAME).resolve()
+
+
+def _is_regular_file(path: Path) -> bool:
+ """A real file, i.e. exists and is not a symlink."""
+ return path.exists() and not path.is_symlink()
+
+
+def read_agents_md(project_dir: Path) -> dict:
+ """Return the editor seed for ``project_dir``.
+
+ ``source`` is ``"agents"`` / ``"claude"`` / ``"none"`` so the UI can show a
+ "loaded from CLAUDE.md" notice when the content came from the fallback.
+ """
+ agents = project_dir / AGENTS_FILENAME
+ claude = project_dir / CLAUDE_FILENAME
+ if agents.is_file():
+ content, source = agents.read_text(encoding="utf-8"), "agents"
+ elif claude.is_file():
+ content, source = claude.read_text(encoding="utf-8"), "claude"
+ else:
+ content, source = "", "none"
+ return {
+ "content": content,
+ "source": source,
+ "symlinked": _claude_points_to_agents(claude),
+ "claude_is_regular_file": _is_regular_file(claude),
+ }
+
+
+def save_agents_md(project_dir: Path, content: str, symlink: bool) -> dict:
+ """Write ``AGENTS.md`` and reconcile the ``CLAUDE.md`` symlink to ``symlink``.
+
+ Invariant: this only ever creates, re-points, or removes a *symlink* named
+ ``CLAUDE.md`` — except when ``symlink`` is on, where a real ``CLAUDE.md`` is
+ intentionally replaced by the symlink (its content is preserved in
+ ``AGENTS.md``, written just above). Toggling off never deletes a real file.
+ """
+ agents = project_dir / AGENTS_FILENAME
+ claude = project_dir / CLAUDE_FILENAME
+ agents.write_text(content, encoding="utf-8")
+
+ migrated = False
+ symlink_error: str | None = None
+ if symlink:
+ # Ensure CLAUDE.md -> AGENTS.md; idempotent when already so. Build the
+ # new link under a temp name and atomically swap it in, so a failed
+ # os.symlink (e.g. unprivileged Windows) never deletes the original
+ # CLAUDE.md without leaving a replacement behind.
+ if not _claude_points_to_agents(claude):
+ was_regular = _is_regular_file(claude)
+ tmp = claude.with_name(CLAUDE_FILENAME + ".vrtmp")
+ try:
+ if tmp.is_symlink() or tmp.exists():
+ tmp.unlink()
+ os.symlink(AGENTS_FILENAME, tmp) # relative target, sibling file
+ os.replace(tmp, claude) # atomic swap over the existing file/link
+ migrated = was_regular # we replaced a real CLAUDE.md file
+ except OSError as err: # e.g. unprivileged Windows symlink
+ symlink_error = str(err)
+ if tmp.is_symlink() or tmp.exists():
+ try:
+ tmp.unlink()
+ except OSError:
+ pass
+ else:
+ # Only remove the CLAUDE.md -> AGENTS.md link this feature manages; a
+ # foreign symlink or a real CLAUDE.md file is left untouched.
+ if _claude_points_to_agents(claude):
+ try:
+ claude.unlink()
+ except OSError as err:
+ symlink_error = str(err)
+
+ return {
+ "symlinked": _claude_points_to_agents(claude),
+ "claude_is_regular_file": _is_regular_file(claude),
+ "migrated": migrated,
+ "symlink_error": symlink_error,
+ }
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index bfd82eb07..477c4b915 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2780,6 +2780,45 @@ def _project_no_folder_error():
)
[email protected]("/api/projects/<project_id>/agents-md", methods=["GET"])
+def project_agents_md_get(project_id: str):
+ """Read the project's AGENTS.md (falling back to CLAUDE.md) for the editor."""
+ from vibe.project_agents_md import read_agents_md
+
+ try:
+ project_dir = _resolve_project_dir(project_id)
+ except LookupError as err:
+ return _project_not_found(err)
+ except _ProjectNoFolder:
+ return _project_no_folder_error()
+ folder = Path(project_dir)
+ if not folder.is_dir():
+ return jsonify({"error": f"project folder not found: {folder}"}), 400
+ return jsonify(read_agents_md(folder))
+
+
[email protected]("/api/projects/<project_id>/agents-md", methods=["PUT"])
+def project_agents_md_save(project_id: str):
+ """Write the project's AGENTS.md and reconcile the optional CLAUDE.md symlink."""
+ from vibe.project_agents_md import save_agents_md
+
+ payload = request.json or {}
+ content = payload.get("content")
+ if content is None:
+ return jsonify({"error": "content is required"}), 400
+ symlink = bool(payload.get("symlink", True))
+ try:
+ project_dir = _resolve_project_dir(project_id)
+ except LookupError as err:
+ return _project_not_found(err)
+ except _ProjectNoFolder:
+ return _project_no_folder_error()
+ folder = Path(project_dir)
+ if not folder.is_dir():
+ return jsonify({"error": f"project folder not found: {folder}"}), 400
+ return jsonify({"ok": True, **save_agents_md(folder, str(content), symlink)})
+
+
# Agent Skills — thin shells over api.* (which wraps the askill CLI). Pure
# data CRUD, so it stays in the UI-server process via core/services (no
# dispatch-socket round-trip). See docs/plans/workbench-skills-page.md.