A rule set in a menu loosens what was chosen and no more
ci / check (push) Canceled after 0s

setRule appended a sourceless rule last, so 'read * allow' shadowed the
default 'read *.env: ask' and 'bash allow' the user's own 'rm *' deny, and
wrote it to the project. Now: choosing what is in force is a no-op; a rule
the user's own config or a written deny takes in whole is refused; a rule
that is made is a project's rule in the session as in the saved file, and
a rule made after the written ones (project, 'always', menu) decides what
a broader rule decided, never what a narrower stricter one did — lookupRule
keeps the strictest narrower match. The menu says where the rule holds,
whether it was saved (a failed save is said), and which stricter rules
still apply. Removing a session rule removes its saved copy.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-12 18:52:10 +00:00
1 parent 98aa346c34
commit 7859237dde
9 files changed
+297 -34

No files matched your search

+9 -3
View File
@@ -13,8 +13,7 @@ All notable changes to LLeMbas CLI. The format follows
config) and what it offers. Enter opens a server: reconnect, switch it off or on (kept for a
trusted project), sign in or out, read its last error in full; its tools, searchable as you
type, each with what the permission rules say of it — asks, always allowed, denied — which
Enter changes (for the session, and saved to a trusted project; your own config's stricter rule
is never loosened from here); its prompts. `/mcp <name>` opens one server directly. Keyboard
Enter changes (for the session, and saved to a trusted project); its prompts. `/mcp <name>` opens one server directly. Keyboard
only; Esc goes back. Over the link and in `lembas run`, `/mcp` and `/mcp <name>` print a plain
table instead.
- **Menus have sections, state marks, a line about the highlighted row, Esc-goes-back, PgUp/PgDn
@@ -26,7 +25,14 @@ All notable changes to LLeMbas CLI. The format follows
too.
- **`/permissions`** (new): the permission rules in force, by where each was made — this session,
the project, your config, built in. Enter changes one (asks / always allowed / denied), the
first row adds one (`bash git status* allow`), and a rule of this session can be removed.
first row adds one (`bash git status* allow`), and a rule of this session can be removed (its
saved copy with it). A rule made in a menu changes what a broader rule decided and nothing
else: a narrower, stricter rule keeps winning (`read: allow` leaves `read *.env` asking), your
own config is never loosened, choosing what is already so changes nothing, and the menu says
which stricter rules still apply. This session and the next start judge a call the same way.
- **A project's rule, or an "always" answer, no longer overrides a narrower, stricter rule**
either: a project's `read: allow` leaves `.env` files asking, unless the project names
`"*.env"` itself.
- **`/status`** (new): the server and login, the model, the session, the project and whether it
is trusted, the MCP servers, and this terminal — how copying and pasting images work here —
on one screen. What needs attention is marked; Enter on a row opens what changes it.
+2 -1
View File
@@ -20,7 +20,7 @@ import { subagentModel, type ModelInfo } from "./team/subagents.ts"
import { assembleSystem, instructionFiles, knowledgeScope, modeText } from "./prompt/assemble.ts"
import type { Changing } from "./session/prefix.ts"
import { describeRepo, repoState } from "./git/repo.ts"
import { findProject, persistProjectRule, trustOf, type Project } from "./project/root.ts"
import { findProject, forgetProjectRule, persistProjectRule, trustOf, type Project } from "./project/root.ts"
import type { Message } from "./provider/types.ts"
import { Engine } from "./session/engine.ts"
import { agents, NOT_FOR_SUBAGENTS } from "./project/agents.ts"
@@ -709,6 +709,7 @@ export function createApp(o: AppOptions): App {
// The configured MCP servers, up to loop.json's wait: their tools in the first list.
beforeFirst: () => Promise.race([mcpReady.catch(() => {}), Bun.sleep(LOOP.context.mcp_wait_ms)]),
persistRule: trusted ? (rule) => persistProjectRule(project, rule) : undefined,
forgetRule: trusted ? (rule) => forgetProjectRule(project, rule) : undefined,
// subagents: false — no task tool, and no team (team.md §2).
spawn: loaded.config.subagents === false ? undefined : spawn,
})
+29 -7
View File
@@ -63,19 +63,33 @@ export function toRules(config: PermissionConfig, source?: Rule["source"]): Rule
return rules
}
/** Whether rule `a` speaks of less than rule `b`: everything `a`'s permission and pattern take in
* is taken in by `b`'s, and they are not the same rule (`read *.env` under `read *`, and `read *`
* under `* *`). */
export function narrowerThan(a: Pick<Rule, "permission" | "pattern">, b: Pick<Rule, "permission" | "pattern">): boolean {
if (a.permission === b.permission && a.pattern === b.pattern) return false
return match(a.permission, b.permission) && match(a.pattern, b.pattern)
}
/** What stands in a new rule's way, so that making it would change nothing or loosen what was
* written on purpose: the person's own (global) rule, or any written deny, that takes in all the
* new rule would — and is stricter. Such a rule is changed where it was written. */
export function standsInTheWay(rule: Pick<Rule, "permission" | "pattern" | "action">, rules: Rule[]): Rule | undefined {
return rules.findLast((r) => !r.learned && RANK[r.action] > RANK[rule.action] && (r.source === "global" || r.action === "deny") && match(rule.permission, r.permission) && match(rule.pattern, r.pattern))
}
/** The written rules a new rule does not change, because they are stricter and speak of less
* than it (or are the person's own): what "still applies" after it is made. */
export function stillStricter(rule: Pick<Rule, "permission" | "pattern" | "action">, rules: Rule[]): Rule[] {
return rules.filter((r) => !r.learned && RANK[r.action] > RANK[rule.action] && match(r.permission, rule.permission) && match(r.pattern, rule.pattern) && narrowerThan(r, rule))
}
/** What the rules say of a permission and pattern, before any mode: undefined where none speaks
* (the call is then asked or allowed by its class and the mode). */
export function ruleAction(permission: string, pattern: string, rules: Rule[]): Action | undefined {
return lookupRule(permission, pattern, rules)?.action
}
/** The user's own global rule that is stricter than `action` for this permission and pattern —
* the floor a rule made anywhere else cannot go under — or undefined. */
export function stricterGlobal(permission: string, pattern: string, action: Action, rules: Rule[]): Rule | undefined {
const own = rules.findLast((r) => r.source === "global" && !r.learned && match(permission, r.permission) && match(pattern, r.pattern))
return own && RANK[own.action] > RANK[action] ? own : undefined
}
function lookupRule(permission: string, pattern: string, rules: Rule[]): Rule | undefined {
const hit = rules.findLast((r) => match(permission, r.permission) && match(pattern, r.pattern))
// A project's rule (or an "always" answer) that is looser than what the user's global config says
@@ -90,6 +104,14 @@ function lookupRule(permission: string, pattern: string, rules: Rule[]): Rule |
const written = rules.findLast((r) => !r.learned && match(permission, r.permission) && match(pattern, r.pattern))
if (written?.action === "deny") return written
}
// A rule made after the written ones — a project's, an "always" answer, one set in a menu —
// decides what a broader rule decided, never what a narrower one did: `read: allow` leaves
// `read *.env: ask` asking, `bash: allow` leaves `bash "git push *": ask`. The strictest
// narrower rule that matches this call keeps winning.
if (hit && (hit.source === "project" || hit.learned)) {
const narrower = rules.filter((r) => r !== hit && !r.learned && RANK[r.action] > RANK[hit.action] && match(permission, r.permission) && match(pattern, r.pattern) && narrowerThan(r, hit))
if (narrower.length) return narrower.reduce((a, b) => (RANK[b.action] > RANK[a.action] ? b : a))
}
return hit
}
+22
View File
@@ -126,6 +126,28 @@ export function persistProjectMcpEnabled(project: Project, name: string, on: boo
writeFileSync(file, doc.toString())
}
/** Take a rule out of the project's config.yaml again (one a menu saved there); whether it was
* there. A permission left with no pattern goes too. */
export function forgetProjectRule(project: Project, rule: Pick<Rule, "permission" | "pattern">): boolean {
const file = join(project.dir, "config.yaml")
if (!existsSync(file)) return false
assertProjectFile(file, project.root)
const doc = parseDocument(readFileSync(file, "utf8"))
const current = doc.getIn(["permission", rule.permission])
if (current === undefined) return false
if (typeof current === "string") {
if (rule.pattern !== "*") return false
doc.deleteIn(["permission", rule.permission])
} else {
if (!doc.hasIn(["permission", rule.permission, rule.pattern])) return false
doc.deleteIn(["permission", rule.permission, rule.pattern])
const left = doc.getIn(["permission", rule.permission]) as { items?: unknown[] } | undefined
if (left && Array.isArray(left.items) && left.items.length === 0) doc.deleteIn(["permission", rule.permission])
}
writeFileSync(file, doc.toString())
return true
}
/** "Always allow (project)": add the rule to the project's config.yaml, keeping its comments. */
export function persistProjectRule(project: Project, rule: Rule) {
const file = join(project.dir, "config.yaml")
+39 -13
View File
@@ -8,7 +8,7 @@ import { isAbsolute } from "node:path"
import type { Asker, AttachmentInfo, Bus } from "../bus/index.ts"
import type { Mode } from "../config/schema.ts"
import type { Level } from "../provider/effort.ts"
import { evaluate, ruleAction, shadowsDeny, stricterGlobal, type Context as PermContext, type PermissionRequest, type Rule } from "../permission/evaluate.ts"
import { evaluate, ruleAction, shadowsDeny, standsInTheWay, stillStricter, type Context as PermContext, type PermissionRequest, type Rule } from "../permission/evaluate.ts"
import { ProviderError, type Client, type ImagePart, type Message, type ResolvedModel, type ToolCallPart, type Usage } from "../provider/types.ts"
import type { Plan } from "../plan/plan.ts"
import { LOOP } from "../harness.ts"
@@ -61,6 +61,8 @@ export interface EngineOptions {
budget?: { wall_seconds?: number; output_bytes?: number; completion_tokens?: number }
/** Rules added by "always allow (project)" are handed here to persist. */
persistRule?: (rule: Rule) => void
/** Take a rule out of the project's config again; whether it was there. */
forgetRule?: (rule: Pick<Rule, "permission" | "pattern">) => boolean
compaction?: { autoAt?: number }
/** Starts a subagent for the task tool; absent in a subagent. */
spawn?: ToolContext["spawn"]
@@ -175,6 +177,8 @@ export class Engine {
* prompt on every step while it exists. */
plan: Plan | undefined
private sessionRules: Rule[] = []
/** The session rules set in a menu (as against learned from an "always" answer). */
private set = new WeakSet<Rule>()
private recentCalls: string[] = []
/** Tools refused with no one able to approve them, and the refusal: still listed (the tool list
* is the session's, harness context.md §10), and every further call answers that refusal. */
@@ -404,25 +408,47 @@ export class Engine {
return ruleAction(permission, pattern, this.rules)
}
/** A rule the person set themselves (a menu, not an answer to a card): in force at once for
* this session, and written to the project's config where the project is trusted. Refused,
* with the rule that stands in the way, where the person's own global config is stricter —
* that is changed there, not written over from a project. */
setRule(rule: Pick<Rule, "permission" | "pattern" | "action">): { saved: "project" | "session" } | { refused: Rule } {
const floor = stricterGlobal(rule.permission, rule.pattern, rule.action, this.o.perm.rules)
/** A rule the person set themselves (a menu, not an answer to a card).
*
* - Choosing what is already in force changes nothing: nothing is added, nothing written.
* - It is refused, with the rule in the way, where the person's own config — or a written deny
* — is stricter and takes in all of it: that is changed where it was written.
* - Otherwise it is in force at once and, in a trusted project, saved to the project's
* config. It is a project's rule in both places (`source: "project"`), so this session and
* the next start from the saved file judge every call the same way: it decides what a
* broader rule decided, and never what a narrower, stricter one did (evaluate.ts). Those
* that still apply are named in `still`.
* - A save that fails leaves the rule in force for this session, and says why. */
setRule(rule: Pick<Rule, "permission" | "pattern" | "action">): { saved: "project" | "session"; still: Rule[]; failed?: string } | { unchanged: true } | { refused: Rule } {
if (ruleAction(rule.permission, rule.pattern, this.rules) === rule.action) return { unchanged: true }
const floor = standsInTheWay(rule, this.o.perm.rules)
if (floor) return { refused: floor }
this.sessionRules = this.sessionRules.filter((r) => !(r.permission === rule.permission && r.pattern === rule.pattern))
this.sessionRules.push({ ...rule })
if (!this.o.persistRule) return { saved: "session" }
this.o.persistRule({ ...rule })
return { saved: "project" }
const made: Rule = { ...rule, source: "project" }
this.sessionRules.push(made)
this.set.add(made)
const still = stillStricter(rule, this.o.perm.rules)
if (!this.o.persistRule) return { saved: "session", still }
try {
this.o.persistRule({ ...rule })
} catch (e) {
return { saved: "session", still, failed: (e as Error).message.split("\n")[0] }
}
return { saved: "project", still }
}
/** Take a rule of this session away again (one made by an "always" answer, or set here). */
dropSessionRule(permission: string, pattern: string): boolean {
dropSessionRule(permission: string, pattern: string): { removed: boolean; file: "removed" | "none" | "kept"; failed?: string } {
const before = this.sessionRules.length
this.sessionRules = this.sessionRules.filter((r) => !(r.permission === permission && r.pattern === pattern))
return this.sessionRules.length < before
const removed = this.sessionRules.length < before
// The copy saved to the project goes with it, where there is one and it can be reached.
if (!this.o.forgetRule) return { removed, file: "kept" }
try {
return { removed, file: this.o.forgetRule({ permission, pattern }) ? "removed" : "none" }
} catch (e) {
return { removed, file: "kept", failed: (e as Error).message.split("\n")[0] }
}
}
/** This session's own rules ("always" answers and what was set in a menu). */
+2 -3
View File
@@ -5,6 +5,7 @@
import type { CommandCtx } from "./commands.ts"
import type { Option } from "./components/dialog.tsx"
import type { Mark } from "./notices.ts"
import { applyRule } from "./menus.ts"
import type { ServerState } from "../mcp/index.ts"
import { persistProjectMcpEnabled } from "../project/root.ts"
import { offers, sourceOf, SOURCE_WORDS, STATE_WORDS, whereOf } from "../mcp/text.ts"
@@ -123,9 +124,7 @@ function openToolRule(c: CommandCtx, server: string, tool: string) {
filter: false,
onBack: () => openMcpServer(c, server, `${TOOL}${tool}`),
onSelect: (action) => {
const r = c.app.engine.setRule({ permission: called, pattern: "*", action: action as "ask" | "allow" | "deny" })
if ("refused" in r) c.view.info(`${tool}: your own config says ${r.refused.action} for ${r.refused.permission} — change it there (~/.config/lembas/config.yaml, permission:); a rule made here cannot loosen it`, "warn")
else c.flash(`${tool}: ${RULE_WORDS[action as keyof typeof RULE_WORDS]}${r.saved === "project" ? " — saved to the project" : " for this session"}`)
applyRule(c, { permission: called, pattern: "*", action: action as "ask" | "allow" | "deny" }, tool)
openMcpServer(c, server, `${TOOL}${tool}`)
},
})
+22 -6
View File
@@ -70,10 +70,19 @@ export function parseRule(text: string): Pick<Rule, "permission" | "pattern" | "
return { permission: words[0]!, pattern: words.slice(1, -1).join(" ") || "*", action }
}
function applyRule(c: CommandCtx, rule: Pick<Rule, "permission" | "pattern" | "action">) {
/** Make a rule, and say truthfully what that did: nothing (it was so already); refused, and by
* which rule; made — where it holds, whether it was saved, and which stricter rules it leaves
* standing. One sentence in the transcript, so it can be read after the menu is gone. */
export function applyRule(c: CommandCtx, rule: Pick<Rule, "permission" | "pattern" | "action">, name = ruleLine(rule as Rule)) {
const r = c.app.engine.setRule(rule)
if ("refused" in r) return c.view.info(`${ruleLine(rule as Rule)}: your own config says ${r.refused.action} — change it there (~/.config/lembas/config.yaml, permission:); a rule made here cannot loosen it`, "warn")
c.flash(`${ruleLine(rule as Rule)}: ${ACTION_WORDS[rule.action]}${r.saved === "project" ? " — saved to the project" : " for this session"}`)
if ("unchanged" in r) return c.flash(`${name}: already ${ACTION_WORDS[rule.action]} — nothing changed`)
if ("refused" in r) {
const whose = r.refused.source === "global" ? "your own config (~/.config/lembas/config.yaml, permission:)" : r.refused.source === "project" ? "this project's .agent/config.yaml" : "the built-in rules"
return c.view.info(`${name}: not changed — ${whose} says ${r.refused.action} for ${ruleLine(r.refused)}, which takes this in. Change it there; a rule made here does not loosen it.`, "warn")
}
const where = r.failed ? `for this session only — it could not be saved to the project: ${r.failed}` : r.saved === "project" ? "for this session, and saved to this project's .agent/config.yaml" : "for this session"
const still = r.still.length ? ` These stricter rules still apply: ${r.still.slice(0, 6).map((x) => `${ruleLine(x)} (${ACTION_WORDS[x.action]})`).join(", ")}${r.still.length > 6 ? `, and ${r.still.length - 6} more` : ""}.` : ""
c.view.info(`${name}: ${ACTION_WORDS[rule.action]} ${where}.${still}`, r.failed ? "warn" : "success")
}
/** /permissions: the rules in force by where they were made; enter changes one, the first row adds one. */
@@ -83,7 +92,7 @@ export function openPermissions(c: CommandCtx, select?: string) {
const where = c.app.trusted ? "this session, and saved to this project's .agent/config.yaml" : "this session only (the project is not trusted)"
c.openDialog({
title: `Permissions — mode ${c.app.engine.mode}`,
body: [`A call no rule speaks of is asked about or allowed by its kind and the mode (/mode). A change made here holds for ${where}.`],
body: [`A call no rule speaks of is asked about or allowed by its kind and the mode (/mode). A rule made here holds for ${where}; it decides what a broader rule decided — a narrower, stricter one, and your own config, keep winning.`],
options: [
{ label: "Add a rule…", value: ADD, description: "<permission> [pattern] <allow|ask|deny>" },
...rules.map(({ rule, from }) => ({ label: ruleLine(rule), value: key(rule), mark: ACTION_MARK[rule.action], description: ACTION_WORDS[rule.action], section: RULE_FROM[from], detail: `${rule.permission} · pattern ${rule.pattern} · ${rule.action}${rule.learned ? " · from an \"always\" answer" : ""}` })),
@@ -126,8 +135,15 @@ export function openPermissions(c: CommandCtx, select?: string) {
onBack: () => openPermissions(c, v),
onSelect: (action) => {
if (action === "remove") {
c.app.engine.dropSessionRule(hit.rule.permission, hit.rule.pattern)
c.flash(`${ruleLine(hit.rule)}: this session's rule is removed`)
const gone = c.app.engine.dropSessionRule(hit.rule.permission, hit.rule.pattern)
const file = gone.failed
? ` — but not from the project's .agent/config.yaml: ${gone.failed}`
: gone.file === "removed"
? ", and its copy in this project's .agent/config.yaml"
: gone.file === "kept"
? " (this session's only: nothing was saved for it)"
: ""
c.view.info(`${ruleLine(hit.rule)}: this session's rule is removed${file}. What stood before it holds again.`, gone.failed ? "warn" : "info")
} else applyRule(c, { permission: hit.rule.permission, pattern: hit.rule.pattern, action: action as Rule["action"] })
openPermissions(c, v)
},
+171
View File
@@ -0,0 +1,171 @@
// A rule set from a menu (/permissions, /mcp) loosens exactly what the person chose and no more:
// it decides what a broader rule decided, never what a narrower, stricter one did; the person's
// own config stays the floor; and the session judges a call as the next start does from the file
// the rule was saved to.
import { afterEach, expect, test } from "bun:test"
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { createApp } from "../src/app.ts"
import { paths } from "../src/config/paths.ts"
import { evaluate, narrowerThan, standsInTheWay, toRules, type Rule } from "../src/permission/evaluate.ts"
import { setTrust } from "../src/project/root.ts"
type App = ReturnType<typeof createApp>
const apps: App[] = []
afterEach(async () => {
for (const a of apps.splice(0)) await a.close()
})
function config(extra = "") {
mkdirSync(paths.config, { recursive: true })
writeFileSync(join(paths.config, "connections.yaml"), "connections:\n f:\n type: webui\n url: http://127.0.0.1:9/v1\n models: { f/m: {} }\n", { mode: 0o600 })
writeFileSync(join(paths.config, "config.yaml"), `model: f/m\n${extra}`)
}
function project(trusted = true): string {
const dir = realpathSync(mkdtempSync(join(tmpdir(), "lembas-rules-")))
Bun.spawnSync(["git", "init", "-q", dir])
writeFileSync(join(dir, ".env"), "SECRET=1\n")
if (trusted) setTrust(dir, "trusted")
return dir
}
const open = (cwd: string): App => {
const app = createApp({ cwd, store: false, asker: { ask: async () => ({ kind: "deny" as const }) } })
apps.push(app)
return app
}
/** What a call of a tool would meet now: allow, ask or deny (in manual mode, before any card). */
function verdict(app: App, tool: string, args: Record<string, unknown>): string {
const t = app.engine.o.tools.find((x) => x.name === tool)!
const request = t.permission(args as never, { ...app.engine.o.toolCtx, signal: new AbortController().signal })
return evaluate(request, { ...app.engine.o.perm, mode: "manual", rules: app.engine.rules }).action
}
const saved = (dir: string) => (existsSync(join(dir, ".agent", "config.yaml")) ? readFileSync(join(dir, ".agent", "config.yaml"), "utf8") : "")
test("choosing what is already in force changes nothing: no rule added, nothing written — and .env still asks", () => {
config()
const dir = project()
const app = open(dir)
expect(verdict(app, "read", { path: ".env" })).toBe("ask")
// Enter on the built-in `read — always allowed` row, Enter again on the value it already has.
const before = app.engine.rules.length
expect(app.engine.setRule({ permission: "read", pattern: "*", action: "allow" })).toEqual({ unchanged: true })
expect(app.engine.rules.length).toBe(before)
expect(saved(dir)).toBe("")
expect(verdict(app, "read", { path: ".env" })).toBe("ask")
})
test("a broad allow from the menu leaves the narrower asks asking — .env, private addresses — in this session and after a start from the saved file", () => {
config()
const dir = project()
const app = open(dir)
// Something is really changed first, so the broad rule is made (not a no-op) and saved.
expect(app.engine.setRule({ permission: "read", pattern: "*", action: "ask" })).toMatchObject({ saved: "project" })
const r = app.engine.setRule({ permission: "read", pattern: "*", action: "allow" })
expect(r).toMatchObject({ saved: "project" })
// It says which stricter rules it leaves standing.
expect((r as { still: Rule[] }).still.map((x) => `${x.permission} ${x.pattern} ${x.action}`)).toEqual(["read *.env ask", "read *.env.* ask"])
expect(verdict(app, "read", { path: "README.md" })).toBe("allow")
expect(verdict(app, "read", { path: ".env" })).toBe("ask")
expect(verdict(app, "read", { path: "config/.env.local" })).toBe("ask")
expect(verdict(app, "web_fetch", { url: "http://127.0.0.1:8080/admin" })).toBe("ask")
expect(app.engine.setRule({ permission: "web_fetch", pattern: "*", action: "ask" })).toMatchObject({ saved: "project" })
expect(app.engine.setRule({ permission: "web_fetch", pattern: "*", action: "allow" })).toMatchObject({ saved: "project", still: [{ permission: "web_fetch", pattern: "private:*", action: "ask" }] })
expect(verdict(app, "web_fetch", { url: "https://example.org/" })).toBe("allow")
expect(verdict(app, "web_fetch", { url: "http://127.0.0.1:8080/admin" })).toBe("ask")
// Even the broadest rule there is.
expect(app.engine.setRule({ permission: "*", pattern: "*", action: "allow" })).toMatchObject({ saved: "project" })
expect(verdict(app, "read", { path: ".env" })).toBe("ask")
expect(verdict(app, "web_fetch", { url: "http://127.0.0.1:8080/admin" })).toBe("ask")
// The next start reads the file: every call is judged as this session judged it.
expect(saved(dir)).toContain("read")
const again = open(dir)
expect(again.engine.ownRules.length).toBe(0)
for (const [tool, args] of [
["read", { path: "README.md" }],
["read", { path: ".env" }],
["read", { path: "config/.env.local" }],
["web_fetch", { url: "https://example.org/" }],
["web_fetch", { url: "http://127.0.0.1:8080/admin" }],
["bash", { command: "ls -la" }],
["bash", { command: "make install" }],
] as const)
expect([tool, JSON.stringify(args), verdict(again, tool, args)]).toEqual([tool, JSON.stringify(args), verdict(app, tool, args)])
})
test("`bash allow` typed into Add a rule does not undo the person's own `rm *` deny or `git push *` ask — now, and after a start from the file", () => {
config("permission:\n bash:\n 'rm *': deny\n 'git push *': ask\n")
const dir = project()
const app = open(dir)
const r = app.engine.setRule({ permission: "bash", pattern: "*", action: "allow" })
expect(r).toMatchObject({ saved: "project" })
expect((r as { still: Rule[] }).still.map((x) => `${x.pattern} ${x.action}`)).toEqual(expect.arrayContaining(["rm * deny", "git push * ask"]))
expect(verdict(app, "bash", { command: "make all" })).toBe("allow")
expect(verdict(app, "bash", { command: "rm -rf build" })).toBe("deny")
expect(verdict(app, "bash", { command: "git push origin main" })).toBe("ask")
const again = open(dir)
expect(verdict(again, "bash", { command: "make all" })).toBe("allow")
expect(verdict(again, "bash", { command: "rm -rf build" })).toBe("deny")
expect(verdict(again, "bash", { command: "git push origin main" })).toBe("ask")
})
test("a rule the person's own config, or a written deny, takes in whole is refused where it is made — not set, not saved", () => {
config("permission:\n bash:\n 'git push *': ask\n 'rm *': deny\n")
const dir = project()
const app = open(dir)
// The very rule the person wrote, loosened: refused.
expect(app.engine.setRule({ permission: "bash", pattern: "git push *", action: "allow" })).toMatchObject({ refused: { pattern: "git push *", action: "ask", source: "global" } })
// A narrower allow under their deny: refused too — the deny takes it in.
expect(app.engine.setRule({ permission: "bash", pattern: "rm -rf build", action: "allow" })).toMatchObject({ refused: { pattern: "rm *", action: "deny" } })
expect(app.engine.ownRules.length).toBe(0)
expect(saved(dir)).toBe("")
// Stricter is always possible.
expect(app.engine.setRule({ permission: "bash", pattern: "git push *", action: "deny" })).toMatchObject({ saved: "project", still: [] })
expect(verdict(app, "bash", { command: "git push origin main" })).toBe("deny")
})
test("a save that fails is said, and the rule holds for this session only; removing a rule takes its saved copy too", () => {
config()
const dir = project()
const app = open(dir)
expect(app.engine.setRule({ permission: "bash", pattern: "make *", action: "allow" })).toMatchObject({ saved: "project" })
expect(saved(dir)).toContain("make *")
expect(app.engine.dropSessionRule("bash", "make *")).toEqual({ removed: true, file: "removed" })
expect(saved(dir)).not.toContain("make *")
expect(verdict(app, "bash", { command: "make all" })).toBe("ask")
expect(verdict(open(dir), "bash", { command: "make all" })).toBe("ask")
// The project's config cannot be written (a directory stands where the file should be).
const blocked = project()
const b = open(blocked)
mkdirSync(join(blocked, ".agent", "config.yaml"), { recursive: true })
const r = b.engine.setRule({ permission: "bash", pattern: "make *", action: "allow" })
expect(r).toMatchObject({ saved: "session" })
expect((r as { failed?: string }).failed).toBeTruthy()
expect(verdict(b, "bash", { command: "make all" })).toBe("allow")
// An untrusted project: the session only, and removing says nothing was saved.
const u = open(project(false))
expect(u.engine.setRule({ permission: "bash", pattern: "make *", action: "allow" })).toEqual({ saved: "session", still: [] })
expect(u.engine.dropSessionRule("bash", "make *")).toEqual({ removed: true, file: "kept" })
})
test("the rules themselves: what is narrower, what stands in the way, and a project's broad allow under a default's narrow ask", () => {
expect(narrowerThan({ permission: "read", pattern: "*.env" }, { permission: "read", pattern: "*" })).toBe(true)
expect(narrowerThan({ permission: "read", pattern: "*" }, { permission: "*", pattern: "*" })).toBe(true)
expect(narrowerThan({ permission: "read", pattern: "*" }, { permission: "read", pattern: "*" })).toBe(false)
expect(narrowerThan({ permission: "read", pattern: "*" }, { permission: "read", pattern: "*.env" })).toBe(false)
const base = [...toRules({ read: { "*": "allow", "*.env": "ask" }, bash: { "*": "ask", "rm -rf /*": "deny" } }, "default")]
expect(standsInTheWay({ permission: "bash", pattern: "rm -rf /tmp", action: "allow" }, base)).toMatchObject({ pattern: "rm -rf /*" })
expect(standsInTheWay({ permission: "bash", pattern: "*", action: "allow" }, base)).toBeUndefined()
// A project's config saying `read: allow` (a file a menu wrote, or one somebody typed): .env still asks.
const rules = [...base, ...toRules({ read: "allow", bash: "allow" }, "project")]
const ctx = { mode: "manual" as const, rules, hardline: [], root: "/p" }
expect(evaluate({ permission: "read", class: "read", patterns: [".env"] }, ctx).action).toBe("ask")
expect(evaluate({ permission: "read", class: "read", patterns: ["a.txt"] }, ctx).action).toBe("allow")
expect(evaluate({ permission: "bash", class: "execute", patterns: ["rm -rf /"] }, ctx).action).toBe("deny")
// …unless the project names the narrow thing itself.
const named = [...base, ...toRules({ read: { "*.env": "allow" } }, "project")]
expect(evaluate({ permission: "read", class: "read", patterns: [".env"] }, { ...ctx, rules: named }).action).toBe("allow")
})
+1 -1
View File
@@ -220,7 +220,7 @@ test("a rule the person's own config makes stricter is not loosened from the men
expect(t.app.engine.setRule({ permission: "mcp__web__tool_0", pattern: "*", action: "allow" })).toMatchObject({ refused: { action: "deny", source: "global" } })
expect(t.app.engine.ruleFor("mcp__web__tool_0")).toBe("deny")
// Stricter is always possible, and for an untrusted project it stays in the session.
expect(t.app.engine.setRule({ permission: "mcp__web__tool_1", pattern: "*", action: "deny" })).toEqual({ saved: "session" })
expect(t.app.engine.setRule({ permission: "mcp__web__tool_1", pattern: "*", action: "deny" })).toEqual({ saved: "session", still: [] })
expect(existsSync(join(t.cwd, ".agent", "config.yaml"))).toBe(false)
})