Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(marker): a capture-only marker no longer resets scope to default (#668)

AkitaOnRails407480a1f581
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b81f5198..ac3e6e8c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
duplicated in a harness-local store that other agents cannot see (#671).
### Fixed
+- A nested `.ai-memory.toml` marker whose only content is a `[capture]`
+ section (e.g. one that just sets `ignore_paths`) no longer resets scope
+ resolution to `default` / basename. The native binary, the POSIX shell
+ hooks, and the generated TypeScript integrations all used to resolve
+ `workspace`/`project` and the other forwarded root-level settings
+ (`project_strategy`, `drop_subagent_captures`, `[recall] default_global`,
+ `[briefing]` keys) from the single nearest marker — the same one that
+ decided `[capture]`/`ignore_paths` — so a capture-only marker in a
+ subdirectory silently shadowed an ancestor marker's declared
+ workspace/project and captures landed in the wrong scope. Scope and the
+ other forwarded settings now resolve from the nearest marker that
+ declares more than `[capture]`, while `[capture]`/`ignore_paths` keeps
+ reading the nearest marker unchanged — a marker that declares nothing
+ else is scope/settings-transparent. Applies to the native `ai-memory`
+ binary, the POSIX shell hooks (`hooks/_lib.sh`), and the generated
+ TypeScript integrations for every adapter that resolves scope client-side
+ (OpenCode, OpenCode2, pi, OMP, OpenClaw); outputs remain byte-identical
+ otherwise. (#668)
- Wiki auto-commits no longer re-hash the whole tree. Since the #594 guard,
every commit cleared the git index and re-read every page, so a session
end cost the size of the wiki and grew with it; the LongMemEval harness
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index 6af75470..3fb87181 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -11,7 +11,10 @@ use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::commands::path_util::home_dir;
-use crate::marker::{find_marker, is_truthy, parse_toml_flag, parse_toml_key, repo_root_project};
+use crate::marker::{
+ find_marker, find_settings_marker, is_truthy, parse_toml_flag, parse_toml_key,
+ repo_root_project,
+};
use ai_memory_hooks::capture_policy::MAX_MARKER_BYTES;
use ai_memory_hooks::{CaptureConfig, CapturePolicy, CaptureSource};
@@ -235,12 +238,15 @@ pub fn marker_query_suffix_without_briefing(cwd: &str, default_strategy: Option<
marker_query_suffix_impl(cwd, default_strategy, false)
}
-/// Whether the nearest marker explicitly enables the compiled project brief.
+/// Whether the nearest settings-declaring marker explicitly enables the
+/// compiled project brief (see [`find_settings_marker`]: a nested
+/// capture-only marker does not shadow an outer marker's `[briefing]`
+/// opt-in, #668).
///
/// Kimi Code uses this before creating its local once-per-session marker so
/// repositories that did not opt in do not accumulate marker files.
pub fn marker_requests_briefing(cwd: &str) -> bool {
- find_marker(cwd)
+ find_settings_marker(cwd)
.and_then(|marker| parse_toml_flag(&marker, "inject_on_session_start"))
.is_some_and(|value| is_truthy(&value))
}
@@ -254,7 +260,10 @@ fn marker_query_suffix_impl(
let (mut workspace, mut project, mut strategy, mut drop_subagent, mut default_global) =
(None, None, None, None, None);
let (mut briefing, mut briefing_budget) = (None, None);
- if let Some(marker) = find_marker(cwd) {
+ // The nearest marker that declares more than `[capture]` (#668): a
+ // nested capture-only marker (e.g. one that only sets `ignore_paths`)
+ // must not shadow an outer marker's workspace/project/briefing/etc.
+ if let Some(marker) = find_settings_marker(cwd) {
workspace = parse_toml_key(&marker, "workspace");
project = parse_toml_key(&marker, "project");
strategy = parse_toml_key(&marker, "project_strategy");
@@ -1036,6 +1045,77 @@ drop_subagent_captures = "true"
// `project_src` must faithfully separate the two ways a `project` override
// is produced — that distinction is the whole basis for `[routing]
// mid_session = "sticky"` honoring markers while overruling derivation.
+ /// A nested capture-only marker (only `[capture]`) must not shadow an
+ /// outer marker's `workspace`/`project` — `marker_query_suffix` forwards
+ /// those from the OUTER marker — while `capture_policy` for the SAME cwd
+ /// still resolves the INNER (nearest) marker's `ignore_paths`: scope and
+ /// capture deliberately read different markers (#668).
+ #[test]
+ fn marker_query_suffix_skips_nested_capture_only_marker_for_scope() {
+ use ai_memory_core::AgentKind;
+ use ai_memory_hooks::CaptureDisposition;
+
+ let tmp = tempfile::TempDir::new().unwrap();
+ // A `.git` dir makes tmp.path() the checkout boundary the walk-up
+ // stops at, so it is actually consulted (a plain non-git directory
+ // outside $HOME only checks its exact cwd — see `checkout_root`).
+ std::fs::create_dir_all(tmp.path().join(".git")).unwrap();
+ std::fs::write(
+ tmp.path().join(".ai-memory.toml"),
+ "workspace = \"acme\"\nproject = \"infra\"\n",
+ )
+ .unwrap();
+ let inner = tmp.path().join("sub");
+ std::fs::create_dir_all(&inner).unwrap();
+ std::fs::write(
+ inner.join(".ai-memory.toml"),
+ "[capture]\nignore_paths = [\"secret/**\"]\n",
+ )
+ .unwrap();
+ let inner_str = inner.to_str().unwrap();
+
+ let qs = marker_query_suffix(inner_str, None);
+ assert!(qs.contains("&workspace=acme"), "{qs}");
+ assert!(qs.contains("&project=infra"), "{qs}");
+
+ // Same cwd: capture policy still comes from the INNER (nearest)
+ // marker, so its `ignore_paths` still applies.
+ let policy = capture_policy(inner_str);
+ let raw = serde_json::json!({
+ "hook_event_name": "PostToolUse",
+ "tool_name": "Edit",
+ "tool_input": {"file_path": format!("{inner_str}/secret/token.txt")},
+ "session_id": "s",
+ "cwd": inner_str,
+ });
+ let decision = policy.inspect(AgentKind::ClaudeCode, &raw, inner_str);
+ assert_eq!(decision.protocol().disposition(), CaptureDisposition::Drop);
+ }
+
+ /// The predicate is conservative: a marker declaring `[capture]` PLUS a
+ /// scope key is a settings boundary, not capture-only, so its own
+ /// `project` wins rather than an outer marker's.
+ #[test]
+ fn marker_query_suffix_capture_plus_project_is_a_boundary() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ std::fs::write(
+ tmp.path().join(".ai-memory.toml"),
+ "workspace = \"acme\"\nproject = \"infra\"\n",
+ )
+ .unwrap();
+ let inner = tmp.path().join("sub");
+ std::fs::create_dir_all(&inner).unwrap();
+ std::fs::write(
+ inner.join(".ai-memory.toml"),
+ "project = \"x\"\n[capture]\nignore_paths = [\"secret/**\"]\n",
+ )
+ .unwrap();
+
+ let qs = marker_query_suffix(inner.to_str().unwrap(), None);
+ assert!(qs.contains("&project=x"), "{qs}");
+ assert!(!qs.contains("&workspace=acme"), "{qs}");
+ }
+
#[test]
fn marker_query_suffix_tags_project_provenance() {
let tmp = tempfile::TempDir::new().unwrap();
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 6e243aab..e9648a63 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -3088,6 +3088,60 @@ const AiMemoryOpencode2: Plugin = {
export default AiMemoryOpencode2;
"#;
+/// `findSettingsMarker` mirrors the native `find_settings_marker` (`marker.rs`)
+/// and the shell `ai_memory_find_settings_marker` (`hooks/_lib.sh`), #668:
+/// the same ancestor walk and HOME/`.git` boundary as `findMarker`, but a
+/// marker that declares nothing beyond `[capture]` is transparent — the walk
+/// skips it and continues to the next ancestor. That keeps a nested
+/// capture-only marker (e.g. one that only sets `ignore_paths`) from
+/// shadowing an outer marker's `workspace`/`project`/etc, without changing
+/// `[capture]`/`ignore_paths` resolution itself (that stays on `findMarker`,
+/// the nearest marker, in the separate capture-policy template). The
+/// boundary walk is duplicated from `findMarker` rather than shared, on
+/// purpose: `findMarker` stays untouched, well-exercised, nearest-marker
+/// behavior for every other caller.
+pub(crate) const TS_FIND_SETTINGS_MARKER: &str = r#"function declaresSettings(text: string): boolean {
+ for (const key of ["workspace", "project", "project_strategy", "drop_subagent_captures"]) {
+ if (tomlKey(text, key) !== undefined) return true;
+ }
+ for (const key of ["default_global", "inject_on_session_start", "max_chars"]) {
+ if (tomlFlag(text, key) !== undefined) return true;
+ }
+ return false;
+}
+
+function findSettingsMarker(cwd: string | undefined): string | undefined {
+ if (!cwd) return undefined;
+ let dir = resolve(cwd);
+ const home = homedir();
+ let boundary: string | undefined;
+ if (home && (dir === home || dir.startsWith(home.endsWith(sep) ? home : home + sep))) {
+ boundary = home;
+ } else if (home) {
+ let probe = dir;
+ while (probe && probe !== dirname(probe)) {
+ if (existsSync(join(probe, ".git"))) {
+ boundary = probe;
+ break;
+ }
+ probe = dirname(probe);
+ }
+ boundary ??= dir;
+ }
+ while (dir && dir !== dirname(dir)) {
+ const marker = join(dir, ".ai-memory.toml");
+ if (existsSync(marker)) {
+ try {
+ if (declaresSettings(readFileSync(marker, "utf8"))) return marker;
+ } catch (_e) {
+ }
+ }
+ if (boundary && dir === boundary) return undefined;
+ dir = dirname(dir);
+ }
+ return undefined;
+}"#;
+
/// Emit the `applyMarkerParams` TypeScript function shared verbatim by the
/// OpenCode plugin and the OMP extension.
///
@@ -3097,14 +3151,18 @@ export default AiMemoryOpencode2;
/// that install-time default when no marker pins a `project_strategy` (#128).
/// A marker's own `project` / `project_strategy` still take precedence (§3.3),
/// and repo-root is resolved host-side via `repoRootProject`.
+///
+/// Scope/settings resolution walks past a capture-only marker to the nearest
+/// ancestor marker that declares a setting (#668) via `findSettingsMarker`,
+/// emitted alongside this function.
fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
let Some(default) = default_strategy else {
return format!(
- "{TS_TOML_FLAG}\n{}",
+ "{TS_TOML_FLAG}\n{TS_FIND_SETTINGS_MARKER}\n{}",
r#"function applyMarkerParams(url: URL, cwd: string | undefined): void {
const managedRun = process.env.AI_MEMORY_RUN_ID;
if (managedRun) url.searchParams.set("managed_run", managedRun);
- const marker = findMarker(cwd);
+ const marker = findSettingsMarker(cwd);
if (!marker || !cwd) return;
url.searchParams.set("cwd", cwd);
try {
@@ -3144,7 +3202,7 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
let defaultGlobal: string | undefined;
let briefing: string | undefined;
let briefingBudget: string | undefined;
- const marker = findMarker(cwd);
+ const marker = findSettingsMarker(cwd);
if (marker) {
try {
const body = readFileSync(marker, "utf8");
@@ -3172,7 +3230,7 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
if (briefingBudget) url.searchParams.set("briefing_budget", briefingBudget);
}"#;
format!(
- "const DEFAULT_PROJECT_STRATEGY = {};\n{TS_TOML_FLAG}\n{body}",
+ "const DEFAULT_PROJECT_STRATEGY = {};\n{TS_TOML_FLAG}\n{TS_FIND_SETTINGS_MARKER}\n{body}",
ts_string_literal(default)
)
}
@@ -7932,6 +7990,21 @@ model = "gpt-5"
assert!(plugin.contains("tomlFlag(body, \"default_global\")"));
assert!(plugin.contains("tomlFlag(body, \"inject_on_session_start\")"));
assert!(plugin.contains("url.searchParams.set(\"briefing_budget\", briefingBudget)"));
+ // #668: applyMarkerParams resolves scope/settings via the
+ // settings-walk, not the nearest-marker findMarker, so a nested
+ // capture-only marker does not shadow an outer marker's scope.
+ assert!(plugin.contains("function findSettingsMarker"));
+ assert!(plugin.contains("function declaresSettings"));
+ assert!(plugin.contains("const marker = findSettingsMarker(cwd);"));
+ assert!(plugin.contains(
+ "for (const key of [\"workspace\", \"project\", \"project_strategy\", \"drop_subagent_captures\"])"
+ ));
+ assert!(plugin.contains(
+ "for (const key of [\"default_global\", \"inject_on_session_start\", \"max_chars\"])"
+ ));
+ assert!(
+ plugin.contains("if (declaresSettings(readFileSync(marker, \"utf8\"))) return marker;")
+ );
assert!(plugin.contains(
"applyMarkerParams(url, typeof payload.cwd === \"string\" ? payload.cwd : undefined);"
));
@@ -8138,6 +8211,10 @@ model = "gpt-5"
plugin.contains("if (repoProject) project = repoProject;"),
"{plugin}"
);
+ assert!(
+ plugin.contains("const marker = findSettingsMarker(cwd);"),
+ "the default-strategy variant must also walk past a capture-only marker (#668): {plugin}"
+ );
}
#[test]
@@ -8255,6 +8332,16 @@ model = "gpt-5"
assert!(extension.contains("tomlFlag(body, \"default_global\")"));
assert!(extension.contains("tomlFlag(body, \"inject_on_session_start\")"));
assert!(extension.contains("url.searchParams.set(\"briefing_budget\", briefingBudget)"));
+ // #668: same settings-walk as the OpenCode plugin (shared
+ // `ts_apply_marker_params`), so a nested capture-only marker does
+ // not shadow an outer marker's scope for the OMP/pi extensions.
+ assert!(extension.contains("function findSettingsMarker"));
+ assert!(extension.contains("function declaresSettings"));
+ assert!(extension.contains("const marker = findSettingsMarker(cwd);"));
+ assert!(
+ extension
+ .contains("if (declaresSettings(readFileSync(marker, \"utf8\"))) return marker;")
+ );
assert!(extension.contains(
"applyMarkerParams(url, typeof payload.cwd === \"string\" ? payload.cwd : undefined);"
));
@@ -8293,6 +8380,10 @@ model = "gpt-5"
extension.contains("if (!projectStrategy) projectStrategy = DEFAULT_PROJECT_STRATEGY;"),
"{extension}"
);
+ assert!(
+ extension.contains("const marker = findSettingsMarker(cwd);"),
+ "the default-strategy variant must also walk past a capture-only marker (#668): {extension}"
+ );
}
#[test]
diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
index b6ed989c..8401c994 100644
--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
@@ -215,15 +215,21 @@ pub(crate) fn manifest_json() -> String {
/// default when no marker pins a `project_strategy` (#128); a marker's own
/// `project` / `project_strategy` still win (§3.3). Mirrors the opencode/omp
/// `ts_apply_marker_params` in `install_hooks.rs`.
+///
+/// Scope/settings resolution walks past a capture-only marker to the nearest
+/// ancestor marker that declares a setting (#668) via `findSettingsMarker`
+/// (`TS_FIND_SETTINGS_MARKER`, shared with `ts_apply_marker_params` so both
+/// copies stay equivalent).
fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {
let toml_flag = super::install_hooks::TS_TOML_FLAG;
+ let find_settings_marker = super::install_hooks::TS_FIND_SETTINGS_MARKER;
let Some(default) = default_strategy else {
return format!(
- "{toml_flag}\n{}",
+ "{toml_flag}\n{find_settings_marker}\n{}",
r#"function applyMarkerParams(url: URL, cwd: string | undefined): void {
if (!cwd) return;
url.searchParams.set("cwd", cwd);
- const marker = findMarker(cwd);
+ const marker = findSettingsMarker(cwd);
if (!marker) return;
try {
const body = readFileSync(marker, "utf8");
@@ -266,7 +272,7 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {
let defaultGlobal: string | undefined;
let briefing: string | undefined;
let briefingBudget: string | undefined;
- const marker = findMarker(cwd);
+ const marker = findSettingsMarker(cwd);
if (marker) {
try {
const body = readFileSync(marker, "utf8");
@@ -301,7 +307,7 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {
if (briefingBudget) url.searchParams.set("briefing_budget", briefingBudget);
}"#;
format!(
- "const DEFAULT_PROJECT_STRATEGY = {};\n{toml_flag}\n{body}",
+ "const DEFAULT_PROJECT_STRATEGY = {};\n{toml_flag}\n{find_settings_marker}\n{body}",
ts_string_literal(default)
)
}
@@ -636,6 +642,16 @@ mod tests {
assert!(plugin.contains("tomlFlag(body, \"default_global\")"));
assert!(plugin.contains("tomlFlag(body, \"inject_on_session_start\")"));
assert!(plugin.contains("url.searchParams.set(\"briefing_budget\", briefingBudget)"));
+ // #668: same settings-walk as the shared ts_apply_marker_params
+ // (install_hooks.rs) — the two applyMarkerParams copies stay
+ // equivalent, so a nested capture-only marker does not shadow an
+ // outer marker's scope here either.
+ assert!(plugin.contains("function findSettingsMarker"));
+ assert!(plugin.contains("function declaresSettings"));
+ assert!(plugin.contains("const marker = findSettingsMarker(cwd);"));
+ assert!(
+ plugin.contains("if (declaresSettings(readFileSync(marker, \"utf8\"))) return marker;")
+ );
assert!(plugin.contains("import { execFileSync } from \"node:child_process\";"));
assert!(
plugin.contains("import { basename, dirname, join, resolve, sep } from \"node:path\";")
@@ -686,6 +702,10 @@ mod tests {
plugin.contains("if (!projectStrategy) projectStrategy = DEFAULT_PROJECT_STRATEGY;"),
"must apply the default when a marker pins no strategy: {plugin}"
);
+ assert!(
+ plugin.contains("const marker = findSettingsMarker(cwd);"),
+ "the default-strategy variant must also walk past a capture-only marker (#668): {plugin}"
+ );
}
#[test]
diff --git a/crates/ai-memory-cli/src/marker.rs b/crates/ai-memory-cli/src/marker.rs
index be626fab..feb04b1b 100644
--- a/crates/ai-memory-cli/src/marker.rs
+++ b/crates/ai-memory-cli/src/marker.rs
@@ -14,7 +14,7 @@
//! splitting one checkout across two scopes.
//!
//! Parsing is deliberately line-based (`parse_toml_key` / `parse_toml_flag`)
-//! and mirrors `hooks/lib/_lib.sh`, so the native binary and the POSIX shell
+//! and mirrors `hooks/_lib.sh`, so the native binary and the POSIX shell
//! hooks agree on what a marker means. `[capture]` is the one section parsed
//! strictly, with a real TOML parser, and stays in `hook_capture`.
@@ -72,7 +72,7 @@ pub(crate) fn read_scope(cwd: &str, env: &RuntimeEnv) -> Option<MarkerScope> {
if env.ignore_marker() {
return None;
}
- let path = find_marker_with_home(cwd, env.home_dir().map(Path::new))?;
+ let path = find_settings_marker_with_home(cwd, env.home_dir().map(Path::new))?;
// One read, three keys: the marker is re-read per key nowhere else on a
// hot path, but this one runs on every client command.
let text = std::fs::read_to_string(&path).ok()?;
@@ -113,6 +113,37 @@ pub(crate) fn find_marker(cwd: &str) -> Option<PathBuf> {
}
fn find_marker_with_home(cwd: &str, home: Option<&Path>) -> Option<PathBuf> {
+ find_marker_matching(cwd, home, |_| true)
+}
+
+/// Like [`find_marker`], but skips a marker that declares nothing beyond a
+/// `[capture]` section (scope/settings-*transparent*) and continues the walk
+/// to the next ancestor. Resolves `workspace`/`project`/`project_strategy`
+/// and the other root-level settings `hook_capture` forwards, so a nested
+/// capture-only marker no longer resets them to their fallback (#668).
+/// `[capture]`/`ignore_paths` itself keeps using [`find_marker`] — the
+/// nearest marker, unchanged.
+pub(crate) fn find_settings_marker(cwd: &str) -> Option<PathBuf> {
+ let home = home_dir();
+ find_settings_marker_with_home(cwd, home.as_deref())
+}
+
+fn find_settings_marker_with_home(cwd: &str, home: Option<&Path>) -> Option<PathBuf> {
+ find_marker_matching(cwd, home, |path| {
+ std::fs::read_to_string(path).is_ok_and(|text| declares_more_than_capture(&text))
+ })
+}
+
+/// Shared walk-up-from-`cwd`-toward-`$HOME` used by [`find_marker_with_home`]
+/// and [`find_settings_marker_with_home`]; `matches` decides whether a marker
+/// file found along the way stops the walk (returned) or is skipped in favor
+/// of the next ancestor. The HOME/checkout-root boundary is identical either
+/// way — only which markers count as a stopping point differs.
+fn find_marker_matching(
+ cwd: &str,
+ home: Option<&Path>,
+ matches: impl Fn(&Path) -> bool,
+) -> Option<PathBuf> {
let start = absolute_normalized(Path::new(cwd));
let home = home.map(absolute_normalized);
let boundary = match home.as_deref() {
@@ -124,7 +155,7 @@ fn find_marker_with_home(cwd: &str, home: Option<&Path>) -> Option<PathBuf> {
let mut dir = start.as_path();
loop {
let candidate = dir.join(".ai-memory.toml");
- if candidate.is_file() {
+ if candidate.is_file() && matches(&candidate) {
return Some(candidate);
}
if boundary.as_deref() == Some(dir) {
@@ -137,6 +168,34 @@ fn find_marker_with_home(cwd: &str, home: Option<&Path>) -> Option<PathBuf> {
}
}
+/// Whether a marker's raw text declares anything beyond a `[capture]`
+/// section: any root-level scope key (`workspace`/`project`/
+/// `project_strategy`), or any of the other settings
+/// `hook_capture::marker_query_suffix_impl` forwards (`[recall]
+/// default_global`, `[briefing]` keys, top-level `drop_subagent_captures`).
+/// A marker with any of these is a resolution boundary; only a marker whose
+/// only content is `[capture]` (e.g. `ignore_paths`) is transparent (#668).
+///
+/// Line-based like [`parse_key_in`] / [`parse_toml_flag`] — section headers
+/// are not tracked, so a stray key is still detected wherever it appears in
+/// the file. That is conservative on purpose: it can only turn a marker INTO
+/// a boundary, never wrongly make one transparent.
+fn declares_more_than_capture(text: &str) -> bool {
+ const QUOTED_KEYS: [&str; 4] = [
+ "workspace",
+ "project",
+ "project_strategy",
+ "drop_subagent_captures",
+ ];
+ const FLAG_KEYS: [&str; 3] = ["default_global", "inject_on_session_start", "max_chars"];
+ QUOTED_KEYS
+ .iter()
+ .any(|key| parse_key_in(text, key).is_some())
+ || FLAG_KEYS
+ .iter()
+ .any(|key| parse_flag_in(text, key).is_some())
+}
+
fn absolute_normalized(path: &Path) -> PathBuf {
path.canonicalize().unwrap_or_else(|_| {
if path.is_absolute() {
@@ -196,7 +255,13 @@ fn parse_key_in(text: &str, key: &str) -> Option<String> {
/// quotes the value. Line-based like [`parse_toml_key`], so section headers
/// are ignored; strips an optional trailing `# comment`.
pub(crate) fn parse_toml_flag(file: &Path, key: &str) -> Option<String> {
- let text = std::fs::read_to_string(file).ok()?;
+ parse_flag_in(&std::fs::read_to_string(file).ok()?, key)
+}
+
+/// [`parse_toml_flag`] over already-read marker text — the counterpart to
+/// [`parse_key_in`], shared with [`declares_more_than_capture`] so it pays
+/// for one read per key instead of re-opening the file.
+fn parse_flag_in(text: &str, key: &str) -> Option<String> {
for line in text.lines() {
let trimmed = line.trim_start();
let Some(after_key) = trimmed.strip_prefix(key) else {
@@ -407,4 +472,84 @@ project = "infra" # this is fine
"a marker with only [capture] rules must not change scope"
);
}
+
+ // ── #668: a capture-only marker is scope/settings-transparent ────────
+
+ /// A nested marker whose only content is `[capture]` must not shadow an
+ /// outer ancestor's declared scope: `read_scope` walks past it and
+ /// returns the OUTER marker's workspace/project.
+ #[test]
+ fn read_scope_skips_a_nested_capture_only_marker() {
+ let tmp = TempDir::new().unwrap();
+ let outer_marker = write_marker(tmp.path(), "workspace = \"acme\"\nproject = \"infra\"\n");
+ let inner = tmp.path().join("sub");
+ fs::create_dir_all(&inner).unwrap();
+ write_marker(&inner, "[capture]\nignore_paths = [\"secret/**\"]\n");
+
+ let scope = read_scope(inner.to_str().unwrap(), &RuntimeEnv::default())
+ .expect("the outer marker still declares scope");
+ assert_eq!(scope.workspace.as_deref(), Some("acme"));
+ assert_eq!(scope.project.as_deref(), Some("infra"));
+ assert_eq!(scope.path, outer_marker.canonicalize().unwrap());
+ }
+
+ /// When every marker in the ancestor chain is capture-only (or none
+ /// exist), behavior is unchanged from before #668: `read_scope` returns
+ /// `None` so the caller falls back to `DEFAULT_WORKSPACE` + repo-root.
+ #[test]
+ fn read_scope_still_none_when_only_capture_only_markers_exist() {
+ let tmp = TempDir::new().unwrap();
+ write_marker(tmp.path(), "[capture]\nignore_paths = [\"secret/**\"]\n");
+ let inner = tmp.path().join("sub");
+ fs::create_dir_all(&inner).unwrap();
+ write_marker(&inner, "[capture]\nignore_paths = [\"other/**\"]\n");
+
+ assert_eq!(
+ read_scope(inner.to_str().unwrap(), &RuntimeEnv::default()),
+ None
+ );
+ }
+
+ /// A marker that declares `[briefing]` but no `workspace`/`project` is
+ /// NOT capture-only — it declares a forwarded setting, so it is a
+ /// resolution boundary. `read_scope` must not walk past it to an outer
+ /// marker's scope, even though that marker declares one: behavior for
+ /// this shape is exactly what it was before #668.
+ #[test]
+ fn read_scope_treats_a_briefing_only_marker_as_a_settings_boundary() {
+ let tmp = TempDir::new().unwrap();
+ write_marker(tmp.path(), "workspace = \"acme\"\nproject = \"infra\"\n");
+ let inner = tmp.path().join("sub");
+ fs::create_dir_all(&inner).unwrap();
+ write_marker(&inner, "[briefing]\ninject_on_session_start = true\n");
+
+ assert_eq!(
+ read_scope(inner.to_str().unwrap(), &RuntimeEnv::default()),
+ None,
+ "a briefing-only marker is a settings boundary: it stops the walk \
+ but declares no scope of its own"
+ );
+ }
+
+ #[test]
+ fn declares_more_than_capture_is_conservative() {
+ assert!(!declares_more_than_capture(
+ "[capture]\nignore_paths = [\"a/**\"]\n"
+ ));
+ assert!(!declares_more_than_capture(""));
+ for text in [
+ "workspace = \"acme\"\n",
+ "project = \"infra\"\n",
+ "project_strategy = \"repo-root\"\n",
+ "drop_subagent_captures = \"true\"\n",
+ "[recall]\ndefault_global = true\n",
+ "[briefing]\ninject_on_session_start = true\n",
+ "[briefing]\nmax_chars = 4000\n",
+ ] {
+ assert!(
+ declares_more_than_capture(text),
+ "{text} should be a settings boundary"
+ );
+ }
+ }
}
diff --git a/docs/marker-file.md b/docs/marker-file.md
index 2a72f5f3..f07c833f 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -40,6 +40,17 @@ hook scripts also forward the current `cwd` so
workspace-only markers can still resolve `project = basename(cwd)` for
handoff lookups.
+A marker whose only content is a `[capture]` section (see
+[Capture exclusions](#capture-exclusions) below) is **transparent** to this
+walk: `workspace`, `project`, `project_strategy`, and the other forwarded
+settings (`drop_subagent_captures`, `[recall] default_global`, `[briefing]`
+keys) are resolved from the nearest ancestor marker that declares at least
+one of them, skipping past any nearer marker that declares nothing but
+`[capture]`. A subdirectory marker added only to exclude some paths from
+capture therefore no longer resets scope to `default` / basename for that
+subtree. `[capture]`/`ignore_paths` itself is unaffected by this and always
+comes from the nearest marker, even a capture-only one.
+
The marker path is shared by the POSIX/PowerShell hook scripts and the
generated OpenCode / OMP / Pi / OpenClaw TypeScript integrations. In all cases,
hook capture and handoff lookup send the same `cwd`, `workspace`, `project`,
diff --git a/hooks/_lib.sh b/hooks/_lib.sh
index 16726a55..768a4bd3 100644
--- a/hooks/_lib.sh
+++ b/hooks/_lib.sh
@@ -70,6 +70,71 @@ ai_memory_parse_toml_flag() {
"$file" | head -n 1 | sed 's/[[:space:]]*$//'
}
+# Whether "$1" (a marker file) declares anything beyond a `[capture]`
+# section: any root-level scope key (workspace/project/project_strategy), or
+# any of the other settings ai_memory_marker_qs / ai_memory_briefing_qs
+# forward (drop_subagent_captures, default_global, [briefing] keys). Mirrors
+# `declares_more_than_capture` in marker.rs. A marker with any of these is a
+# resolution boundary; only a marker whose only content is `[capture]` (e.g.
+# ignore_paths) is scope/settings-transparent (#668).
+ai_memory_marker_declares_settings() {
+ file="$1"
+ [ -f "$file" ] || return 1
+ for key in workspace project project_strategy drop_subagent_captures; do
+ [ -n "$(ai_memory_parse_toml_key "$file" "$key")" ] && return 0
+ done
+ for key in default_global inject_on_session_start max_chars; do
+ [ -n "$(ai_memory_parse_toml_flag "$file" "$key")" ] && return 0
+ done
+ return 1
+}
+
+# Like ai_memory_find_marker, but skips a marker that declares nothing beyond
+# `[capture]` (see ai_memory_marker_declares_settings) and continues the walk
+# to the next ancestor. Resolves workspace/project/project_strategy and the
+# other root-level settings ai_memory_marker_qs / ai_memory_briefing_qs
+# forward, so a nested capture-only marker no longer resets them to their
+# fallback (#668). [capture]/ignore_paths itself keeps using
+# ai_memory_find_marker (the nearest marker, unchanged). Boundary logic is
+# duplicated rather than shared with ai_memory_find_marker on purpose: this
+# file is sourced by every supported agent's hook scripts, so the existing,
+# well-exercised walk stays untouched.
+ai_memory_find_settings_marker() {
+ dir="$1"
+ [ -z "$dir" ] && return 0
+ boundary=""
+ if [ -n "${HOME:-}" ]; then
+ case "$dir" in
+ "$HOME"|"$HOME"/*) boundary="$HOME" ;;
+ *)
+ probe="$dir"
+ while [ -n "$probe" ] && [ "$probe" != "/" ]; do
+ if [ -e "$probe/.git" ]; then
+ boundary="$probe"
+ break
+ fi
+ parent=$(dirname "$probe")
+ [ "$parent" = "$probe" ] && break
+ probe="$parent"
+ done
+ [ -n "$boundary" ] || boundary="$dir"
+ ;;
+ esac
+ fi
+ while [ -n "$dir" ] && [ "$dir" != "/" ]; do
+ if [ -f "$dir/.ai-memory.toml" ] && ai_memory_marker_declares_settings "$dir/.ai-memory.toml"; then
+ printf '%s\n' "$dir/.ai-memory.toml"
+ return 0
+ fi
+ if [ -n "$boundary" ] && [ "$dir" = "$boundary" ]; then
+ return 0
+ fi
+ parent=$(dirname "$dir")
+ [ "$parent" = "$dir" ] && return 0
+ dir="$parent"
+ done
+}
+
# Extract the first cwd-like path from a JSON payload on stdin or in $1.
# Returns the value or nothing. This is intentionally a tiny shell fallback,
# not a JSON parser; taking the first match preserves the top-level cwd when
@@ -235,7 +300,10 @@ ai_memory_marker_qs() {
# deliberate marker rescope from a host-derived repo-root name. Only the
# latter may yield to session-sticky attribution (#394).
ps=""
- marker=$(ai_memory_find_marker "$cwd")
+ # The nearest marker that declares more than `[capture]` (#668): a nested
+ # capture-only marker (e.g. one that only sets ignore_paths) must not
+ # shadow an outer marker's workspace/project/etc.
+ marker=$(ai_memory_find_settings_marker "$cwd")
if [ -n "$marker" ]; then
ws=$(ai_memory_parse_toml_key "$marker" workspace)
pr=$(ai_memory_parse_toml_key "$marker" project)
@@ -285,7 +353,9 @@ ai_memory_marker_qs() {
ai_memory_briefing_qs() {
cwd="$1"
[ -z "$cwd" ] && return 0
- marker=$(ai_memory_find_marker "$cwd")
+ # Settings walk (#668): a nested capture-only marker must not shadow an
+ # outer marker's [briefing] opt-in.
+ marker=$(ai_memory_find_settings_marker "$cwd")
[ -n "$marker" ] || return 0
qs=""
briefing=$(ai_memory_parse_toml_flag "$marker" inject_on_session_start)
diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.sh
index 09f96258..3ab8cd55 100755
--- a/tests/hooks/test_lib.sh
+++ b/tests/hooks/test_lib.sh
@@ -180,6 +180,45 @@ assert_eq "closer marker wins" "&cwd=$(ai_memory_url_encode "$TMP/a/b/c")&worksp
QS3=$(ai_memory_marker_qs "$TMP/nonexistent")
assert_eq "no marker -> cwd only" "&cwd=$(ai_memory_url_encode "$TMP/nonexistent")" "$QS3"
+# --- capture-only marker transparency (#668) ---------------------------
+# A nested marker whose only content is [capture] must not shadow an outer
+# marker's workspace/project: ai_memory_marker_qs skips it and forwards the
+# OUTER marker's fields, while ai_memory_find_marker (used for [capture]
+# itself) still resolves the INNER (nearest) marker.
+mkdir -p "$TMP/scope/inner"
+printf 'workspace = "acme"\nproject = "infra"\n' >"$TMP/scope/.ai-memory.toml"
+printf '[capture]\nignore_paths = ["secret/**"]\n' >"$TMP/scope/inner/.ai-memory.toml"
+
+assert_eq "capture-only marker: find_marker still resolves nearest" \
+ "$TMP/scope/inner/.ai-memory.toml" \
+ "$(ai_memory_find_marker "$TMP/scope/inner")"
+assert_eq "capture-only marker: find_settings_marker skips it for the outer" \
+ "$TMP/scope/.ai-memory.toml" \
+ "$(ai_memory_find_settings_marker "$TMP/scope/inner")"
+assert_eq "capture-only marker: marker_qs forwards the OUTER scope" \
+ "&cwd=$(ai_memory_url_encode "$TMP/scope/inner")&workspace=acme&project=infra&project_src=marker" \
+ "$(ai_memory_marker_qs "$TMP/scope/inner")"
+
+# A marker declaring [briefing] but no workspace/project is NOT capture-only
+# (it declares a forwarded setting), so it stays a resolution boundary: the
+# outer marker's scope must not leak through it.
+printf '[briefing]\ninject_on_session_start = true\n' >"$TMP/scope/inner/.ai-memory.toml"
+assert_eq "briefing-only marker is a settings boundary, not transparent" \
+ "" "$(ai_memory_parse_toml_key "$(ai_memory_find_settings_marker "$TMP/scope/inner")" workspace)"
+assert_eq "marker_qs stops at the briefing-only boundary" \
+ "&cwd=$(ai_memory_url_encode "$TMP/scope/inner")" \
+ "$(ai_memory_marker_qs "$TMP/scope/inner")"
+
+# A capture-only marker with no scope-declaring ancestor: still transparent,
+# and resolution falls back exactly as it does with no marker at all.
+mkdir -p "$TMP/no-outer-scope/inner"
+printf '[capture]\nignore_paths = ["a/**"]\n' >"$TMP/no-outer-scope/inner/.ai-memory.toml"
+assert_eq "capture-only marker with no ancestor scope: settings walk finds none" \
+ "" "$(ai_memory_find_settings_marker "$TMP/no-outer-scope/inner")"
+assert_eq "capture-only marker with no ancestor scope: marker_qs is cwd-only" \
+ "&cwd=$(ai_memory_url_encode "$TMP/no-outer-scope/inner")" \
+ "$(ai_memory_marker_qs "$TMP/no-outer-scope/inner")"
+
# --- repo-root strategy: host-side resolution -------------------------
# Outside any git repo the helper stays silent (caller keeps basename(cwd)).
assert_eq "repo_root_project on non-git path is empty" "" \