grep returns no line of a file read would ask about (M2)
The grep tool's permission is judged for the directory it searches; the files in it were then read with rg --hidden and their lines returned, so a .env came back unasked in manual and plan mode. Each file a match comes from is now judged as read of it would be (the rules and the mode as they are); what is not allowed is left out and named after the matches. Spec: filesystem.md, 'A search does not read what read would ask about'. glob/list return names only and are unchanged; show is the person's view. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
7 files changed
+138
-5
No files matched your search
@@ -24,6 +24,10 @@ All notable changes to LLeMbas CLI. The format follows
|
||||
- **A command longer than 32 KiB is asked about in every mode, auto included**, without being
|
||||
analysed: a very long line could keep the permission check — and with it the whole program —
|
||||
busy for many seconds.
|
||||
- **The `grep` tool no longer returns lines of a file `read` would ask about.** A search of a
|
||||
directory was judged for the directory only, so the lines of a `.env` in it came back unasked
|
||||
— in plan mode too. Such files are now left out of the result, which says how many and which,
|
||||
so the model can ask to `read` one. Names are not content: `glob` and `list` still show them.
|
||||
- **The force-push floor reads the push.** It refused any forced push with "main" somewhere in
|
||||
it (`feature/main-menu`) and missed deleting the branch (`git push origin :main`,
|
||||
`--delete main`), a forced `--all`/`--mirror`, and a bare `git push -f` while on main. The
|
||||
|
||||
@@ -114,6 +114,9 @@ page *Harness-parity* in LLeMbas CLI's wiki.
|
||||
pattern). No longer refused: a forced push to `feature/main-menu`. Now refused: `:main`,
|
||||
`--delete main`, `-d`, a forced `--all`/`--mirror`, and a forced push naming no branch when
|
||||
the current branch is known to be main or master. `conformance/hardline.json` has `branch`.
|
||||
- **A search does not read what `read` would ask about** (`filesystem.md`): `grep` returns no
|
||||
line of a file whose `read` is not allowed at that moment, and names the files left out;
|
||||
`glob` and `list` are names, not content, and unchanged. **Both implementations.**
|
||||
- Conformance: every case of `conformance/terminal.json` is in the new names; cases of `env`,
|
||||
`status`, `status_dir` and `prompt` in the old ones; `errors.json` for the product `term`.
|
||||
|
||||
|
||||
@@ -149,6 +149,28 @@ device.
|
||||
A device's own errors (a file too large, a binary file, a protected path) are the CLI's and stay as
|
||||
they are; the ones above it says the same way.
|
||||
|
||||
## A search does not read what `read` would ask about
|
||||
|
||||
Spec 3.15.0. `grep` over a directory reads every file under it, and its permission is judged for
|
||||
the directory. **No line of a file comes back from a search unless `read` of that file would run
|
||||
without asking, by the rules and the mode as they are at that moment** — a file whose `read` rule
|
||||
is `ask` or `deny` (`.env`, by the defaults), also when it is reached through a symbolic link, in
|
||||
manual, edit and plan mode alike; in auto mode only a `deny` leaves a file out. The files left out
|
||||
that had a match are counted and named after the matches, so that the model can `read` one — which
|
||||
asks the person:
|
||||
|
||||
```
|
||||
(2 files with matches were left out: reading them needs the person's approval — use read on one to ask: {path}, {path})
|
||||
```
|
||||
|
||||
At most five are named, then `…`. A search *of the file itself* (`path` names it) was judged as a
|
||||
read of it and is not filtered again. Outside the project the person answered for the directory.
|
||||
|
||||
**Names are not content.** `glob` and `list` return the name of such a file as of any other: that
|
||||
`.env` exists is not what the rule protects, and the model needs the name to ask for it. `show`
|
||||
puts a file in front of the person, not the model, and follows its own permission. What the person
|
||||
attaches themself (`@file`) is their own act.
|
||||
|
||||
## A listing
|
||||
|
||||
`list` and a directory given to `read`: one entry per line, directories (and mounts) with a trailing
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// backstop, not a budget (LLeMbas generation._run / _wrap_up).
|
||||
// The text is the harness spec's, so LLeMbas's Continue sends the same words.
|
||||
import continueText from "../../harness/prompts/tasks/continue.md" with { type: "text" }
|
||||
import { isAbsolute } from "node:path"
|
||||
import { isAbsolute, relative } 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"
|
||||
@@ -364,6 +364,12 @@ export class Engine {
|
||||
}
|
||||
|
||||
/** What is met now, for a call: the mode for plan, the display as it is; the rest are fixed. */
|
||||
/** Whether the read tool would read this file unasked right now (ToolContext.mayRead). */
|
||||
mayRead(abs: string): boolean {
|
||||
const ctx: PermContext = { ...this.o.perm, mode: this.mode, rules: [...this.o.perm.rules, ...this.sessionRules] }
|
||||
return evaluate({ permission: "read", class: "read", patterns: [relative(ctx.root, abs) || "."], paths: [abs] }, ctx).action === "allow"
|
||||
}
|
||||
|
||||
private met(): Set<Requirement> {
|
||||
const met = this.could()
|
||||
if (this.mode !== "plan") met.delete("plan")
|
||||
@@ -1165,6 +1171,7 @@ export class Engine {
|
||||
...this.o.toolCtx,
|
||||
signal,
|
||||
backgroundNow: bgNow.signal,
|
||||
mayRead: (abs) => this.mayRead(abs),
|
||||
question: this.o.asker.question ? (req, id) => this.waiting(this.o.asker.question!(req, id), "question") : undefined,
|
||||
plan: {
|
||||
get: () => this.plan,
|
||||
|
||||
+32
-4
@@ -1,5 +1,5 @@
|
||||
import { stat } from "node:fs/promises"
|
||||
import { join, relative } from "node:path"
|
||||
import { isAbsolute, join, relative } from "node:path"
|
||||
import { z } from "zod"
|
||||
import { absPath, defineTool, showPath, ToolError, truncate, type ToolContext } from "./tool.ts"
|
||||
import { described } from "../harness.ts"
|
||||
@@ -35,6 +35,12 @@ async function listFiles(dir: string, glob: string | undefined, ctx: ToolContext
|
||||
return out
|
||||
}
|
||||
|
||||
/** What a search says of the files it did not return lines from (filesystem.md). */
|
||||
export function leftOut(files: string[]): string {
|
||||
const shown = files.slice(0, 5).join(", ") + (files.length > 5 ? ", …" : "")
|
||||
return `(${files.length} ${files.length === 1 ? "file with matches was" : "files with matches were"} left out: reading ${files.length === 1 ? "it" : "them"} needs the person's approval — use read on one to ask: ${shown})`
|
||||
}
|
||||
|
||||
export const globTool = defineTool({
|
||||
...described("glob"),
|
||||
access: "glob",
|
||||
@@ -75,16 +81,36 @@ export const grepTool = defineTool({
|
||||
async run(a, ctx) {
|
||||
const target = absPath(a.path ?? ".", ctx)
|
||||
const lines: string[] = []
|
||||
// A search over a directory reads every file in it. Nothing of a file `read` would ask about
|
||||
// or refuse comes back (the permission above judged the directory, not each file): it is
|
||||
// left out, and said — the model can `read` one, which asks.
|
||||
const left = new Set<string>()
|
||||
const judged = new Map<string, boolean>()
|
||||
const keep = (abs: string): boolean => {
|
||||
// Outside the project the person answered for the directory itself (external_directory),
|
||||
// and the read rules are the project's.
|
||||
if (abs === target || !ctx.mayRead || !(abs === ctx.root || abs.startsWith(ctx.root.endsWith("/") ? ctx.root : ctx.root + "/"))) return true
|
||||
let ok = judged.get(abs)
|
||||
if (ok === undefined) judged.set(abs, (ok = ctx.mayRead(abs)))
|
||||
if (!ok) left.add(abs)
|
||||
return ok
|
||||
}
|
||||
if (!(await stat(target).catch(() => undefined))) throw new ToolError(`No such file or directory: ${target}`)
|
||||
if (hasRg) {
|
||||
const args = ["rg", "--line-number", "--no-heading", "--color", "never", "--hidden", "--glob", "!.git", "--max-columns", "400", "--max-columns-preview"]
|
||||
// --null: the file's name ends at a NUL, so it is read exactly, whatever it holds.
|
||||
const args = ["rg", "--line-number", "--no-heading", "--with-filename", "--null", "--color", "never", "--hidden", "--glob", "!.git", "--max-columns", "400", "--max-columns-preview"]
|
||||
if (a.ignore_case) args.push("-i")
|
||||
if (a.literal) args.push("-F")
|
||||
if (a.include) args.push("--glob", a.include)
|
||||
args.push("-e", a.pattern, target)
|
||||
const r = await run(args, ctx.root, ctx.signal)
|
||||
if (r.code > 1) throw new ToolError(r.err.trim() || `rg exited ${r.code}`)
|
||||
for (const l of r.out.split("\n")) if (l) lines.push(l)
|
||||
for (const l of r.out.split("\n")) {
|
||||
if (!l) continue
|
||||
const nul = l.indexOf("\0")
|
||||
if (nul < 0) lines.push(l)
|
||||
else if (keep(isAbsolute(l.slice(0, nul)) ? l.slice(0, nul) : join(ctx.root, l.slice(0, nul)))) lines.push(`${l.slice(0, nul)}:${l.slice(nul + 1)}`)
|
||||
}
|
||||
} else {
|
||||
let re: RegExp
|
||||
try {
|
||||
@@ -95,6 +121,7 @@ export const grepTool = defineTool({
|
||||
const st = await stat(target)
|
||||
const files = st.isDirectory() ? (await listFiles(target, a.include, ctx)).map((f) => join(target, f)) : [target]
|
||||
for (const f of files) {
|
||||
if (!keep(f)) continue
|
||||
const text = await Bun.file(f).text().catch(() => "")
|
||||
if (text.includes("\0")) continue
|
||||
text.split("\n").forEach((l, i) => {
|
||||
@@ -106,7 +133,8 @@ export const grepTool = defineTool({
|
||||
const more = lines.length > 200 ? `\n(${lines.length - 200} more matches — narrow the search)` : ""
|
||||
// The commonest miss: searching for code text like `len(x)` as a regex, where ( ) are a group.
|
||||
const hint = !lines.length && !a.literal && /[()[\]{}.*+?|\\^$]/.test(a.pattern) ? " The pattern is a regular expression; to search for the text as written, set literal: true." : ""
|
||||
return { output: truncate(lines.slice(0, 200).join("\n") || "No matches." + hint) + more, title: `/${a.pattern}/ · ${lines.length} matches`, meta: { hits: lines.length } }
|
||||
const out = left.size ? `\n${leftOut([...left])}` : ""
|
||||
return { output: truncate(lines.slice(0, 200).join("\n") || "No matches." + hint) + more + out, title: `/${a.pattern}/ · ${lines.length} matches`, meta: { hits: lines.length } }
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -18,6 +18,11 @@ export interface ToolContext {
|
||||
/** mtime (ms) of each file when it was last read or written by a tool, to detect outside edits. */
|
||||
fileStamps: Map<string, number>
|
||||
bashTimeoutMs: number
|
||||
/** Whether `read` of this file would run without asking, by the rules and the mode as they are
|
||||
* now (set by the engine per step). A tool that reads many files on the model's behalf (grep)
|
||||
* returns nothing of a file this refuses (filesystem.md, *A search does not read what `read`
|
||||
* would ask about*). Absent: nothing is filtered (a caller with no permissions of its own). */
|
||||
mayRead?: (abs: string) => boolean
|
||||
/** Instruction files (AGENTS.md / CLAUDE.md) the model has already been given. */
|
||||
instructionsSeen?: Set<string>
|
||||
/** Ask the user questions (the ask_user tool). Absent where nobody can answer. */
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
// A search returns nothing of a file `read` would ask about (harness filesystem.md, spec 3.15.0).
|
||||
import { afterAll, expect, test } from "bun:test"
|
||||
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join, relative } from "node:path"
|
||||
import type { Mode } from "../src/config/schema.ts"
|
||||
import { DEFAULT_RULES, evaluate, toRules } from "../src/permission/evaluate.ts"
|
||||
import { BUILTIN_HARDLINE } from "../src/permission/hardline.ts"
|
||||
import { grepTool, globTool } from "../src/tool/search.ts"
|
||||
import type { ToolContext } from "../src/tool/tool.ts"
|
||||
|
||||
const root = realpathSync(mkdtempSync(join(tmpdir(), "lembas-search-")))
|
||||
afterAll(() => rmSync(root, { recursive: true, force: true }))
|
||||
mkdirSync(join(root, "src"))
|
||||
writeFileSync(join(root, ".env"), "API_KEY=made-up-value\n")
|
||||
writeFileSync(join(root, "src", ".env.local"), "API_KEY=another\n")
|
||||
writeFileSync(join(root, ".env.example"), "API_KEY=\n")
|
||||
writeFileSync(join(root, "src", "a.ts"), "const API_KEY = process.env.API_KEY\n")
|
||||
symlinkSync(join(root, ".env"), join(root, "notes.txt"))
|
||||
|
||||
const ctxFor = (mode: Mode): ToolContext =>
|
||||
({
|
||||
root,
|
||||
cwd: root,
|
||||
signal: new AbortController().signal,
|
||||
readFiles: new Set(),
|
||||
fileStamps: new Map(),
|
||||
bashTimeoutMs: 1000,
|
||||
// What the engine composes (Engine.mayRead): the read tool's own answer, now.
|
||||
mayRead: (abs: string) => evaluate({ permission: "read", class: "read", patterns: [relative(root, abs) || "."], paths: [abs] }, { mode, rules: toRules(DEFAULT_RULES, "default"), hardline: BUILTIN_HARDLINE, root }).action === "allow",
|
||||
}) as ToolContext
|
||||
|
||||
for (const mode of ["manual", "edit", "plan"] as const)
|
||||
test(`grep in ${mode} mode returns no line of .env, and says what it left out`, async () => {
|
||||
const r = await grepTool.run({ pattern: "API_KEY" }, ctxFor(mode))
|
||||
expect(r.output).not.toContain("made-up-value")
|
||||
expect(r.output).not.toContain("another")
|
||||
expect(r.output).toContain("src/a.ts:1:")
|
||||
expect(r.output).toContain(".env.example:1:")
|
||||
expect(r.output).toContain("2 files with matches were left out")
|
||||
expect(r.output).toContain(join(root, ".env"))
|
||||
})
|
||||
|
||||
test("grep with include naming the file is filtered the same", async () => {
|
||||
const r = await grepTool.run({ pattern: ".", include: ".env" }, ctxFor("manual"))
|
||||
expect(r.output).not.toContain("made-up-value")
|
||||
expect(r.output).toContain("1 file with matches was left out")
|
||||
})
|
||||
|
||||
test("grep through a link to .env is filtered when ripgrep is told to follow it by name", async () => {
|
||||
const r = await grepTool.run({ pattern: "API_KEY", path: "." , include: "notes.txt" }, ctxFor("manual"))
|
||||
expect(r.output).not.toContain("made-up-value")
|
||||
})
|
||||
|
||||
test("auto mode asks nothing, so nothing is left out", async () => {
|
||||
const r = await grepTool.run({ pattern: "API_KEY" }, ctxFor("auto"))
|
||||
expect(r.output).toContain("made-up-value")
|
||||
expect(r.output).not.toContain("left out")
|
||||
})
|
||||
|
||||
test("names are not content: glob lists .env", async () => {
|
||||
const r = await globTool.run({ pattern: "**/.env*" }, ctxFor("manual"))
|
||||
expect(r.output).toContain(join(root, ".env"))
|
||||
})
|
||||
Reference in new issue
Block a user