diff --git a/package.json b/package.json index a234e81..19297a7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencode-switchman", - "version": "1.1.0", + "version": "1.1.1", "description": "OpenCode orchestration plugin: six-lane shell matrix dispatch (hard ROUTE_META validation / breaker self-healing / probes / three-pool quota awareness / cost-aware tiebreaker)", "license": "MIT", "repository": { diff --git a/src/assets/agents-md.ts b/src/assets/agents-md.ts index b11be30..6b08f47 100644 --- a/src/assets/agents-md.ts +++ b/src/assets/agents-md.ts @@ -16,6 +16,8 @@ // [2026-09-14]-[shell handoff relay §2 item 5 + §6 declaration widening: D1's soft tiers end with the inline HANDOFF marker the // dispatcher must treat as the authoritative remaining-work state; §6's declaration duty moves from a major-action list to // every substantive action, matching the per-turn [ROUTE] line (src/route-line.ts)] +// [2026-09-17]-[broad-search clarify: §5 gains the ask-first rule for whole-project searches (mechanically enforced by +// the search clarify gate in src/index.ts + pure helpers in src/search-clarify.ts; jsonc search.clarify:false disables)] export const AGENTS_MD = `# Global Protocol (master dispatcher rules; opencode-switchman subagent rules are embedded in the shell definitions) > This protocol ships with the opencode-switchman plugin and is injected into the system prompt automatically by default (bundled with the package, updated with versions); scope: opencode with the opencode-switchman plugin installed. @@ -69,8 +71,9 @@ Task artifacts (plans, implementation progress, process-control notes, design do ## 4. Verification and Re-Review - Logic changes must be verified once; changes >20 lines, multiple call sites, or long output → hand to tester; >300 lines or core/security/data logic → reviewer re-review (review chain, cross-family preferred — same-family self-review only as a last-resort DOWNGRADED seat). -## 5. Self-read budget (always on, every turn) +## 5. Self-read Budget and Broad-Search Clarify (always on, every turn) Each self-read is costed against a per-call injection budget (default ~1500 tokens; the live cap rides the \`[WATERMARK:SESSION]\` banner line). Reads over the cap are auto-bounded or rejected with exact bounded-retry params (\`read limit=N offset=M\`); once the per-turn self-read cap is spent, delegate the turn's remaining reads to an economy shell. Watermarks are lifecycle advice only: past {{SOFT}} prefer delegating new scans; past {{HARD}} wrap up (verification/delivery bash stays open; state-changing git is delivery — run it yourself, never delegate it); at {{FORCE}} compact immediately. Unbounded history dumps (e.g. \`git log -p\` without \`-n\`) are rejected at any context size — scope them or delegate. +Broad-search clarify: the session's first whole-project search (glob \`**\` without a path scope, pathless grep, or recursive rg/grep -r/find/fd at the project root) is denied once by the plugin with an ask-first error — relay that marker question to the user verbatim (more precise file/directory guidance?). With narrower guidance, redo the search scoped to it (never silently widen back to whole-project while that scope holds); without guidance or on a decline, retry the same call (it passes once the ask completed). Retrying the search without asking is a violation. Disable via jsonc \`search.clarify:false\`. ## 6. Major-Action Reporting and the Expert Panel - [MANDATORY] Before each substantive action (the enumeration below is the minimum set, not the ceiling; self-reading >3 files or a single file >1000 lines, self-editing >100 lines or across files, commands expected to produce large output, any delegation), declare in one sentence: \`[DISPATCH] self: \` / \`[DISPATCH] delegate : \`; acting without declaration is forbidden. diff --git a/src/config.ts b/src/config.ts index cf575e7..642ab2d 100644 --- a/src/config.ts +++ b/src/config.ts @@ -39,6 +39,8 @@ export interface UserConfig { workspace: { enabled: boolean; dirname: string } // [2026-09-05]-[project language preference: conversation/comments/docs language — first-run ask + per-turn [LANG] iron-rule line] lang: { enabled: boolean; ask: boolean; candidates: string[] } + // [2026-09-17]-[broad-search clarify: whole-project searches ask the user for narrower guidance once per session] + search: { clarify: boolean } // [2026-09-06]-[tmux pane mirroring: live subagent attach panes in the home tmux window's right column] tmux: { enabled: boolean; rightPct: number; maxPanes: number; mini: boolean } lanes: Partial> @@ -52,7 +54,7 @@ export const DEFAULT_CONTEXT_TOKENS = { soft: 50_000, hard: 90_000, force: 130_0 export const DEFAULT_DELEGATION_FLOOR = 3_000 /** Factory defaults for behavior sections (fillMissing baseline; only bad-typed values fall back and report SWM037) */ -export function defaultBehaviorConfig(): Pick { +export function defaultBehaviorConfig(): Pick { return { quota: { glmFiveHourReservePct: 90, deepseekLowBalanceWarnCny: 10 }, cost: { enabled: true }, @@ -68,6 +70,7 @@ export function defaultBehaviorConfig(): Pick { filled.lang.enabled = defaults.lang.enabled }) if (typeof filled.lang.ask !== "boolean") bad("lang.ask", () => { filled.lang.ask = defaults.lang.ask }) if (!Array.isArray(filled.lang.candidates) || filled.lang.candidates.length === 0 || !filled.lang.candidates.every((c: unknown) => typeof c === "string" && c.trim() === c && !!c.trim() && c.length <= 48)) bad("lang.candidates", () => { filled.lang.candidates = structuredClone(defaults.lang.candidates) }) + // [2026-09-17]-[broad-search clarify switch] + if (typeof filled.search.clarify !== "boolean") bad("search.clarify", () => { filled.search.clarify = defaults.search.clarify }) // [2026-09-06]-[tmux pane mirroring: enabled/mini booleans; rightPct integer 10..90; maxPanes integer 1..4] if (typeof filled.tmux.enabled !== "boolean") bad("tmux.enabled", () => { filled.tmux.enabled = defaults.tmux.enabled }) if (!Number.isInteger(filled.tmux.rightPct) || filled.tmux.rightPct < 10 || filled.tmux.rightPct > 90) bad("tmux.rightPct", () => { filled.tmux.rightPct = defaults.tmux.rightPct }) @@ -278,6 +283,8 @@ export function resolveEffectiveOptions(raw: unknown, cfg: UserConfig): { option workspace: has(o, "workspace") ? { ...cfg.workspace, ...o.workspace } : cfg.workspace, // [2026-09-05]-[project language preference switch: same merge pattern (jsonc baseline, tuple explicit keys override)] lang: has(o, "lang") ? { ...cfg.lang, ...o.lang } : cfg.lang, + // [2026-09-17]-[broad-search clarify switch: same merge pattern] + search: has(o, "search") ? { ...cfg.search, ...o.search } : cfg.search, // [2026-09-06]-[tmux pane mirroring switches: same merge pattern] tmux: has(o, "tmux") ? { ...cfg.tmux, ...o.tmux } : cfg.tmux, lanes: has(o, "lanes") ? o.lanes : cfg.lanes, @@ -293,7 +300,7 @@ export function resolveEffectiveOptions(raw: unknown, cfg: UserConfig): { option lmarenaCheck: has(o.capability, "lmarenaCheck") ? o.capability!.lmarenaCheck! : cfg.capability.lmarenaCheck, }, } - for (const section of ["cost", "banner", "rules", "lanes", "matrix", "capability", "context", "builtinAgents", "injection", "dispatch", "relay", "workspace", "lang", "tmux"] as const) if (has(o, section)) legacySections.push(section) + for (const section of ["cost", "banner", "rules", "lanes", "matrix", "capability", "context", "builtinAgents", "injection", "dispatch", "relay", "workspace", "lang", "search", "tmux"] as const) if (has(o, section)) legacySections.push(section) return { options, legacySections } } export function routePolicy(config: UserConfig, legacy?: Partial>): RoutePolicy { diff --git a/src/index.ts b/src/index.ts index 34cfe52..44bf88c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -62,6 +62,7 @@ import type { SwitchmanOptions, Lane, LaneResult, Pool, ShellRegEntry, ModelKey import { WorkspaceTracker, DEFAULT_WORKSPACE_DIRNAME, type EnsuredWorkspace } from "./workspace" import { TmuxPaneManager, serverOriginOf } from "./tmux" import { loadLangConfig, renderLangLine, renderAskDirective, saveLangFromQuestion, langGateDecision, LANG_GATE_TOOLS, hasLangMarkerQuestions, detectUiLocale } from "./lang-config" +import { SEARCH_CLARIFY_TOOLS, SEARCH_CLARIFY_MAX_DENIES, isBroadSearchCall, describeSearchCall, searchClarifyDenyMessage, hasSearchMarkerQuestion } from "./search-clarify" import { renderRouteLine, routeLineEnabled } from "./route-line" import { loadDispatchMode } from "./dispatch-mode" import { detectMode, readConfigured, normalizeProviderListResponse } from "./activation" @@ -213,6 +214,12 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // [2026-09-07]-[lang hard gate: per-session waiver set — a completed marker question call that did NOT persist a // config (user declined / unparsable output) opens the gate for this session so a decline never deadlocks writes] const langGateWaived = new Set() + // [2026-09-17]-[broad-search clarify gate: searchScopeAsked = sessions whose scope ask already completed (marker + // question captured, or anti-deadlock fail-open after repeated denies) — broad searches pass from then on; + // searchDenyCount = per-session deny counter backing the fail-open (a broken/unavailable question tool must + // never wedge a session on its own broad search)] + const searchScopeAsked = new Set() + const searchDenyCount = new Map() // [2026-09-06]-[tmux pane mirroring: dispatched subagent sessions open as live `opencode attach` panes in the home // tmux window — main pane left / subagent column right (max 3 visible, FIFO replacement on completion); inert // outside tmux, fail-open everywhere. pendingTask = dispatch intents recorded per main session, consumed by the @@ -1694,6 +1701,34 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (denySkip.has(input.callID)) throw e // internal error on our side (never one of our own denies) → fail-open, do not break the tool path } + // [2026-09-17]-[broad-search clarify gate: a main session's first whole-project search (glob '**' unscoped / + // pathless grep / recursive rg|grep -r|find|fd at the project root) is denied with an ask-first error — the + // user is asked ONCE for more precise file guidance (marker question); narrower guidance re-scopes the retry, + // no guidance (or a decline) re-runs it (the latch opens on marker-question completion; after 2 denies without + // an ask the gate fail-opens for the session — anti-deadlock). Shell/internal sessions exempt (a delegated + // scouter IS the sanctioned broad-search path); detection is conservative (uncertain shapes pass); not ctx + // control — /ctx-pause does not suspend it; search.clarify:false disables entirely] + try { + const scSid = (input as any).sessionID as string | undefined + if (scSid && SEARCH_CLARIFY_TOOLS.has(input.tool) && !isShellOrInternalSession(scSid) + && options.search!.clarify && !searchScopeAsked.has(scSid)) { + if (isBroadSearchCall(input.tool, output.args)) { + const n = (searchDenyCount.get(scSid) ?? 0) + 1 + searchDenyCount.set(scSid, n) + if (n > SEARCH_CLARIFY_MAX_DENIES) { + searchScopeAsked.add(scSid) + appendStatusLog(`search clarify gate: fail-open after ${SEARCH_CLARIFY_MAX_DENIES} denies without an ask — gate open for session ${scSid}`) + } else { + denySkip.add(input.callID) + appendStatusLog(`search clarify gate: tool '${input.tool}' denied (broad search, ask-first) in session ${scSid} (${n}/${SEARCH_CLARIFY_MAX_DENIES})`) + throw new Error(searchClarifyDenyMessage(describeSearchCall(input.tool, output.args))) + } + } + } + } catch (e) { + if (denySkip.has(input.callID)) throw e + // internal error on our side (never one of our own denies) → fail-open, do not break the tool path + } // [2026-09-14]-[D3 dispatch:"off" opt-out: a project that set the top-level "dispatch":"off" in // /settings.json stands down ALL dispatch governance for task calls — the entire task path // below is skipped (uninjected-shell deny + its autoRedirect, built-in agent deny + its autoRedirect, @@ -1870,6 +1905,12 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { langGateWaived.add(hookInput.sessionID) appendStatusLog(`lang gate: marker question completed without a saved config — gate waived for session ${hookInput.sessionID}`) } + // [2026-09-17]-[broad-search clarify latch: our marker question completed (answered or declined — either + // way the user was asked) → broad searches pass for the rest of the session] + if (hasSearchMarkerQuestion(hookInput.args)) { + searchScopeAsked.add(hookInput.sessionID) + appendStatusLog(`search clarify: scope ask completed — gate open for session ${hookInput.sessionID}`) + } } catch { /* fail-open */ } } const sid = hookInput.sessionID @@ -2060,6 +2101,8 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { workspace.forget(sid) langAsked.delete(sid) langGateWaived.delete(sid) + searchScopeAsked.delete(sid) + searchDenyCount.delete(sid) // [2026-09-06]-[tmux pane mirroring: deleted child frees its pane; deleted main drops its dispatch intents] if (tmuxPanes.tracking(sid)) void tmuxPanes.noteChildEnd(sid) pendingTask.delete(sid) diff --git a/src/provider-config.ts b/src/provider-config.ts index 509c3fc..67570cc 100644 --- a/src/provider-config.ts +++ b/src/provider-config.ts @@ -148,6 +148,11 @@ export function renderDefaultConfigJsonc(): string { // "maxPanes": 3, // max visible subagent panes (1..4; extra dispatches wait in a FIFO queue and take over freed panes) // "mini": false // true = minimal attach interface instead of the full TUI // }, + // Broad-search clarify: the first whole-project search per main session (glob '**' unscoped / pathless grep / + // recursive rg|grep -r|find|fd) is denied once with an ask-first error — the user is asked for narrower file guidance. + // "search": { + // "clarify": true // master switch; false = broad searches run without the ask + // }, // Third-party/future extension data goes under namespace keys, not into providers. "extensions": {} } diff --git a/src/search-clarify.ts b/src/search-clarify.ts new file mode 100644 index 0000000..32f6eef --- /dev/null +++ b/src/search-clarify.ts @@ -0,0 +1,126 @@ +// [2026-09-17]-[broad-search clarify gate: a whole-project search (glob '**' without a path scope / grep without path / +// recursive rg|grep -r|find|fd from the project root) is denied ONCE per main session with an ask-first error — the +// model must relay a marker question to the user ("more precise file/directory guidance?"); narrower guidance re-scopes +// the search, no guidance re-runs it (the call passes after the ask). Latch = marker question completion (captured in +// tool.execute.after) or the 2nd deny (anti-deadlock fail-open, a broken/unavailable question tool must never wedge a +// session). Pure helpers + constants only; wiring in src/index.ts; protocol clause in src/assets/agents-md.ts §5] +// +// Detection is deliberately conservative (fail-open): quoted multi-token patterns and unexpected shapes classify as +// scoped — a missed broad search costs some tokens, a false deny wedges the task. Shell/internal sessions are exempt +// at the wiring layer (delegated scouter shells ARE the delegated broad-search path). + +/** Marker embedded in the ask's question text and matched in tool.execute.after capture */ +export const SEARCH_ASK_MARKER = "switchman-search-scope" + +/** Tools whose calls can constitute a broad search (task/read/edit can never be one) */ +export const SEARCH_CLARIFY_TOOLS: ReadonlySet = new Set(["glob", "grep", "bash"]) + +/** Anti-deadlock: after this many denies without an ask the gate opens permanently for the session */ +export const SEARCH_CLARIFY_MAX_DENIES = 2 + +/** path value that leaves the search anchored at the project root (absent / empty / "." / "./" / "/") */ +function isRootishPath(p: unknown): boolean { + if (p === undefined || p === null) return true + if (typeof p !== "string") return false + const t = p.trim() + return t === "" || t === "." || t === "./" || t === "/" +} + +/** True when the tool call would scan the whole project rather than a named scope (pure, conservative) */ +export function isBroadSearchCall(tool: string, args: unknown): boolean { + try { + const a = (args ?? {}) as { pattern?: unknown; path?: unknown; command?: unknown } + if (tool === "glob") { + const pattern = typeof a.pattern === "string" ? a.pattern : "" + if (!pattern.includes("**")) return false + // a concrete leading directory in the pattern itself (e.g. src/**/*.ts) already scopes the search + const first = pattern.split("/")[0] ?? "" + const wildcardFirst = first === "**" || first.includes("*") || /^[{[?]/.test(first) + return wildcardFirst && isRootishPath(a.path) + } + if (tool === "grep") { + // whole-project text search = exactly what the user must be asked about; include filters do not scope location + return isRootishPath(a.path) + } + if (tool === "bash") { + const command = typeof a.command === "string" ? a.command : "" + return isBroadBashSearch(command) + } + return false + } catch { return false } +} + +const BASH_SEARCH_HEAD = /^(?:sudo\s+|env\s+|[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*(rg|grep|find|fd|ag|ack)\b/ + +/** Flags that consume the NEXT token as a value (pattern/file/glob/type/…); their operands must not be mistaken for path operands */ +const BASH_VALUE_FLAGS: ReadonlySet = new Set([ + "-e", "-f", "-g", "-m", "-A", "-B", "-C", "-t", "-T", + "--regexp", "--file", "--glob", "--type", "--type-not", "--max-count", "--max-filesize", + "--include", "--exclude", "--exclude-dir", "--pre", "--context", "--after-context", "--before-context", + "-name", "-iname", "-path", "-ipath", "-lname", "-regex", "-iregex", "-type", "-user", "-group", "-perm", "-size", + "-mtime", "-atime", "-ctime", "-newer", "-exec", "-ok", +]) + +/** bash recursive-search heuristic: rg/fd/ag/ack recurse by default, grep only with -r/-R, find walks its root operand. + * Only the FIRST pipeline segment is analyzed (downstream `| head`/`| sort` legs are filters, not the search scope); + * quoted tokens are unquoted; '!'-prefixed exclusion globs are never path operands */ +function isBroadBashSearch(command: string): boolean { + const seg = command.trim().split(/(?:\|\||&&|;|\|)/)[0]!.trim() + const m = BASH_SEARCH_HEAD.exec(seg) + if (!m) return false + const name = m[1]! + const tokens = seg.slice(m[0].length).split(/\s+/).filter(Boolean) + const positional: string[] = [] + let skipNext = false + for (const raw of tokens) { + if (skipNext) { skipNext = false; continue } + if (raw.startsWith("-")) { + if (BASH_VALUE_FLAGS.has(raw)) skipNext = true + continue + } + const t = raw.replace(/^['"]|['"]$/g, "") + if (t.startsWith("!")) continue + positional.push(t) + } + if (name === "grep") { + // grep recurses only with -r/-R among the flags seen + const flags = tokens.filter((t) => t.startsWith("-")).join(" ") + if (!/(^|\s)-[a-zA-Z]*[rR]/.test(` ${flags} `) && !/\s--recursive\b/.test(` ${flags} `)) return false + } + if (name === "find") { + // find [flags] ROOT [...]: absent root = cwd; root-ish root = whole project + return positional.length === 0 || isRootishPath(positional[0]) + } + // rg/fd/ag/ack [flags] PATTERN [PATH...]: pattern-only (or -e pattern) = cwd; any root-ish path operand = whole project + if (positional.length <= 1) return true + return positional.some((p) => isRootishPath(p)) +} + +/** One-line description of the blocked call for the ask text (bounded, quoted fragments stripped) */ +export function describeSearchCall(tool: string, args: unknown): string { + const a = (args ?? {}) as { pattern?: unknown; command?: unknown } + const raw = tool === "bash" ? (typeof a.command === "string" ? a.command : "") : (typeof a.pattern === "string" ? a.pattern : "") + const desc = raw.replace(/["'\n]/g, " ").replace(/\s+/g, " ").trim().slice(0, 60) + return `${tool}: ${desc || "(no pattern)"}` +} + +/** Pure gate decision: null = allow, string = the denial message shown to the model */ +export function searchClarifyDenyMessage(desc: string): string { + return [ + `[opencode-switchman] BLOCKED (broad-search clarify): this call would search the whole project (${desc}).`, + `Ask the user ONCE via the question tool before re-running it — question text verbatim, marker included:`, + `"${SEARCH_ASK_MARKER}: I am about to run a whole-project search (${desc}). Do you have more precise`, + `file/directory guidance?" (single-choice, options: "No — search the whole project" / "Yes — I will type paths",`, + `free input allowed). With narrower paths: redo the search scoped to them and never fall back to a whole-project`, + `scan while that scope holds. Without guidance (or the user declines): retry this exact call — it passes once the`, + `ask has completed. Retrying the search without asking is a violation.`, + ].join(" ") +} + +/** True when the question-tool args carry our marker question (the search-scope ask relayed by the model) */ +export function hasSearchMarkerQuestion(args: unknown): boolean { + try { + const questions = (args as any)?.questions + return Array.isArray(questions) && questions.some((q) => typeof q?.question === "string" && q.question.includes(SEARCH_ASK_MARKER)) + } catch { return false } +} diff --git a/src/shells.json b/src/shells.json index 720ac23..a3d6f4f 100644 --- a/src/shells.json +++ b/src/shells.json @@ -1,6 +1,6 @@ { "_note": "opencode-switchman full matrix: authoritative enabled surface (models enabled in model management, scripts/visible-models.txt) × all declared thinking efforts (models.dev reasoning_options, toggle→off). Generated by scripts/gen-shells.ts — do not edit by hand; after model on/off changes, sync the pin file and re-run bun run gen:shells. The six lane chains are computed from capability score × lane affinity × structural gate × billing factor (api billing 0.85, unknown group 0.75, sunk by coefficient; no vendor-reserved seats).", - "generated_at": "2026-09-15T02:01:26.140Z", + "generated_at": "2026-09-17T13:56:26.846Z", "counts": { "shells": 104, "visible_models": 13 diff --git a/src/types.ts b/src/types.ts index a3c058a..5883c0a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -343,6 +343,12 @@ export interface LangOptions { /** Candidate language labels offered in the ask (custom free input always allowed besides these) */ candidates?: string[] } +// [2026-09-17]-[broad-search clarify: the first whole-project search per main session is denied once with an ask-first +// error (more precise file guidance? — narrower scope re-targets the search, no guidance re-runs it); see src/search-clarify.ts] +export interface SearchOptions { + /** Master switch (default true): broad-search ask-first gate on glob/grep/bash */ + clarify?: boolean +} // [2026-09-06]-[tmux pane mirroring: dispatched subagent sessions open as live `opencode attach` panes in a // right-hand column of the home tmux window (main pane left, subagent panes right; status line untouched); // inert outside tmux — see src/tmux.ts] @@ -377,5 +383,6 @@ export interface SwitchmanOptions { relay?: RelayOptions workspace?: WorkspaceOptions lang?: LangOptions + search?: SearchOptions tmux?: TmuxOptions } diff --git a/src/version.ts b/src/version.ts index b3d8b14..8879019 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,2 +1,2 @@ // Generated at build time: run bun scripts/gen-version.ts -export const PLUGIN_VERSION = "1.1.0" +export const PLUGIN_VERSION = "1.1.1" diff --git a/test/search-clarify.test.ts b/test/search-clarify.test.ts new file mode 100644 index 0000000..c6095ca --- /dev/null +++ b/test/search-clarify.test.ts @@ -0,0 +1,157 @@ +// [2026-09-17]-[broad-search clarify behavioral contract: a main session's first whole-project search (glob '**' +// unscoped / pathless grep / recursive rg|grep -r|find|fd at the root) is denied with an ask-first marker question; +// the retry passes once the ask completed (marker question capture) or fail-opens after the 2nd deny (anti-deadlock); +// scoped searches, shell subagent sessions and search.clarify:false are exempt. Pure helpers matrix + hook wiring] +import { expect, test } from "bun:test" +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" + +const configDir = mkdtempSync(join(tmpdir(), "switchman-srch-config-")) +const stateDir = mkdtempSync(join(tmpdir(), "switchman-srch-state-")) +const projectDir = mkdtempSync(join(tmpdir(), "switchman-srch-project-")) +process.env.OPENCODE_CONFIG_DIR = configDir +process.env.SWITCHMAN_STATE = stateDir +// project language preference pre-configured so the lang hard gate never masks the search gate in bash cases +mkdirSync(join(projectDir, ".switchman"), { recursive: true }) +writeFileSync(join(projectDir, ".switchman", "settings.json"), JSON.stringify({ v: 1, lang: { conversation: "en", comments: "en", docs: "en" } })) + +import { SwitchmanPlugin } from "../src/index" +import { SEARCH_ASK_MARKER, describeSearchCall, hasSearchMarkerQuestion, isBroadSearchCall, searchClarifyDenyMessage } from "../src/search-clarify" + +function readStatusLog(): string { + const p = join(stateDir, "status-log.json") + return existsSync(p) ? readFileSync(p, "utf8") : "" +} + +const fakeClient = { + provider: { list: async () => [] }, + session: { + async fork(opts: any) { return { data: { id: `${opts?.path?.id}_fork`, title: "T (fork)" } } }, + async update() { return { data: {} } }, + async list() { return { data: [] } }, + async get(opts: any) { return { data: { id: opts?.path?.id, title: "T", directory: projectDir } } }, + async summarize() { return { data: true } }, + }, +} + +async function boot(rawOptions: any = {}) { + const hooks = await SwitchmanPlugin({ client: fakeClient, directory: projectDir } as any, { matrix: { mode: "legacy" }, ...rawOptions } as any) + const emit = (event: any) => hooks.event!({ event } as any) + const call = (sid: string, tool: string, args: any) => + hooks["tool.execute.before"]!({ sessionID: sid, tool, callID: `call_${sid}_${Math.random()}` } as any, { args } as any) + const questionDone = (sid: string) => + hooks["tool.execute.after"]!({ sessionID: sid, tool: "question", callID: `q_${sid}_${Math.random()}`, args: { questions: [{ question: `${SEARCH_ASK_MARKER}: I am about to run a whole-project search. Do you have more precise file/directory guidance?`, header: "Search scope", options: [{ label: "No — search the whole project" }, { label: "Yes — I will type paths" }] }] } } as any, + { output: 'No — search the whole project' } as any) + return { hooks, emit, call, questionDone } +} + +test("isBroadSearchCall: glob — recursive wildcard without a path scope is broad; pattern- or path-scoped is not", () => { + expect(isBroadSearchCall("glob", { pattern: "**/*.ts" })).toBe(true) + expect(isBroadSearchCall("glob", { pattern: "**/*.ts", path: "." })).toBe(true) + expect(isBroadSearchCall("glob", { pattern: "**/package.json" })).toBe(true) + expect(isBroadSearchCall("glob", { pattern: "**/*.ts", path: "src" })).toBe(false) + expect(isBroadSearchCall("glob", { pattern: "src/**/*.ts" })).toBe(false) + expect(isBroadSearchCall("glob", { pattern: "*.ts" })).toBe(false) + expect(isBroadSearchCall("glob", { pattern: "package.json" })).toBe(false) +}) + +test("isBroadSearchCall: grep — pathless (or root path) is broad; include filters do not scope location", () => { + expect(isBroadSearchCall("grep", { pattern: "TODO" })).toBe(true) + expect(isBroadSearchCall("grep", { pattern: "TODO", path: "." })).toBe(true) + expect(isBroadSearchCall("grep", { pattern: "TODO", include: "*.ts" })).toBe(true) + expect(isBroadSearchCall("grep", { pattern: "TODO", path: "src" })).toBe(false) + expect(isBroadSearchCall("grep", { pattern: "TODO", path: "src/index.ts" })).toBe(false) +}) + +test("isBroadSearchCall: bash — recursive search commands rooted at the project are broad; scoped operands are not", () => { + expect(isBroadSearchCall("bash", { command: "rg foo" })).toBe(true) + expect(isBroadSearchCall("bash", { command: "rg -n --hidden foo" })).toBe(true) + expect(isBroadSearchCall("bash", { command: "rg foo ." })).toBe(true) + expect(isBroadSearchCall("bash", { command: "sudo rg foo" })).toBe(true) + expect(isBroadSearchCall("bash", { command: "rg foo src" })).toBe(false) + expect(isBroadSearchCall("bash", { command: "grep -rn foo ." })).toBe(true) + expect(isBroadSearchCall("bash", { command: "grep --recursive foo" })).toBe(true) + expect(isBroadSearchCall("bash", { command: "grep -rn foo src/" })).toBe(false) + expect(isBroadSearchCall("bash", { command: "grep foo file.txt" })).toBe(false) // no recursion flag + expect(isBroadSearchCall("bash", { command: "find . -name '*.ts'" })).toBe(true) + expect(isBroadSearchCall("bash", { command: "find src -name x" })).toBe(false) + expect(isBroadSearchCall("bash", { command: "fd pattern" })).toBe(true) + expect(isBroadSearchCall("bash", { command: "fd pattern src" })).toBe(false) + expect(isBroadSearchCall("bash", { command: "ls -la" })).toBe(false) + expect(isBroadSearchCall("bash", { command: "cat package.json" })).toBe(false) +}) + +test("isBroadSearchCall: bash regression 2026-09-17 — exclusion globs are not path operands; pipes are cut at the first segment", () => { + // the incident commands (whole-project Chinese-comment scan that must trigger the ask) + expect(isBroadSearchCall("bash", { command: "rg -n '\\p{Han}' --glob '!node_modules' --glob '!dist' --glob '!*.zh.md' -g '!*.lock' | head -100" })).toBe(true) + expect(isBroadSearchCall("bash", { command: "rg -c '\\p{Han}' --glob '!node_modules' --glob '!dist' --glob '!*.zh.md' -g '!*.lock' | sort -t: -k2 -rn" })).toBe(true) + expect(isBroadSearchCall("bash", { command: "rg -e '\\p{Han}'" })).toBe(true) // -e pattern, no path → cwd + expect(isBroadSearchCall("bash", { command: "find . -type f -name '*.ts' | xargs wc -l" })).toBe(true) + expect(isBroadSearchCall("bash", { command: "grep -rn --include='*.ts' foo ." })).toBe(true) + // explicit file/dir lists stay scoped + expect(isBroadSearchCall("bash", { command: "rg -n '\\p{Han}' README.md docs/reference.md | head -40" })).toBe(false) + expect(isBroadSearchCall("bash", { command: "rg -n foo skills/db-query/scripts/lib/mysql-readonly.js | rg '\\p{Han}' | head -5" })).toBe(false) + expect(isBroadSearchCall("bash", { command: "cat x | rg foo" })).toBe(false) // search command not at the head +}) + +test("deny message carries the verbatim marker question and the retry contract; marker detection is exact", () => { + const msg = searchClarifyDenyMessage(describeSearchCall("glob", { pattern: "**/*.ts" })) + expect(msg).toContain(SEARCH_ASK_MARKER) + expect(msg).toContain("whole-project search (glob: **/*.ts)") + expect(msg).toContain("question tool") + expect(msg).toContain("retry this exact call") + expect(msg).toContain("Retrying the search without asking is a violation") + expect(hasSearchMarkerQuestion({ questions: [{ question: `${SEARCH_ASK_MARKER}: broader guidance?` }] })).toBe(true) + expect(hasSearchMarkerQuestion({ questions: [{ question: "unrelated" }] })).toBe(false) + expect(hasSearchMarkerQuestion({})).toBe(false) +}) + +test("gate wiring: first broad call denied with the marker ask; retry without asking denied; third attempt fail-opens", async () => { + const { call } = await boot() + const sid = "ses_srch_main1" + const broad = { pattern: "**/*.ts" } + await expect(call(sid, "glob", broad)).rejects.toThrow(SEARCH_ASK_MARKER) + await expect(call(sid, "glob", broad)).rejects.toThrow(SEARCH_ASK_MARKER) + await expect(call(sid, "glob", broad)).resolves.toBeUndefined() + expect(readStatusLog()).toContain("search clarify gate") +}) + +test("gate wiring: marker question completed → latch opens; a different session still gated", async () => { + const { call, questionDone } = await boot() + const sid = "ses_srch_main2" + const other = "ses_srch_other2" + await expect(call(sid, "glob", { pattern: "**/*.ts" })).rejects.toThrow(SEARCH_ASK_MARKER) + await questionDone(sid) + expect(readStatusLog()).toContain("scope ask completed") + await expect(call(sid, "glob", { pattern: "**/*.ts" })).resolves.toBeUndefined() + await expect(call(sid, "grep", { pattern: "TODO" })).resolves.toBeUndefined() // latch is per-session, all later broad searches pass + await expect(call(other, "grep", { pattern: "TODO" })).rejects.toThrow(SEARCH_ASK_MARKER) +}) + +test("gate wiring: scoped searches pass immediately; shell subagent sessions are exempt", async () => { + const { call, emit } = await boot() + const sid = "ses_srch_main3" + await expect(call(sid, "grep", { pattern: "TODO", path: "src" })).resolves.toBeUndefined() + await expect(call(sid, "glob", { pattern: "src/**/*.ts" })).resolves.toBeUndefined() + await expect(call(sid, "bash", { command: "rg foo src" })).resolves.toBeUndefined() + const shellSid = "ses_srch_shell3" + emit({ type: "session.created", properties: { info: { id: shellSid, agent: "glm-mx-53f-low", title: "T" } } }) + await expect(call(shellSid, "glob", { pattern: "**/*.ts" })).resolves.toBeUndefined() + await expect(call(shellSid, "bash", { command: "rg foo" })).resolves.toBeUndefined() +}) + +test("gate wiring: search.clarify:false disables the gate entirely", async () => { + const { call } = await boot({ search: { clarify: false } }) + await expect(call("ses_srch_off", "glob", { pattern: "**/*.ts" })).resolves.toBeUndefined() + await expect(call("ses_srch_off", "grep", { pattern: "TODO" })).resolves.toBeUndefined() +}) + +test("gate wiring: non-question tool completions never open the latch", async () => { + const { hooks, call } = await boot() + const sid = "ses_srch_main4" + await expect(call(sid, "glob", { pattern: "**/*.ts" })).rejects.toThrow(SEARCH_ASK_MARKER) + await hooks["tool.execute.after"]!({ sessionID: sid, tool: "question", callID: "q_unrelated", args: { questions: [{ question: "unrelated question" }] } } as any, + { output: "x" } as any) + await expect(call(sid, "glob", { pattern: "**/*.ts" })).rejects.toThrow(SEARCH_ASK_MARKER) +})