Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(bots): persona-declared access scopes — read/write/execute per directory

Salman Qureshie1e5040e13cb
diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.ts
index 1f400c26..703f9fe5 100644
--- a/src/bots/bot-manager.test.ts
+++ b/src/bots/bot-manager.test.ts
@@ -373,6 +373,41 @@ describe('Per-bot permission isolation (fail-closed)', () => {
expect(pm.getManifest().capabilities.shell.blocked).toContain('sudo *');
});
+ it('persona ## Access grants merge additively into the registry scopes', () => {
+ const manifest = store.create({ id: 'cookiebot', name: 'Cookiebot' }) as BotManifest;
+ store.writePersona('cookiebot', `# Cookiebot\n\n## Access\n\n- ~/cookies — read\n- /tmp/execdir — execute\n`);
+ const registry = createBotCapabilityRegistry({
+ botId: 'cookiebot',
+ manifest,
+ botDir: store.botDir('cookiebot'),
+ permissions: store.readPermissions('cookiebot'),
+ persona: store.readPersona('cookiebot'),
+ userMemory: null,
+ config: getDefaultConfig() as MercuryConfig,
+ });
+ const scopes = registry.permissions.getManifest().capabilities.filesystem.scopes;
+ // Own profile dir (default grant) still there, plus the persona grants.
+ expect(scopes.some(s => s.path === store.botDir('cookiebot'))).toBe(true);
+ expect(scopes.some(s => s.path.endsWith('/cookies') && s.read && !s.write)).toBe(true);
+ expect(scopes.some(s => s.path === '/tmp/execdir' && s.execute)).toBe(true);
+ });
+
+ it('a persona without an Access section changes nothing (current permissions apply)', () => {
+ const manifest = store.create({ id: 'plainbot', name: 'Plainbot' }) as BotManifest;
+ const registry = createBotCapabilityRegistry({
+ botId: 'plainbot',
+ manifest,
+ botDir: store.botDir('plainbot'),
+ permissions: store.readPermissions('plainbot'),
+ persona: store.readPersona('plainbot'), // default template: examples only, no grant bullets
+ userMemory: null,
+ config: getDefaultConfig() as MercuryConfig,
+ });
+ const scopes = registry.permissions.getManifest().capabilities.filesystem.scopes;
+ expect(scopes).toHaveLength(1);
+ expect(scopes[0].path).toBe(store.botDir('plainbot'));
+ });
+
it('fs write outside the bot scope is denied without prompting', async () => {
const manifest = store.create({ id: 'writer', name: 'Writer' }) as BotManifest;
const registry = createBotCapabilityRegistry({
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index 526aaefb..59dcea33 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -545,6 +545,10 @@ export class BotManager {
manifest,
botDir: this.store.botDir(botId),
permissions: this.store.readPermissions(botId),
+ // The persona's `## Access` section grants extra path scopes — read at
+ // registry build, so a persona edit (invalidateRuntime on write) applies
+ // to the very next turn.
+ persona: this.store.readPersona(botId),
userMemory: this.userMemoryFor(botId, manifest),
config: this.config,
});
diff --git a/src/bots/persona-access.test.ts b/src/bots/persona-access.test.ts
new file mode 100644
index 00000000..a91bf486
--- /dev/null
+++ b/src/bots/persona-access.test.ts
@@ -0,0 +1,70 @@
+import { describe, it, expect } from 'vitest';
+import { parsePersonaAccess } from './persona-access.js';
+
+describe('parsePersonaAccess (## Access section → path scopes)', () => {
+ it('parses one bullet per grant with read/write/execute modes', () => {
+ const persona = `# Cookie bot
+
+Eats cookies.
+
+## Access
+
+- ~/cookies — read
+- ~/projects/site: read, write
+- /usr/local/bin/tool — execute
+- self — read, write
+
+## Output
+
+Concise.
+`;
+ expect(parsePersonaAccess(persona)).toEqual([
+ { scope: '~/cookies', read: true, write: false, execute: false },
+ { scope: '~/projects/site', read: true, write: true, execute: false },
+ { scope: '/usr/local/bin/tool', read: false, write: false, execute: true },
+ { scope: 'self', read: true, write: true, execute: false },
+ ]);
+ });
+
+ it('supports quoted paths and r/w/x shorthand, and defaults a bare path to read', () => {
+ const persona = `## Access
+
+- "~/Library/Application Support/Cookies" — read
+- \`~/notes\` — w
+- ~/logs
+`;
+ expect(parsePersonaAccess(persona)).toEqual([
+ { scope: '~/Library/Application Support/Cookies', read: true, write: false, execute: false },
+ { scope: '~/notes', read: false, write: true, execute: false },
+ { scope: '~/logs', read: true, write: false, execute: false },
+ ]);
+ });
+
+ it('ignores prose, inline examples that are not bullets, and bullets without a path', () => {
+ const persona = `## Access
+
+You can always read and write inside your own profile directory. Examples:
+\`- ~/some/dir — read\` · \`- ~/other/dir — read, write\` (these are template
+examples, not grants). A granted directory covers everything inside it.
+`;
+ expect(parsePersonaAccess(persona)).toEqual([]);
+ });
+
+ it('an absent or empty section grants nothing (current permissions.yaml behavior)', () => {
+ expect(parsePersonaAccess('')).toEqual([]);
+ expect(parsePersonaAccess('# Bot\n\nNo access section here.\n')).toEqual([]);
+ expect(parsePersonaAccess('## Access\n\n(nothing granted yet)\n')).toEqual([]);
+ });
+
+ it('stops at the next heading', () => {
+ const persona = `## Access
+
+- ~/granted — read
+
+## Output
+
+- ~/not-a-grant — read, write
+`;
+ expect(parsePersonaAccess(persona)).toEqual([{ scope: '~/granted', read: true, write: false, execute: false }]);
+ });
+});
\ No newline at end of file
diff --git a/src/bots/persona-access.ts b/src/bots/persona-access.ts
new file mode 100644
index 00000000..6cf1e539
--- /dev/null
+++ b/src/bots/persona-access.ts
@@ -0,0 +1,62 @@
+import type { BotPathScope } from './types.js';
+
+/**
+ * Persona-declared access grants (`## Access` section in persona.md).
+ *
+ * The persona is where users describe their bot in their own words — so it is
+ * also where they grant directory access. One bullet per grant:
+ *
+ * ## Access
+ * - ~/cookies — read
+ * - ~/projects/site — read, write
+ * - /usr/local/bin/tool — execute
+ * - self — read, write
+ *
+ * Parsing is deliberately conservative: only list bullets inside the section
+ * count, the path must look like a path (or `self`), and prose/example text
+ * that isn't a bullet is ignored — so a template's inline example can never
+ * grant anything. An absent or empty section changes nothing: the bot keeps
+ * exactly the scopes from its permissions.yaml (fail-closed default).
+ */
+export function parsePersonaAccess(persona: string): BotPathScope[] {
+ if (!persona) return [];
+ const grants: BotPathScope[] = [];
+ let inSection = false;
+ for (const line of persona.split('\n')) {
+ if (/^#{1,2}\s/.test(line)) {
+ inSection = /^##\s+Access\b/i.test(line);
+ continue;
+ }
+ if (!inSection) continue;
+ const bullet = /^\s*[-*]\s+(.+)$/.exec(line);
+ if (!bullet) continue;
+ const grant = parseGrant(bullet[1]);
+ if (grant) grants.push(grant);
+ }
+ return grants;
+}
+
+function parseGrant(bullet: string): BotPathScope | null {
+ // Path = quoted text first (…/`…`), else the first whitespace token.
+ const quoted = /["'`]([^"'`]+)["'`]/.exec(bullet);
+ let rawPath = quoted?.[1] ?? bullet.split(/\s+/)[0] ?? '';
+ rawPath = rawPath.trim().replace(/[,.;:]+$/, '');
+ if (!looksLikePath(rawPath)) return null;
+
+ const modes = { read: false, write: false, execute: false };
+ const modePart = bullet.slice(bullet.indexOf(rawPath) + rawPath.length);
+ for (const word of modePart.toLowerCase().split(/[^a-z+]+/)) {
+ if (word === 'read' || word === 'r') modes.read = true;
+ else if (word === 'write' || word === 'w') modes.write = true;
+ else if (word === 'execute' || word === 'exec' || word === 'run' || word === 'x') modes.execute = true;
+ }
+ // A bare path (no modes stated) grants read — the least-privilege default.
+ if (!modes.read && !modes.write && !modes.execute) modes.read = true;
+ return { scope: rawPath, ...modes };
+}
+
+function looksLikePath(value: string): boolean {
+ if (value === 'self') return true;
+ if (value.length === 0 || value.length > 512) return false;
+ return /^(?:~|\/|\.{1,2}\/|[A-Za-z]:[\\/]|\\\\)/.test(value);
+}
\ No newline at end of file
diff --git a/src/bots/persona-template.test.ts b/src/bots/persona-template.test.ts
index ba1b0428..389f35fe 100644
--- a/src/bots/persona-template.test.ts
+++ b/src/bots/persona-template.test.ts
@@ -93,6 +93,60 @@ describe('refinePersona (convert to template)', () => {
expect(calls[1]).toContain('verifies repos are active');
});
+ it('drops Access grants for paths the user never wrote (no invented permissions)', async () => {
+ scriptedResponses.push(`# R
+
+Research.
+
+## Character
+
+Skeptical.
+
+## Standing instructions
+
+- Be skeptical
+
+## Access
+
+- ~/cookies — read
+- ~/some/dir — read
+
+## Output
+
+Concise.
+`);
+ const raw = 'Research bot; may read ~/cookies for cookie context.';
+ const result = await refinePersona(raw, 'R', stubProvider());
+ expect(result).toContain('~/cookies');
+ expect(result).not.toContain('~/some/dir');
+ });
+
+ it('drops the whole Access section when no user-stated grant survives', async () => {
+ scriptedResponses.push(`# R
+
+Research.
+
+## Character
+
+Skeptical.
+
+## Standing instructions
+
+- Be skeptical
+
+## Access
+
+- ~/some/dir — read
+- /etc — read
+
+## Output
+
+Concise.
+`);
+ const result = await refinePersona('plain research bot, no special access', 'R', stubProvider());
+ expect(result).not.toContain('## Access');
+ });
+
it('a failing inventory pass falls back to the single-pass build', async () => {
let calls = 0;
const flakyInventory = {
diff --git a/src/bots/persona-template.ts b/src/bots/persona-template.ts
index b5554dd5..e0664b0a 100644
--- a/src/bots/persona-template.ts
+++ b/src/bots/persona-template.ts
@@ -1,5 +1,6 @@
import type { BaseProvider } from '../providers/base.js';
import { logger } from '../utils/logger.js';
+import { parsePersonaAccess } from './persona-access.js';
export interface PersonaRefinement {
/** Refined persona (template format), or null when unusable. */
@@ -95,7 +96,11 @@ Output ONLY markdown, in exactly this shape:
<output format expectations: shape, length, evidence, tone>
-Rules: keep length proportional to the source material — a rich persona stays rich, never compress requirements away; never invent new capabilities, tools, or permissions; keep stated restrictions verbatim in meaning; no preamble, no code fences.`,
+## Access
+
+<directory access the user EXPLICITLY granted — one bullet per grant, exactly like: \`- ~/some/dir — read\` or \`- ~/other/dir — read, write\` or \`- /usr/local/bin/tool — execute\`. Extract these ONLY from paths + access the user stated; if the user granted nothing beyond the bot's own profile directory, write the single line: Only the bot's own profile directory.>
+
+Rules: keep length proportional to the source material — a rich persona stays rich, never compress requirements away; never invent new capabilities, tools, or permissions; keep stated restrictions verbatim in meaning; the ## Access section may contain ONLY directory access the user stated — never invent paths, and never add write or execute where the user said read; no preamble, no code fences.`,
'You write precise bot persona files. Restructure only; never add or remove requirements.',
);
const text = (result.text ?? '').trim();
@@ -109,5 +114,39 @@ Rules: keep length proportional to the source material — a rich persona stays
logger.debug({ botName }, 'Persona refinement produced unusable output — keeping raw');
return null;
}
- return text.endsWith('\n') ? text : text + '\n';
+ return sanitizePersonaAccess(text.endsWith('\n') ? text : text + '\n', source);
+}
+
+/**
+ * Enforce the no-invented-permissions rule on the drafted `## Access`
+ * section: a grant whose path the user never wrote (a copied example, a
+ * hallucinated path) is removed, and an Access section with no surviving
+ * grants is dropped entirely. `self` is always allowed — it is the default.
+ */
+function sanitizePersonaAccess(draft: string, source: string): string {
+ if (!draft.includes('## Access')) return draft;
+ const lines = draft.split('\n');
+ const start = lines.findIndex(l => /^##\s+Access\b/i.test(l));
+ if (start === -1) return draft;
+ let end = lines.length;
+ for (let i = start + 1; i < lines.length; i++) {
+ if (/^#{1,2}\s/.test(lines[i])) { end = i; break; }
+ }
+ const kept: string[] = [];
+ for (const line of lines.slice(start, end)) {
+ const bullet = /^\s*[-*]\s+(.+)$/.exec(line);
+ if (!bullet) { kept.push(line); continue; }
+ const grant = parsePersonaAccess(`## Access\n${line}`)[0];
+ const path = grant?.scope ?? '';
+ if (!path || path === 'self' || source.includes(path)) {
+ kept.push(line);
+ }
+ // else: dropped — the user never wrote this path
+ }
+ const section = kept.filter(l => l.trim().length > 0);
+ if (section.length <= 1) {
+ // No grants survived — drop the empty section entirely.
+ return [...lines.slice(0, start), ...lines.slice(end)].join('\n').replace(/\n+$/, '') + '\n';
+ }
+ return [...lines.slice(0, start), ...section, ...lines.slice(end)].join('\n');
}
\ No newline at end of file
diff --git a/src/bots/registry-factory.ts b/src/bots/registry-factory.ts
index e19b5140..55eaf880 100644
--- a/src/bots/registry-factory.ts
+++ b/src/bots/registry-factory.ts
@@ -5,6 +5,7 @@ import type { UserMemoryStore } from '../memory/user-memory.js';
import type { MercuryConfig } from '../utils/config.js';
import { logger } from '../utils/logger.js';
import type { BotManifest, BotPermissionsFile, BotPathScope } from './types.js';
+import { parsePersonaAccess } from './persona-access.js';
/**
* Tools a bot must never see, regardless of manifest. These are the tools
@@ -36,6 +37,11 @@ export interface BotRegistryDeps {
config: MercuryConfig;
/** Per-bot memory store (P0-5); null until memory scoping is wired. */
userMemory?: UserMemoryStore | null;
+ /**
+ * Persona text — a `## Access` section grants extra path scopes (merged
+ * with permissions.yaml). Absent or empty section = no change.
+ */
+ persona?: string;
}
/**
@@ -55,7 +61,10 @@ export function createBotCapabilityRegistry(deps: BotRegistryDeps): CapabilityRe
// Reshape the manifest in place (never call save() — that writes the
// global ~/.mercury/permissions.yaml, and bots have no path to it).
const manifest = pm.getManifest();
- manifest.capabilities.filesystem.scopes = buildBotScopes(deps.permissions.paths, deps.botDir);
+ manifest.capabilities.filesystem.scopes = buildBotScopes(
+ mergeScopeGrants(deps.permissions.paths, parsePersonaAccess(deps.persona ?? '')),
+ deps.botDir,
+ );
manifest.capabilities.shell.autoApproved = [];
manifest.capabilities.shell.blocked = [
...new Set([...manifest.capabilities.shell.blocked, ...(deps.permissions.blockedCommands ?? [])]),
@@ -97,18 +106,50 @@ export function filterBotTools(all: Record<string, any>, manifest: BotManifest):
}
/**
- * Bot path scopes from permissions.yaml. 'self' resolves to the bot's own
- * profile dir; everything else resolves against cwd or home (~). An
- * unconfigured bot gets NO filesystem access (fail-closed) — but the store
- * always writes a default self scope at creation.
+ * Merge raw scope grants from permissions.yaml and the persona's `## Access`
+ * section. Additive by design: the persona can only WIDEN what
+ * permissions.yaml already grants, and the same path granted twice unions
+ * its modes. No persona Access section = permissions.yaml alone (unchanged).
+ */
+function mergeScopeGrants(
+ fileScopes: BotPathScope[] | undefined,
+ personaScopes: BotPathScope[],
+): BotPathScope[] {
+ if (personaScopes.length === 0) return fileScopes ?? [];
+ const merged = [...(fileScopes ?? [])];
+ for (const grant of personaScopes) {
+ const key = normalizeScopeKey(grant.scope);
+ const existing = merged.find(p => normalizeScopeKey(p.scope) === key);
+ if (existing) {
+ existing.read = existing.read || grant.read;
+ existing.write = existing.write || grant.write;
+ existing.execute = existing.execute || grant.execute;
+ } else {
+ merged.push(grant);
+ }
+ }
+ return merged;
+}
+
+/** Key for grant de-duplication: resolved absolute path ('self' resolved later). */
+function normalizeScopeKey(scope: string): string {
+ return scope === 'self' ? 'self' : resolve(scope.replace(/^~/, homedir())).toLowerCase();
+}
+
+/**
+ * Bot path scopes from permissions.yaml + persona Access grants. 'self'
+ * resolves to the bot's own profile dir; everything else resolves against
+ * cwd or home (~). An unconfigured bot gets NO filesystem access
+ * (fail-closed) — but the store always writes a default self scope at
+ * creation.
*/
-function buildBotScopes(paths: BotPathScope[] | undefined, botDir: string): Array<{ path: string; read: boolean; write: boolean }> {
- const scopes: Array<{ path: string; read: boolean; write: boolean }> = [];
+function buildBotScopes(paths: BotPathScope[] | undefined, botDir: string): Array<{ path: string; read: boolean; write: boolean; execute?: boolean }> {
+ const scopes: Array<{ path: string; read: boolean; write: boolean; execute?: boolean }> = [];
for (const p of paths ?? []) {
const resolved = p.scope === 'self'
? resolve(botDir)
: resolve(p.scope.replace(/^~/, homedir()));
- scopes.push({ path: resolved, read: p.read ?? false, write: p.write ?? false });
+ scopes.push({ path: resolved, read: p.read ?? false, write: p.write ?? false, execute: p.execute || undefined });
}
return scopes;
}
\ No newline at end of file
diff --git a/src/bots/store.ts b/src/bots/store.ts
index 086f2712..93c5da63 100644
--- a/src/bots/store.ts
+++ b/src/bots/store.ts
@@ -100,6 +100,15 @@ falls outside it.
- If you lack permission for an action, stop and report it in your summary
instead of attempting a workaround.
+## Access
+
+You can always read and write inside your own profile directory. Anything
+else is denied until it is granted here — one bullet per directory (the
+forms below are examples only; write real bullets to grant access):
+\`- ~/some/dir — read\` · \`- ~/other/dir — read, write\` · \`- /usr/local/bin/tool — execute\`.
+A granted directory covers everything inside it. Outside these grants you
+do not act — you stop and report which access you would have needed.
+
## Output
- Lead with the outcome, then the details.
diff --git a/src/bots/types.ts b/src/bots/types.ts
index 71189e05..c12490cc 100644
--- a/src/bots/types.ts
+++ b/src/bots/types.ts
@@ -108,6 +108,11 @@ export interface BotPathScope {
scope: string;
read?: boolean;
write?: boolean;
+ /**
+ * May run shell commands whose path arguments lie inside this scope
+ * (fail-closed bots only; the global blocked-command list still wins).
+ */
+ execute?: boolean;
}
/** One journal entry — the permanent compact record of a bot run. */
diff --git a/src/capabilities/permissions.test.ts b/src/capabilities/permissions.test.ts
index d037cd44..438269b0 100644
--- a/src/capabilities/permissions.test.ts
+++ b/src/capabilities/permissions.test.ts
@@ -46,6 +46,53 @@ describe('splitShellSegments', () => {
});
});
+describe('fail-closed execute scopes (bots)', () => {
+ function managerWithExecuteScope() {
+ const permissions = new PermissionManager();
+ const manifest = permissions.getManifest();
+ manifest.capabilities.shell.enabled = true;
+ manifest.capabilities.filesystem.scopes = [
+ { path: '/tmp/execdir', read: true, write: false, execute: true },
+ { path: '/tmp/readonlydir', read: true, write: false },
+ ];
+ permissions.setAutoApproveAll(false);
+ permissions.setFailClosed(true);
+ permissions.setCurrentContext('bot', 'worker');
+ return permissions;
+ }
+
+ it('runs a command whose path arguments all lie inside an execute scope', async () => {
+ const permissions = managerWithExecuteScope();
+ await expect(permissions.checkShellCommand('node /tmp/execdir/tool.js --flag')).resolves.toMatchObject({ allowed: true, needsApproval: false });
+ });
+
+ it('denies a command that reaches outside the execute scope', async () => {
+ const permissions = managerWithExecuteScope();
+ await expect(permissions.checkShellCommand('node /tmp/execdir/tool.js /etc/passwd')).resolves.toMatchObject({ allowed: false });
+ });
+
+ it('does not treat a read-only (non-execute) scope as execute', async () => {
+ const permissions = managerWithExecuteScope();
+ await expect(permissions.checkShellCommand('node /tmp/readonlydir/tool.js')).resolves.toMatchObject({ allowed: false });
+ });
+
+ it('blocked commands win over execute scopes', async () => {
+ const permissions = managerWithExecuteScope();
+ permissions.getManifest().capabilities.shell.blocked = ['rm *'];
+ await expect(permissions.checkShellCommand('rm -rf /tmp/execdir')).resolves.toMatchObject({ allowed: false });
+ });
+
+ it('commands without path arguments stay approval-gated (cwd is not a grant)', async () => {
+ const permissions = managerWithExecuteScope();
+ await expect(permissions.checkShellCommand('npm install')).resolves.toMatchObject({ allowed: false });
+ });
+
+ it('a bare script path inside the execute scope runs without approval', async () => {
+ const permissions = managerWithExecuteScope();
+ await expect(permissions.checkShellCommand('/tmp/execdir/run.sh --serve')).resolves.toMatchObject({ allowed: true, needsApproval: false });
+ });
+});
+
describe('PermissionManager remote safety', () => {
it('enforces hard command blocks before Local allow-all', async () => {
const permissions = new PermissionManager();
diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.ts
index 27b87698..b8585b26 100644
--- a/src/capabilities/permissions.ts
+++ b/src/capabilities/permissions.ts
@@ -9,6 +9,13 @@ export interface FileScope {
path: string;
read: boolean;
write: boolean;
+ /**
+ * Explicit execute grant (fail-closed bots): shell commands whose path
+ * arguments all resolve inside this scope may run. The global
+ * blocked-command list always wins; commands without path arguments stay
+ * approval-gated.
+ */
+ execute?: boolean;
}
export interface ShellPermissions {
@@ -542,7 +549,7 @@ export class PermissionManager {
const hasPathTraversal = this.hasPathBeyondCwd(segment);
if (hasPathTraversal) {
const scopeCheck = await this.checkFsAccess(hasPathTraversal, 'write');
- if (!scopeCheck.allowed) {
+ if (!scopeCheck.allowed && !this.isExecuteScoped(hasPathTraversal)) {
return { allowed: false, reason: `No permission to access ${hasPathTraversal}. Use approve_scope tool with path="${hasPathTraversal}" and mode="write" to request access.`, needsApproval: false };
}
}
@@ -560,6 +567,19 @@ export class PermissionManager {
return { allowed: true, needsApproval: false };
}
+ // Fail-closed execute grants (bots): an explicitly granted execute scope
+ // lets the bot run commands whose path arguments ALL live inside it — the
+ // blocked list already won above. Commands with no path argument stay
+ // approval-gated: an unscoped `npm install` mutates cwd and can reach
+ // anywhere via the network, so it is not covered by a directory grant.
+ if (this.failClosed) {
+ const pathTokens = segments.flatMap(s => this.extractPathTokens(s));
+ if (pathTokens.length > 0 && pathTokens.every(t => this.isExecuteScoped(t))) {
+ logger.info({ cmd: trimmed, paths: pathTokens.length }, 'Shell command allowed by execute scope');
+ return { allowed: true, needsApproval: false };
+ }
+ }
+
// All non-safe commands require user approval in ask-me mode
if (this.askHandler && this.currentChannelType !== 'internal') {
const result = await this.askHandler(`Run command: ${trimmed}`);
@@ -681,23 +701,35 @@ export class PermissionManager {
}
}
- private hasPathBeyondCwd(command: string): string | null {
- const pathPatterns = [
- /(?:^|\s)(\/[^\s]+)/,
- /(?:^|\s)(~\/[^\s]+)/,
- /(?:^|\s)\.\.\/([^\s]+)/,
- /(?:^|\s)([A-Za-z]:\\[^\s]+)/,
- /(?:^|\s)(\\\\[^\s]+)/,
- ];
- for (const p of pathPatterns) {
- const match = command.match(p);
- if (match) {
- const candidate = resolve(match[1].replace(/^~/, homedir()));
- if (!candidate.startsWith(this.cwd)) {
- return candidate;
- }
+ private static readonly PATH_PATTERNS = [
+ /(?:^|\s)(\/[^\s]+)/,
+ /(?:^|\s)(~\/[^\s]+)/,
+ /(?:^|\s)\.\.\/([^\s]+)/,
+ /(?:^|\s)([A-Za-z]:\\[^\s]+)/,
+ /(?:^|\s)(\\\\[^\s]+)/,
+ ];
+
+ /** Every path-like token in a command segment, resolved (tilde expanded). */
+ private extractPathTokens(text: string): string[] {
+ const out: string[] = [];
+ for (const pattern of PermissionManager.PATH_PATTERNS) {
+ for (const match of text.matchAll(new RegExp(pattern.source, 'g'))) {
+ out.push(resolve(match[1].replace(/^~/, homedir())));
}
}
+ return out;
+ }
+
+ /** A resolved path is covered by an explicit execute grant. */
+ private isExecuteScoped(resolvedPath: string): boolean {
+ if (this.findScope(resolvedPath)?.execute) return true;
+ return this.findTempScope(resolvedPath)?.execute === true;
+ }
+
+ private hasPathBeyondCwd(command: string): string | null {
+ for (const candidate of this.extractPathTokens(command)) {
+ if (!candidate.startsWith(this.cwd)) return candidate;
+ }
return null;
}