Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(device): discover AGENTS.md and skills up to the repository root (#22961)

YuTengjingef07539e4c9a
diff --git a/apps/desktop/src/main/controllers/__tests__/WorkspaceCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/WorkspaceCtr.test.ts
index 7abf09e5f57..ecbb970454e 100644
--- a/apps/desktop/src/main/controllers/__tests__/WorkspaceCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/WorkspaceCtr.test.ts
@@ -18,6 +18,13 @@ vi.mock('electron', () => ({
vi.mock('node:fs/promises', () => ({
readFile: vi.fn(),
readdir: vi.fn(),
+ // Instruction files are deduped by their real path (CLAUDE.md is often a
+ // symlink to AGENTS.md); no fixture here uses symlinks.
+ realpath: vi.fn(async (target: string) => target),
+ // No `.git` anywhere, so the scan stays in the working directory.
+ stat: vi.fn(async () => {
+ throw new Error('ENOENT');
+ }),
}));
vi.mock('@lobechat/device-control/claude-code-memory', () => ({
@@ -84,8 +91,8 @@ describe('WorkspaceCtr', () => {
expect(result.skills.map((s) => s.name)).toEqual(['reviewer', 'spa-routes']);
expect(result.instructions).toEqual([
- { content: '# Agents', source: 'AGENTS.md' },
- { content: '# Claude', source: 'CLAUDE.md' },
+ { content: '# Agents', path: '/proj/AGENTS.md', source: 'AGENTS.md' },
+ { content: '# Claude', path: '/proj/CLAUDE.md', source: 'CLAUDE.md' },
]);
// Approves the scanned root for the lobe-file:// preview protocol.
expect(mockLocalFileProtocolManager.approveIndexedProjectRoot).toHaveBeenCalledWith('/proj');
diff --git a/apps/server/src/routers/lambda/__tests__/deviceWorkspaceGuard.test.ts b/apps/server/src/routers/lambda/__tests__/deviceWorkspaceGuard.test.ts
index 98c4c5f15e6..9f736f95cc1 100644
--- a/apps/server/src/routers/lambda/__tests__/deviceWorkspaceGuard.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/deviceWorkspaceGuard.test.ts
@@ -7,6 +7,7 @@ import {
assertWorkspaceDeviceEditable,
assertWorkspaceDeviceVisible,
assertWorkspaceRootApproved,
+ registerDeviceSkillRoots,
} from '../deviceWorkspaceGuard';
const mockModel = (
@@ -78,6 +79,34 @@ describe('assertWorkspaceRootApproved', () => {
).rejects.toBeInstanceOf(TRPCError);
});
+ it('keeps parent-level skill roots of earlier projects while their project stays approved', async () => {
+ registerDeviceSkillRoots('dev-skills', [
+ { projectRoot: '/repo-a/pkg', root: '/repo-a/.agents/skills' },
+ ]);
+ registerDeviceSkillRoots('dev-skills', [
+ { projectRoot: '/repo-b/pkg', root: '/repo-b/.agents/skills' },
+ ]);
+ const model = mockModel({ workingDirs: [{ path: '/repo-a/pkg' }, { path: '/repo-b/pkg' }] });
+
+ await expect(
+ assertWorkspaceRootApproved(model, 'dev-skills', '/repo-a/.agents/skills'),
+ ).resolves.toBeUndefined();
+ await expect(
+ assertWorkspaceRootApproved(model, 'dev-skills', '/repo-b/.agents/skills'),
+ ).resolves.toBeUndefined();
+ });
+
+ it('revokes a parent-level skill root once its project is no longer approved', async () => {
+ registerDeviceSkillRoots('dev-revoke', [
+ { projectRoot: '/repo-a/pkg', root: '/repo-a/.agents/skills' },
+ ]);
+ const model = mockModel({ workingDirs: [{ path: '/elsewhere' }] });
+
+ await expect(
+ assertWorkspaceRootApproved(model, 'dev-revoke', '/repo-a/.agents/skills'),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
it('rejects an empty workspace root with BAD_REQUEST before hitting the DB', async () => {
const model = mockModel({ workingDirs: [{ path: '/Users/me/proj' }] });
await expect(assertWorkspaceRootApproved(model, 'dev-1', '')).rejects.toMatchObject({
diff --git a/apps/server/src/routers/lambda/device/projectFiles.ts b/apps/server/src/routers/lambda/device/projectFiles.ts
index d4f5a00db8c..d3fce7b5494 100644
--- a/apps/server/src/routers/lambda/device/projectFiles.ts
+++ b/apps/server/src/routers/lambda/device/projectFiles.ts
@@ -276,14 +276,22 @@ export const projectFilesRouter = router({
workspaceId: ctx.workspaceId,
});
- // Register device-scoped skill roots (~/.agents/skills / ~/.claude/skills)
+ // Register skill roots outside the scanned directory β€” device-scoped
+ // (~/.agents/skills, …) and project skills found in a parent directory β€”
// in an in-memory cache so subsequent getLocalFilePreview calls pass the
// workspace root guard without polluting the UI's working-directory list.
+ // A parent-level grant is tied to the scanned project, so it holds only
+ // while that project is an approved root.
if (result?.skills) {
- const skillRoots = [
- ...new Set(result.skills.filter((s) => s.scope === 'device').map((s) => s.previewRoot)),
- ].filter(Boolean);
- registerDeviceSkillRoots(input.deviceId, skillRoots);
+ registerDeviceSkillRoots(
+ input.deviceId,
+ result.skills.flatMap((s) => {
+ if (s.scope === 'device') return [{ root: s.previewRoot }];
+ if (s.previewRoot !== input.scope)
+ return [{ projectRoot: input.scope, root: s.previewRoot }];
+ return [];
+ }),
+ );
}
return result ?? null;
diff --git a/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts b/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts
index 40fa6e121c7..c941bbc9c6b 100644
--- a/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts
+++ b/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts
@@ -36,16 +36,40 @@ export const assertWorkspaceDeviceEditable = (
};
/**
- * In-memory cache of device-scoped skill preview roots, populated by
- * `listProjectSkills` and consumed by `assertWorkspaceRootApproved` to
- * authorize read-only file previews without persisting skill paths into
- * the DB (which would leak into the UI's working-directory list).
+ * In-memory cache of skill preview roots outside a project's working
+ * directory, populated by `listProjectSkills` and consumed by
+ * `assertWorkspaceRootApproved` to authorize read-only file previews without
+ * persisting skill paths into the DB (which would leak into the UI's
+ * working-directory list).
+ *
+ * Two kinds of grant: device skill directories (`~/.agents/skills`, …) hold
+ * unconditionally; project skill directories found in a parent of the scanned
+ * project carry that project and hold only while it is still approved, like
+ * the memory grants below. Accumulates per device so scanning project B does
+ * not revoke project A's grants, oldest evicted past the cap.
*/
-const deviceSkillRoots = new Map<string, Set<string>>();
+const MAX_SKILL_ROOTS_PER_DEVICE = 50;
+
+export interface DeviceSkillRootGrant {
+ /** The project the skill directory was found above; absent for device skills. */
+ projectRoot?: string;
+ root: string;
+}
+
+const deviceSkillRoots = new Map<string, Map<string, DeviceSkillRootGrant>>();
+
+export const registerDeviceSkillRoots = (deviceId: string, grants: DeviceSkillRootGrant[]) => {
+ if (grants.length === 0) return;
-export const registerDeviceSkillRoots = (deviceId: string, roots: string[]) => {
- if (roots.length === 0) return;
- deviceSkillRoots.set(deviceId, new Set(roots));
+ const current = deviceSkillRoots.get(deviceId) ?? new Map<string, DeviceSkillRootGrant>();
+ for (const grant of grants) {
+ if (!grant.root) continue;
+ const key = JSON.stringify([grant.projectRoot ?? null, grant.root]);
+ current.delete(key);
+ current.set(key, grant);
+ }
+ while (current.size > MAX_SKILL_ROOTS_PER_DEVICE) current.delete(current.keys().next().value!);
+ deviceSkillRoots.set(deviceId, current);
};
/**
@@ -82,9 +106,14 @@ export const registerDeviceMemoryRoot = (deviceId: string, grant: DeviceMemoryRo
deviceMemoryRoots.set(deviceId, grants);
};
-const isWithinSkillRoots = (deviceId: string, workingDirectory: string): boolean =>
- [...(deviceSkillRoots.get(deviceId) ?? [])].some((root) =>
- isPathWithinRoot(root, workingDirectory),
+const isWithinSkillRoots = (
+ deviceId: string,
+ workingDirectory: string,
+ isProjectApproved: (projectRoot: string) => boolean,
+): boolean =>
+ [...(deviceSkillRoots.get(deviceId)?.values() ?? [])].some(
+ ({ projectRoot, root }) =>
+ isPathWithinRoot(root, workingDirectory) && (!projectRoot || isProjectApproved(projectRoot)),
);
const isWithinMemoryGrant = (
@@ -146,7 +175,7 @@ export const assertWorkspaceRootApproved = async (
approvedRoots.some((root) => isPathWithinRoot(root, target));
const approved =
isApprovedRoot(workingDirectory) ||
- isWithinSkillRoots(deviceId, workingDirectory) ||
+ isWithinSkillRoots(deviceId, workingDirectory, isApprovedRoot) ||
isWithinMemoryGrant(deviceId, workingDirectory, isApprovedRoot);
if (!approved) {
diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
index ee106715369..c3f6d4c2c34 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
@@ -772,8 +772,9 @@ export const prepareOperation = async (
};
}
- // Project skills + the root AGENTS.md are discovered server-side by
- // scanning the device's bound project directory ("workspace init"), cached
+ // Project skills + AGENTS.md are discovered server-side by scanning the
+ // device's bound project directory and its parents up to the repository
+ // root ("workspace init"), cached
// on `devices.workingDirs` and reused within the TTL. Skills surface in
// `<available_skills>` (metadata only β€” SKILL.md bodies are read lazily at
// activation via `local-system` readFile, which `serverRuntimes/skills.ts`
@@ -819,8 +820,9 @@ export const prepareOperation = async (
// concatenate them. Returning them rather than stamping `agentConfig` keeps
// run context off the agent's configuration.
if (workspaceInit.workspace.instructions.length) {
- projectInstructions = workspaceInit.workspace.instructions.map(({ content, source }) => ({
+ projectInstructions = workspaceInit.workspace.instructions.map(({ content, path, source }) => ({
content,
+ path,
source,
}));
log(
diff --git a/packages/context-engine/src/providers/ProjectInstructionsInjector.ts b/packages/context-engine/src/providers/ProjectInstructionsInjector.ts
index aba70659c6c..68f3ae84f19 100644
--- a/packages/context-engine/src/providers/ProjectInstructionsInjector.ts
+++ b/packages/context-engine/src/providers/ProjectInstructionsInjector.ts
@@ -13,6 +13,11 @@ const log = debug('context-engine:provider:ProjectInstructionsInjector');
export interface ProjectInstructionFile {
content: string;
+ /**
+ * Absolute path of the file, telling the model which directory the rules
+ * cover when several levels of a repository contribute one.
+ */
+ path?: string;
/** Where the file came from, e.g. `AGENTS.md` β€” surfaced to the model. */
source: string;
}
@@ -23,8 +28,8 @@ export interface ProjectInstructionsInjectorConfig {
}
/**
- * Injects a project's root instruction files (`AGENTS.md` / `CLAUDE.md`) into
- * the system message.
+ * Injects a project's instruction files (`AGENTS.md` / `CLAUDE.md`, from the
+ * working directory up to the repository root) into the system message.
*
* Takes the files rather than a rendered block: wrapping them is presentation,
* which belongs to the pipeline that owns the system message. The server used
@@ -55,8 +60,8 @@ export class ProjectInstructionsInjector extends BaseSystemRoleProvider {
return instructions
.map(
- ({ content, source }) =>
- `<project_instructions source="${source}">\n${content}\n</project_instructions>`,
+ ({ content, path, source }) =>
+ `<project_instructions source="${source}"${path ? ` path="${path}"` : ''}>\n${content}\n</project_instructions>`,
)
.join('\n\n');
}
diff --git a/packages/context-engine/src/providers/__tests__/ProjectInstructionsInjector.test.ts b/packages/context-engine/src/providers/__tests__/ProjectInstructionsInjector.test.ts
index 25cb9449a90..2b14cb81b38 100644
--- a/packages/context-engine/src/providers/__tests__/ProjectInstructionsInjector.test.ts
+++ b/packages/context-engine/src/providers/__tests__/ProjectInstructionsInjector.test.ts
@@ -38,13 +38,32 @@ describe('ProjectInstructionsInjector', () => {
});
const system = systemContentOf(result);
- expect(system).toContain('<project_instructions source="AGENTS.md">\nUse bun.\n</project_instructions>');
+ expect(system).toContain(
+ '<project_instructions source="AGENTS.md">\nUse bun.\n</project_instructions>',
+ );
expect(system).toContain('<project_instructions source="CLAUDE.md">');
// Appended after the persona, not replacing it.
expect(system.startsWith('You are a helpful assistant.')).toBe(true);
expect(result.metadata.projectInstructionCount).toBe(2);
});
+ it('names the file path when the scan recorded one', async () => {
+ const result = await run({
+ instructions: [
+ { content: 'Repo rules.', path: '/repo/AGENTS.md', source: 'AGENTS.md' },
+ { content: 'Web rules.', path: '/repo/packages/web/AGENTS.md', source: 'AGENTS.md' },
+ ],
+ });
+
+ const system = systemContentOf(result);
+ expect(system).toContain(
+ '<project_instructions source="AGENTS.md" path="/repo/AGENTS.md">\nRepo rules.\n</project_instructions>',
+ );
+ expect(system).toContain(
+ '<project_instructions source="AGENTS.md" path="/repo/packages/web/AGENTS.md">',
+ );
+ });
+
it('keeps the files in the order they were collected', async () => {
const result = await run({
instructions: [
@@ -58,7 +77,11 @@ describe('ProjectInstructionsInjector', () => {
});
it('leaves the system message untouched when there are no files', async () => {
- for (const config of [{}, { instructions: [] }, { enabled: false, instructions: [{ content: 'x', source: 'a.md' }] }]) {
+ for (const config of [
+ {},
+ { instructions: [] },
+ { enabled: false, instructions: [{ content: 'x', source: 'a.md' }] },
+ ]) {
const result = await run(config);
expect(systemContentOf(result)).toBe('You are a helpful assistant.');
}
diff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.ts
index 075c54376a8..759e6cb4aa6 100644
--- a/packages/device-control/src/__tests__/dispatch.test.ts
+++ b/packages/device-control/src/__tests__/dispatch.test.ts
@@ -146,7 +146,9 @@ describe('executeDeviceRpc', () => {
};
expect(result.skills.map((s) => s.name)).toEqual(['spa-routes']);
- expect(result.instructions).toEqual([{ content: '# Agents', source: 'AGENTS.md' }]);
+ expect(result.instructions).toEqual([
+ { content: '# Agents', path: path.join(root, 'AGENTS.md'), source: 'AGENTS.md' },
+ ]);
expect(deps.approveProjectRoot).toHaveBeenCalledWith(root);
});
diff --git a/packages/device-control/src/__tests__/workspace.test.ts b/packages/device-control/src/__tests__/workspace.test.ts
new file mode 100644
index 00000000000..c96ffe15b75
--- /dev/null
+++ b/packages/device-control/src/__tests__/workspace.test.ts
@@ -0,0 +1,183 @@
+import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises';
+import type * as NodeOs from 'node:os';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { initWorkspace, listProjectSkills } from '../workspace';
+
+let base: string;
+let home: string;
+
+vi.mock('node:os', async (importOriginal) => {
+ const actual = await importOriginal<typeof NodeOs>();
+ return { ...actual, homedir: () => home };
+});
+
+const write = async (file: string, content: string) => {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, content);
+};
+
+const writeSkill = (dir: string, name: string, description = `${name} skill`) =>
+ write(
+ path.join(dir, name, 'SKILL.md'),
+ `---\nname: ${name}\ndescription: ${description}\n---\n\n# ${name}\n`,
+ );
+
+beforeEach(async () => {
+ base = await mkdtemp(path.join(tmpdir(), 'workspace-scan-'));
+ home = path.join(base, 'home');
+ await mkdir(home, { recursive: true });
+});
+
+afterEach(async () => {
+ await rm(base, { force: true, recursive: true });
+});
+
+describe('initWorkspace', () => {
+ it('reads instructions from the working directory up to the repository root, root first', async () => {
+ const repo = path.join(base, 'outside', 'repo');
+ const pkg = path.join(repo, 'packages', 'web');
+ await mkdir(path.join(repo, '.git'), { recursive: true });
+ await write(path.join(base, 'outside', 'AGENTS.md'), 'above the repository');
+ await write(path.join(repo, 'AGENTS.md'), 'repo rules');
+ await write(path.join(pkg, 'AGENTS.md'), 'web rules');
+
+ const result = await initWorkspace({ scope: pkg });
+
+ expect(result.instructions).toEqual([
+ { content: 'repo rules', path: path.join(repo, 'AGENTS.md'), source: 'AGENTS.md' },
+ { content: 'web rules', path: path.join(pkg, 'AGENTS.md'), source: 'AGENTS.md' },
+ ]);
+ });
+
+ it('stops at a .git file, as in a worktree or submodule', async () => {
+ const outer = path.join(base, 'outer');
+ const submodule = path.join(outer, 'sub');
+ await mkdir(path.join(outer, '.git'), { recursive: true });
+ await write(path.join(submodule, '.git'), 'gitdir: ../.git/modules/sub');
+ await write(path.join(outer, 'AGENTS.md'), 'outer rules');
+ await write(path.join(submodule, 'AGENTS.md'), 'sub rules');
+
+ const result = await initWorkspace({ scope: submodule });
+
+ expect(result.instructions.map((item) => item.content)).toEqual(['sub rules']);
+ });
+
+ it('reads only the working directory outside a repository', async () => {
+ const dir = path.join(base, 'plain', 'dir');
+ await write(path.join(base, 'plain', 'AGENTS.md'), 'parent rules');
+ await write(path.join(dir, 'AGENTS.md'), 'dir rules');
+
+ const result = await initWorkspace({ scope: dir });
+
+ expect(result.instructions.map((item) => item.content)).toEqual(['dir rules']);
+ });
+
+ it('injects a CLAUDE.md symlinked to AGENTS.md once', async () => {
+ const repo = path.join(base, 'repo');
+ await mkdir(path.join(repo, '.git'), { recursive: true });
+ await write(path.join(repo, 'AGENTS.md'), 'shared rules');
+ await symlink('AGENTS.md', path.join(repo, 'CLAUDE.md'));
+
+ const result = await initWorkspace({ scope: repo });
+
+ expect(result.instructions).toEqual([
+ { content: 'shared rules', path: path.join(repo, 'AGENTS.md'), source: 'AGENTS.md' },
+ ]);
+ });
+
+ it('keeps the nearest files when the total budget runs out', async () => {
+ const repo = path.join(base, 'repo');
+ const pkg = path.join(repo, 'pkg');
+ await mkdir(path.join(repo, '.git'), { recursive: true });
+ await write(path.join(repo, 'AGENTS.md'), 'r'.repeat(70 * 1024));
+ await write(path.join(pkg, 'AGENTS.md'), 'a'.repeat(70 * 1024));
+ await write(path.join(pkg, 'CLAUDE.md'), 'c'.repeat(70 * 1024));
+
+ const result = await initWorkspace({ scope: pkg });
+
+ expect(result.instructions.map((item) => [item.path, item.content.length])).toEqual([
+ [path.join(pkg, 'AGENTS.md'), 64 * 1024],
+ [path.join(pkg, 'CLAUDE.md'), 64 * 1024],
+ ]);
+ });
+
+ it('counts the budget in UTF-8 bytes, not characters', async () => {
+ const repo = path.join(base, 'repo');
+ await mkdir(path.join(repo, '.git'), { recursive: true });
+ // 3 bytes per character in UTF-8: 30,000 characters is ~88KB.
+ await write(path.join(repo, 'AGENTS.md'), 'θ§„'.repeat(30_000));
+
+ const result = await initWorkspace({ scope: repo });
+
+ const [file] = result.instructions;
+ expect(Buffer.byteLength(file.content, 'utf8')).toBeLessThanOrEqual(64 * 1024);
+ expect(file.content).toBe('θ§„'.repeat(Math.floor((64 * 1024) / 3)));
+ });
+
+ it('discovers skills in parent directories and .codex/skills, nearest first', async () => {
+ const repo = path.join(base, 'repo');
+ const pkg = path.join(repo, 'packages', 'web');
+ await mkdir(path.join(repo, '.git'), { recursive: true });
+ await writeSkill(path.join(pkg, '.claude', 'skills'), 'deploy', 'web deploy');
+ await writeSkill(path.join(repo, '.agents', 'skills'), 'deploy', 'root deploy');
+ await writeSkill(path.join(repo, '.codex', 'skills'), 'review');
+ await writeSkill(path.join(home, '.codex', 'skills'), 'personal');
+ await writeSkill(path.join(home, '.agents', 'skills'), 'review', 'device review');
+
+ const result = await initWorkspace({ scope: pkg });
+
+ expect(
+ result.skills.map(({ description, name, previewRoot, scope, source }) => ({
+ description,
+ name,
+ previewRoot,
+ scope,
+ source,
+ })),
+ ).toEqual([
+ {
+ description: 'web deploy',
+ name: 'deploy',
+ previewRoot: pkg,
+ scope: 'project',
+ source: '.claude/skills',
+ },
+ {
+ description: 'personal skill',
+ name: 'personal',
+ previewRoot: path.join(home, '.codex', 'skills'),
+ scope: 'device',
+ source: '.codex/skills',
+ },
+ {
+ description: 'review skill',
+ name: 'review',
+ previewRoot: path.join(repo, '.codex', 'skills'),
+ scope: 'project',
+ source: '.codex/skills',
+ },
+ ]);
+ });
+});
+
+describe('listProjectSkills', () => {
+ it('approves the source directory of a parent-level skill for preview', async () => {
+ const repo = path.join(base, 'repo');
+ const pkg = path.join(repo, 'pkg');
+ await mkdir(path.join(repo, '.git'), { recursive: true });
+ await mkdir(pkg, { recursive: true });
+ await writeSkill(path.join(repo, '.agents', 'skills'), 'lint');
+ const approveProjectRoot = vi.fn(async () => {});
+
+ const result = await listProjectSkills({ scope: pkg }, { approveProjectRoot });
+
+ expect(result.skills.map((skill) => skill.path)).toEqual([
+ path.join(repo, '.agents', 'skills', 'lint', 'SKILL.md'),
+ ]);
+ expect(approveProjectRoot).toHaveBeenCalledWith(path.join(repo, '.agents', 'skills'));
+ });
+});
diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.ts
index 46739c23f54..5f8dd02f301 100644
--- a/packages/device-control/src/types.ts
+++ b/packages/device-control/src/types.ts
@@ -11,7 +11,7 @@ import type { DeviceClient, DeviceCliRestartParams, DeviceCliUpdateState } from
// ─── Workspace scan ───
export type ProjectSkillScope = 'device' | 'project';
-export type ProjectSkillSource = '.agents/skills' | '.claude/skills';
+export type ProjectSkillSource = '.agents/skills' | '.claude/skills' | '.codex/skills';
export interface ProjectSkillItem {
description?: string;
@@ -39,6 +39,8 @@ export interface InitWorkspaceParams {
export interface WorkspaceInstructionsItem {
content: string;
+ /** Absolute path of the file; the working directory or one of its parents. */
+ path: string;
source: 'AGENTS.md' | 'CLAUDE.md';
}
diff --git a/packages/device-control/src/workspace.ts b/packages/device-control/src/workspace.ts
index a2b996700ca..d361ff99bd5 100644
--- a/packages/device-control/src/workspace.ts
+++ b/packages/device-control/src/workspace.ts
@@ -29,8 +29,16 @@ const MAX_DIRECTORY_PAGE_SIZE = 1000;
const SKILL_SOURCES = [
'.agents/skills',
'.claude/skills',
+ '.codex/skills',
] as const satisfies readonly ProjectSkillSource[];
+/**
+ * Upper bound on directories walked from the working directory to the
+ * repository root, so a pathological path cannot turn one scan into hundreds
+ * of filesystem probes.
+ */
+const MAX_ANCESTOR_DEPTH = 32;
+
interface SkillScanRoot {
previewRoot: string;
scope: ProjectSkillScope;
@@ -38,13 +46,58 @@ interface SkillScanRoot {
sourceRoot: string;
}
-const createProjectSkillRoots = (root: string): SkillScanRoot[] =>
- SKILL_SOURCES.map((source) => ({
- previewRoot: root,
- scope: 'project',
- source,
- sourceRoot: path.join(root, source),
- }));
+const pathExists = async (target: string): Promise<boolean> => {
+ try {
+ await stat(target);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * Directories whose agent files apply to `root`, nearest first: `root` itself,
+ * then each parent up to and including the repository root (the nearest
+ * ancestor containing `.git`, a directory in a checkout and a file in a
+ * worktree or submodule). Without a repository root only `root` applies, so a
+ * directory outside any repository never picks up files from `~` or `/`.
+ *
+ * Mirrors the startup discovery of Codex, Claude Code, OpenCode and pi, so a
+ * run bound to `packages/web` of a monorepo still sees the root `AGENTS.md`
+ * and `.agents/skills`.
+ */
+const resolveAgentFileDirs = async (root: string): Promise<string[]> => {
+ const start = path.resolve(root);
+ const dirs: string[] = [];
+ let current = start;
+
+ for (let depth = 0; depth < MAX_ANCESTOR_DEPTH; depth += 1) {
+ dirs.push(current);
+ if (await pathExists(path.join(current, '.git'))) return dirs;
+
+ const parent = path.dirname(current);
+ if (parent === current) break;
+ current = parent;
+ }
+
+ return [start];
+};
+
+const createProjectSkillRoots = (root: string, dirs: string[]): SkillScanRoot[] =>
+ dirs.flatMap((dir, index) =>
+ SKILL_SOURCES.map((source) => {
+ const sourceRoot = path.join(dir, source);
+ return {
+ // Skills in the working directory preview against it, as before. A
+ // parent directory is not an approved root, so its skills preview
+ // against their own source directory, the way device skills do.
+ previewRoot: index === 0 ? root : sourceRoot,
+ scope: 'project' as const,
+ source,
+ sourceRoot,
+ };
+ }),
+ );
const createDeviceSkillRoots = (): SkillScanRoot[] => {
const home = os.homedir();
@@ -60,8 +113,12 @@ const createDeviceSkillRoots = (): SkillScanRoot[] => {
});
};
-const createSkillRoots = (root: string): SkillScanRoot[] => [
- ...createProjectSkillRoots(root),
+/**
+ * Scan order decides name collisions (first wins): the working directory
+ * before its parents, project before device.
+ */
+const createSkillRoots = async (root: string): Promise<SkillScanRoot[]> => [
+ ...createProjectSkillRoots(root, await resolveAgentFileDirs(root)),
...createDeviceSkillRoots(),
];
@@ -193,34 +250,76 @@ const approvePreviewRoots = async (
await Promise.all([...roots].map((root) => deps.approveProjectRoot!(root)));
};
+/** Per-file cap, so one oversized file cannot crowd out the others. */
+const MAX_INSTRUCTIONS_FILE_BYTES = 64 * 1024;
+/** Cap across every directory, bounding the cached payload and the system role. */
+const MAX_INSTRUCTIONS_TOTAL_BYTES = 128 * 1024;
+const INSTRUCTION_FILENAMES = ['AGENTS.md', 'CLAUDE.md'] as const;
+
/**
- * Read the project-root agent instructions files (`AGENTS.md`, then `CLAUDE.md`).
- * Collects every present candidate rather than first-match, since both can
- * coexist. Each body is capped so a pathologically large file can't bloat the
- * cached payload or the injected system role.
+ * Cut `raw` to at most `maxBytes` of UTF-8. Measuring `string.length` would
+ * count UTF-16 units, letting CJK text exceed the budget about threefold. A
+ * character split at the boundary decodes to U+FFFD and is dropped.
*/
-const readWorkspaceInstructions = async (root: string): Promise<WorkspaceInstructionsItem[]> => {
- const MAX_INSTRUCTIONS_BYTES = 64 * 1024;
- const candidates = ['AGENTS.md', 'CLAUDE.md'] as const;
+const truncateUtf8 = (raw: string, maxBytes: number): { bytes: number; content: string } => {
+ const buffer = Buffer.from(raw, 'utf8');
+ if (buffer.length <= maxBytes) return { bytes: buffer.length, content: raw };
+
+ const content = buffer
+ .subarray(0, maxBytes)
+ .toString('utf8')
+ .replace(/\uFFFD+$/, '');
+ return { bytes: Buffer.byteLength(content, 'utf8'), content };
+};
- const instructions: WorkspaceInstructionsItem[] = [];
- for (const source of candidates) {
- try {
- const raw = await readFile(path.join(root, source), 'utf8');
- const content =
- raw.length > MAX_INSTRUCTIONS_BYTES ? raw.slice(0, MAX_INSTRUCTIONS_BYTES) : raw;
- instructions.push({ content, source });
- } catch {
- // File absent or unreadable; skip it.
+/**
+ * Read the agent instructions files (`AGENTS.md`, then `CLAUDE.md`) in `dirs`
+ * (nearest first), returned root first so the most specific file comes last
+ * in the prompt, as the other harnesses order them.
+ *
+ * Both names are read in each directory since they can coexist, except when
+ * one is a symlink to the other (a common way to share one file between
+ * harnesses): the same file is never injected twice. The total budget is
+ * spent nearest first, so when it runs out the farthest parents are dropped,
+ * not the working directory's own rules.
+ */
+const readWorkspaceInstructions = async (dirs: string[]): Promise<WorkspaceInstructionsItem[]> => {
+ const seen = new Set<string>();
+ const byDir: WorkspaceInstructionsItem[][] = [];
+ let remaining = MAX_INSTRUCTIONS_TOTAL_BYTES;
+
+ for (const dir of dirs) {
+ const found: WorkspaceInstructionsItem[] = [];
+ for (const source of INSTRUCTION_FILENAMES) {
+ if (remaining <= 0) break;
+ const filePath = path.join(dir, source);
+ try {
+ const real = await realpath(filePath);
+ if (seen.has(real)) continue;
+ seen.add(real);
+
+ const raw = await readFile(filePath, 'utf8');
+ const { bytes, content } = truncateUtf8(
+ raw,
+ Math.min(MAX_INSTRUCTIONS_FILE_BYTES, remaining),
+ );
+ remaining -= bytes;
+ found.push({ content, path: filePath, source });
+ } catch {
+ // File absent or unreadable; skip it.
+ }
}
+ byDir.push(found);
}
- return instructions;
+ return byDir.reverse().flat();
};
/**
- * Scan agent skill directories for the project and the execution device.
- * Project skills win over device skills on name collision. Approves each
+ * Scan agent skill directories for the project (the working directory and its
+ * parents up to the repository root) and the execution device. Nearer project
+ * skills win over farther ones, and project skills over device skills, on name
+ * collision. Approves each
* discovered skill's preview root for the host preview protocol.
*/
export const listProjectSkills = async (
@@ -228,7 +327,7 @@ export const listProjectSkills = async (
deps: WorkspaceScanDeps = {},
): Promise<ListProjectSkillsResult> => {
const root = params.scope;
- const skills = await collectSkills(createSkillRoots(root));
+ const skills = await collectSkills(await createSkillRoots(root));
if (skills.length > 0) {
await approvePreviewRoots(skills, deps);
@@ -239,8 +338,8 @@ export const listProjectSkills = async (
/**
* One-call "workspace init" scan: merge project and execution-device skills
- * (deduped by name, project winning) and read the project-root agent
- * instructions. Approves the project root regardless of what was found, since
+ * (deduped by name, project winning) and read the agent instructions from the
+ * working directory up to the repository root. Approves the project root regardless of what was found, since
* the run is now bound to this root.
*/
export const initWorkspace = async (
@@ -249,8 +348,12 @@ export const initWorkspace = async (
): Promise<InitWorkspaceResult> => {
const root = params.scope;
- const skills = await collectSkills(createSkillRoots(root));
- const instructions = await readWorkspaceInstructions(root);
+ const dirs = await resolveAgentFileDirs(root);
+ const skills = await collectSkills([
+ ...createProjectSkillRoots(root, dirs),
+ ...createDeviceSkillRoots(),
+ ]);
+ const instructions = await readWorkspaceInstructions(dirs);
await approvePreviewRoots(skills, deps, [root]);
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index 91e775689d1..48858f73a78 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -767,7 +767,7 @@ export interface ResolveSkillResourcePathResult {
}
export type ProjectSkillScope = 'device' | 'project';
-export type ProjectSkillSource = '.agents/skills' | '.claude/skills';
+export type ProjectSkillSource = '.agents/skills' | '.claude/skills' | '.codex/skills';
export interface ProjectSkillItem {
description?: string;
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index b73dd180141..bdb87d302a9 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -19,7 +19,7 @@ export interface DeviceUnavailableErrorData {
}
export type ProjectSkillScope = 'device' | 'project';
-export type ProjectSkillSource = '.agents/skills' | '.claude/skills';
+export type ProjectSkillSource = '.agents/skills' | '.claude/skills' | '.codex/skills';
/**
* A filesystem skill discovered on the execution device by the client at
@@ -41,8 +41,9 @@ export interface ProjectSkillMeta {
}
/**
- * A single project-root agent instructions file (`AGENTS.md` / `CLAUDE.md`) read
- * from the device filesystem during workspace init. Unlike skills (metadata
+ * A single agent instructions file (`AGENTS.md` / `CLAUDE.md`) read from the
+ * working directory or one of its parents up to the repository root during
+ * workspace init. Unlike skills (metadata
* only), the full body is carried so it can be injected into the system role and
* rendered in web without a second device round-trip. Carried as a list on
* {@link WorkspaceInitResult} since multiple files can coexist (e.g. both
@@ -51,6 +52,11 @@ export interface ProjectSkillMeta {
export interface WorkspaceInstructions {
/** Full file content (capped at read time, e.g. 64KB). */
content: string;
+ /**
+ * Absolute path of the file. Absent in scans cached before parent
+ * directories were read, which only covered the working directory.
+ */
+ path?: string;
/** Source file the instructions were read from. */
source: 'AGENTS.md' | 'CLAUDE.md';
}
diff --git a/src/features/SkillsList/useProjectSkills.ts b/src/features/SkillsList/useProjectSkills.ts
index d0dd475bd7a..b7b270719e5 100644
--- a/src/features/SkillsList/useProjectSkills.ts
+++ b/src/features/SkillsList/useProjectSkills.ts
@@ -33,8 +33,9 @@ export interface UseProjectSkillsResult {
/**
* Shared scan + handlers for filesystem-backed skills. Project skills live
- * under `.agents/skills` / `.claude/skills` in `workingDirectory`; device
- * skills live under those directories in the execution device's home.
+ * under `.agents/skills` / `.claude/skills` / `.codex/skills` in
+ * `workingDirectory` and its parents up to the repository root; device skills
+ * live under those directories in the execution device's home.
*
* `deviceId` picks the transport for both listing and preview: when set, the
* scan and file reads run on that bound device via RPC (`device.listProjectSkills`
@@ -98,7 +99,10 @@ export const useProjectSkills = (
const openSkillFile = useCallback(
(skill: ProjectSkillItem, filePath: string) => {
openLocalFile({
- allowExternalFilePreview: skill.scope === 'device',
+ // Project skills found in a parent of the working directory preview
+ // against their own source directory, outside the project scope too.
+ allowExternalFilePreview:
+ skill.scope === 'device' || (!!skill.previewRoot && skill.previewRoot !== previewRoot),
// A bound device (remote, or this machine as a device) reads the preview
// over RPC, exactly like the Files tab; an undefined deviceId falls back to
// local Electron IPC. The old `isRemote` no-op predated remote preview.