Skip to content

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

Rust

feat(routing): opt-in sticky mid-session attribution (#394)

AkitaOnRails36b92543cdfd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 54f8b870..0be83a49 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Added `[routing] mid_session` to choose how a mid-session event is attributed
+ once the agent's cwd has moved. `follow-cwd` (default) keeps the historical
+ per-event resolution; `sticky` keeps the session's project wherever the agent
+ wanders, closing the cross-repo `cd` case that split one session's raw record
+ across two projects. Lifecycle hooks now tag each `project` override with its
+ provenance (`project_src=marker` or `project_src=repo-root`), so `sticky`
+ overrules a host-derived repo name while a `.ai-memory.toml` marker still
+ wins in both modes. Clients older than this release send no provenance and
+ keep their overrides authoritative (#394).
- Added `[auth].secure_cookie` for HTTPS reverse-proxy deployments to mark
`/web` browser authentication cookies `Secure` while preserving plain-HTTP
loopback compatibility by default (#396).
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index 86a7562e..e497bf49 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -258,11 +258,16 @@ fn marker_query_suffix_impl(
briefing = parse_toml_flag(&marker, "inject_on_session_start");
briefing_budget = parse_toml_flag(&marker, "max_chars");
}
+ // Provenance of `project`, forwarded as `project_src` so the server can
+ // tell a deliberate marker rescope from a host-derived repo-root name.
+ // Only the latter may yield to session-sticky attribution (#394).
+ let mut project_src = project.as_ref().map(|_| "marker");
if strategy.is_none() {
strategy = default_strategy.map(str::to_owned);
}
if project.is_none() && matches!(strategy.as_deref(), Some("repo-root" | "repo_root")) {
project = repo_root_project(cwd);
+ project_src = project.as_ref().map(|_| "repo-root");
}
if let Some(val) = workspace {
qs.push_str(&format!("&workspace={}", url_encode(&val)));
@@ -270,6 +275,9 @@ fn marker_query_suffix_impl(
if let Some(val) = project {
qs.push_str(&format!("&project={}", url_encode(&val)));
}
+ if let Some(val) = project_src {
+ qs.push_str(&format!("&project_src={val}"));
+ }
if let Some(val) = strategy {
qs.push_str(&format!("&project_strategy={}", url_encode(&val)));
}
@@ -943,6 +951,37 @@ drop_subagent_captures = "true"
let qs = marker_query_suffix(sub.to_str().unwrap(), Some("repo-root"));
assert!(qs.contains("&project=contentcreator"), "{qs}");
assert!(qs.contains("&project_strategy=repo-root"), "{qs}");
+ // Host-derived, so the server may let a session overrule it (#394).
+ assert!(qs.contains("&project_src=repo-root"), "{qs}");
+ }
+
+ // `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.
+ #[test]
+ fn marker_query_suffix_tags_project_provenance() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let dir = tmp.path().join("workdir");
+ std::fs::create_dir_all(&dir).unwrap();
+
+ // No override at all: nothing to describe.
+ let qs = marker_query_suffix(dir.to_str().unwrap(), None);
+ assert!(!qs.contains("&project="), "{qs}");
+ assert!(!qs.contains("&project_src="), "{qs}");
+
+ // Marker-declared project: a deliberate rescope.
+ std::fs::write(dir.join(".ai-memory.toml"), "project = \"pinned\"\n").unwrap();
+ let qs = marker_query_suffix(dir.to_str().unwrap(), None);
+ assert!(qs.contains("&project=pinned"), "{qs}");
+ assert!(qs.contains("&project_src=marker"), "{qs}");
+
+ // A marker project wins over the baked repo-root default, and keeps
+ // reporting `marker` — the provenance must follow the value that
+ // actually shipped, not the strategy that was configured.
+ let qs = marker_query_suffix(dir.to_str().unwrap(), Some("repo-root"));
+ assert!(qs.contains("&project=pinned"), "{qs}");
+ assert!(qs.contains("&project_src=marker"), "{qs}");
+ assert!(!qs.contains("project_src=repo-root"), "{qs}");
}
#[test]
diff --git a/crates/ai-memory-cli/src/commands/init.rs b/crates/ai-memory-cli/src/commands/init.rs
index 1e2423ad..4137ec82 100644
--- a/crates/ai-memory-cli/src/commands/init.rs
+++ b/crates/ai-memory-cli/src/commands/init.rs
@@ -246,8 +246,28 @@ mod tests {
.is_some_and(|p| p.len() == 64),
"parsed token_pepper must round-trip from the rendered template"
);
+ // `[auth]` must stay the LAST section of config.default.toml: the
+ // block appended here emits bare keys, so any section added below it
+ // silently swallows them into the wrong table. Assert the structural
+ // rule directly rather than leaving it to whichever `[auth]` key
+ // happens to be checked above.
+ let rendered = std::fs::read_to_string(&cfg_path).unwrap();
+ let last_section = rendered
+ .lines()
+ .rfind(|line| line.trim_start().starts_with('['))
+ .expect("rendered config declares sections");
+ assert_eq!(
+ last_section.trim(),
+ "[auth]",
+ "[auth] must remain the last section; init appends bare keys after it"
+ );
assert!(loaded.auth.bearer_token.is_none());
assert!(!loaded.slots.per_user);
+ assert_eq!(
+ loaded.routing.mid_session,
+ ai_memory_core::MidSessionRouting::FollowCwd,
+ "generated config must preserve historical per-event attribution"
+ );
assert_eq!(
loaded.consolidation.max_input_tokens,
ai_memory_consolidate::DEFAULT_CONSOLIDATION_MAX_INPUT_TOKENS
diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
index 58f5b584..f05201c3 100644
--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
@@ -224,6 +224,9 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {
const briefingBudget = tomlFlag(body, "max_chars");
if (workspace) url.searchParams.set("workspace", workspace);
if (project) url.searchParams.set("project", project);
+ // `project_src` tells the server a marker rescope from a host-derived
+ // repo-root name; only the latter yields to sticky routing (#394).
+ if (project) url.searchParams.set("project_src", "marker");
if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);
if (dropSubagent) url.searchParams.set("drop_subagent", dropSubagent);
if (defaultGlobal) url.searchParams.set("default_global", defaultGlobal);
@@ -231,7 +234,10 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {
if (briefingBudget) url.searchParams.set("briefing_budget", briefingBudget);
if (!project && (projectStrategy === "repo-root" || projectStrategy === "repo_root")) {
const repoProject = repoRootProject(cwd);
- if (repoProject) url.searchParams.set("project", repoProject);
+ if (repoProject) {
+ url.searchParams.set("project", repoProject);
+ url.searchParams.set("project_src", "repo-root");
+ }
}
} catch (_e) {
}
@@ -262,13 +268,20 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {
} catch (_e) {
}
}
+ // `project_src` tells the server a marker rescope from a host-derived
+ // repo-root name; only the latter yields to sticky routing (#394).
+ let projectSrc: string | undefined = project ? "marker" : undefined;
if (!projectStrategy) projectStrategy = DEFAULT_PROJECT_STRATEGY;
if (!project && (projectStrategy === "repo-root" || projectStrategy === "repo_root")) {
const repoProject = repoRootProject(cwd);
- if (repoProject) project = repoProject;
+ if (repoProject) {
+ project = repoProject;
+ projectSrc = "repo-root";
+ }
}
if (workspace) url.searchParams.set("workspace", workspace);
if (project) url.searchParams.set("project", project);
+ if (projectSrc) url.searchParams.set("project_src", projectSrc);
if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);
if (dropSubagent) url.searchParams.set("drop_subagent", dropSubagent);
if (defaultGlobal) url.searchParams.set("default_global", defaultGlobal);
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index b25c1d8d..3810ffa5 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -625,6 +625,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
)),
home_dir: config.home_dir.clone(),
trusted_proxy_identity: trusted_proxy_identity_enabled(&config.auth),
+ mid_session_routing: config.routing.mid_session,
});
let workstreams = workstream_router(WorkstreamState {
writer: store.writer.clone(),
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index 69f7063e..2675861d 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -207,6 +207,10 @@ pub struct Config {
/// and `per_actor` are for shared installs. See [`AutoScopeSettings`]
/// and [`ai_memory_core::ActiveProjectMode`].
pub auto_scope: AutoScopeSettings,
+ /// `[routing]` — how mid-session events whose cwd moved are attributed.
+ /// Default `follow-cwd` preserves the historical per-event resolution;
+ /// `sticky` keeps the session's project. See [`RoutingSettings`].
+ pub routing: RoutingSettings,
/// Env-backed alias for hook ingest tokens per second per source.
pub hook_rate_per_sec: f64,
/// Env-backed alias for hook ingest burst tokens per source.
@@ -512,6 +516,18 @@ impl Default for AutoScopeSettings {
}
}
+/// `[routing]` section of `config.toml`.
+///
+/// Set under `[routing]` in `config.toml` or via the
+/// `AI_MEMORY_ROUTING__MID_SESSION` env var.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(default)]
+pub struct RoutingSettings {
+ /// `follow-cwd` (default) or `sticky`. See
+ /// [`ai_memory_core::MidSessionRouting`] for full semantics.
+ pub mid_session: ai_memory_core::MidSessionRouting,
+}
+
impl Default for Config {
fn default() -> Self {
Self {
@@ -540,6 +556,7 @@ impl Default for Config {
sanitize: ai_memory_core::SanitizeConfig::default(),
auth: AuthSettings::default(),
auto_scope: AutoScopeSettings::default(),
+ routing: RoutingSettings::default(),
hook_rate_per_sec: 0.0,
hook_rate_burst: 0.0,
allowed_hosts: vec!["localhost".into(), "127.0.0.1".into(), "::1".into()],
diff --git a/crates/ai-memory-cli/templates/config.default.toml b/crates/ai-memory-cli/templates/config.default.toml
index 49a72e62..dbfe2ca4 100644
--- a/crates/ai-memory-cli/templates/config.default.toml
+++ b/crates/ai-memory-cli/templates/config.default.toml
@@ -162,6 +162,27 @@ interval_secs = 3600
max_sessions_per_tick = 1 # per project
min_session_age_secs = 600
+# How a mid-session event is attributed when the agent's cwd has moved since
+# the session started. Session-CREATING events always resolve from their own
+# cwd, and a `.ai-memory.toml` marker naming a project always wins in both
+# modes — a marker is a deliberate rescope, not drift.
+#
+# follow-cwd (default) Re-resolve every mid-session event from its own cwd.
+# A `cd` into a sibling checkout records those observations in
+# that checkout's project, splitting one session's raw record
+# across two projects.
+# sticky Keep the session's project wherever the agent wanders. Matches
+# the one-session-one-project model the rest of the system uses
+# (`sessions.project_id` is single-valued, and consolidation
+# writes one page in the session's project). Recommended when
+# one agent session means one project.
+[routing]
+mid_session = "follow-cwd"
+
+# NOTE: `[auth]` must remain the LAST section in this template.
+# `ai-memory init` appends further `[auth]` keys (token_pepper, root_username,
+# ...) as bare keys to the end of the rendered file, so any section added
+# below would silently capture them.
# Browser session cookies are safe on plain loopback HTTP by default. For `/web`
# behind a trusted HTTPS-terminating reverse proxy, set this to true so browsers
# send the cookie only over HTTPS. Do not enable it for direct HTTP: browsers
diff --git a/crates/ai-memory-core/src/active_project.rs b/crates/ai-memory-core/src/active_project.rs
index e0334bae..97f0e0e6 100644
--- a/crates/ai-memory-core/src/active_project.rs
+++ b/crates/ai-memory-core/src/active_project.rs
@@ -93,6 +93,56 @@ pub enum ActiveProjectMode {
PerActor,
}
+/// Selects how the hook router attributes MID-SESSION events whose cwd has
+/// moved since the session started. Set under `[routing] mid_session`.
+///
+/// Distinct from [`ActiveProjectMode`], which namespaces the in-process
+/// "current project" pointer: this decides the DURABLE project written on
+/// observations, and it never affects session-CREATING events — opening a
+/// session always resolves from its own cwd.
+///
+/// `FollowCwd` is the default and preserves the historical behavior exactly:
+/// every mid-session event re-resolves from its own cwd, so `cd`-ing into a
+/// sibling checkout routes those observations to that checkout's project.
+///
+/// `Sticky` treats mid-session navigation as navigation: the session's project
+/// stays the source of truth wherever the agent wanders. This matches the
+/// product's own model — `sessions.project_id` holds exactly one value, and
+/// consolidation writes one page in the session's project — so following the
+/// cwd splits a session's raw record across projects while its page lands in
+/// only one. A `.ai-memory.toml` marker still wins in both modes: naming a
+/// project is a deliberate rescope, not drift (#394).
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum MidSessionRouting {
+ /// Re-resolve every mid-session event from its own cwd. Historical
+ /// behavior, and the default.
+ #[default]
+ #[serde(alias = "follow_cwd")]
+ FollowCwd,
+ /// Inherit the session's project for every mid-session event, overruling
+ /// a host-derived repo-root override but never a marker-declared one.
+ Sticky,
+}
+
+impl MidSessionRouting {
+ /// Whether this mode lets an established session overrule a
+ /// non-deliberate (host-derived) project override.
+ #[must_use]
+ pub const fn overrules_derived_override(self) -> bool {
+ matches!(self, Self::Sticky)
+ }
+
+ /// Stable config/log representation.
+ #[must_use]
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::FollowCwd => "follow-cwd",
+ Self::Sticky => "sticky",
+ }
+ }
+}
+
/// Composite identity used to key per-actor entries.
/// This cache key namespaces active-project pointers only; it does not
/// namespace durable hook `SessionId` records.
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index 088c9548..81143648 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -37,6 +37,7 @@ pub const GLOBAL_SCOPE_PROJECT: &str = "_global";
pub use active_project::{
ActiveProject, ActiveProjectMode, ActorKey, DEFAULT_MAX_ENTRIES, DEFAULT_PER_KEY_TTL,
+ MidSessionRouting,
};
pub use actor::{
ActorContext, AuthLevel, AuthzError, Capability, IdentityKey, OwnerFilter,
diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rs
index f32d682b..dfb94bc9 100644
--- a/crates/ai-memory-hooks/src/payload.rs
+++ b/crates/ai-memory-hooks/src/payload.rs
@@ -85,6 +85,10 @@ pub struct HookQuery {
pub ingest_key: Option<String>,
/// Explicit root-only recovery propagation from `finalize-session --all-owners`.
pub all_owners: Option<String>,
+ /// Provenance of the `project` override: `marker` when a
+ /// `.ai-memory.toml` named it, `repo-root` when the host hook derived it
+ /// from the enclosing checkout. Absent on older clients (#394).
+ pub project_src: Option<String>,
}
/// Coalesced view of an incoming hook event after light parsing of the
@@ -110,6 +114,9 @@ pub struct HookEnvelope {
pub project_override: Option<String>,
/// Project derivation strategy declared by the hook marker.
pub project_strategy: ProjectStrategy,
+ /// Where `project_override` came from. Always [`ProjectSource::Unspecified`]
+ /// when there is no override, so the two can never disagree (#394).
+ pub project_source: ProjectSource,
/// Whether this project opted into `drop_subagent_captures` via its
/// `.ai-memory.toml` (forwarded as the `drop_subagent` query flag). The
/// ingest router consults this per-event so the drop is scoped to the
@@ -245,6 +252,66 @@ impl ProjectStrategy {
}
}
+/// Where a `project` override on the wire came from.
+///
+/// The host-side hook sends `project=` for two very different reasons: a
+/// `.ai-memory.toml` marker naming the project outright, and `repo-root`
+/// derivation of the enclosing checkout's name (which must run host-side —
+/// a containerized server cannot see the client's checkout). Both arrive as
+/// the same query parameter, so before #394's `sticky` knob the router could
+/// not honor one while overriding the other. This discriminator is that
+/// missing signal: a marker is a deliberate rescope and always wins, while a
+/// repo-root derivation is just "where the cwd happens to be" and may yield
+/// to the session under `[routing] mid_session = "sticky"`.
+///
+/// Older clients omit the parameter entirely and parse as [`Self::Unspecified`],
+/// which keeps their overrides authoritative — the pre-#394 behavior.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum ProjectSource {
+ /// No provenance declared: either no override at all, or a client too
+ /// old to tag one. Treated as authoritative, never as fell-through.
+ #[default]
+ Unspecified,
+ /// A `.ai-memory.toml` marker named this project explicitly.
+ Marker,
+ /// The host hook derived it from the enclosing git repo root under the
+ /// `repo-root` strategy.
+ RepoRoot,
+}
+
+impl ProjectSource {
+ /// Parse the `project_src` query value. Unknown values fall back to
+ /// [`Self::Unspecified`] so a typo can never downgrade an override into
+ /// something the session is allowed to overrule.
+ #[must_use]
+ pub fn parse(value: Option<&str>) -> Self {
+ match value {
+ Some("marker") => Self::Marker,
+ Some("repo-root" | "repo_root") => Self::RepoRoot,
+ _ => Self::Unspecified,
+ }
+ }
+
+ /// Stable wire/log representation.
+ #[must_use]
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Unspecified => "unspecified",
+ Self::Marker => "marker",
+ Self::RepoRoot => "repo-root",
+ }
+ }
+
+ /// Whether an override from this source may yield to session-sticky
+ /// attribution. Only host-side repo-root derivation may: it carries no
+ /// operator intent, just the cwd's enclosing checkout.
+ #[must_use]
+ pub const fn yields_to_session(self) -> bool {
+ matches!(self, Self::RepoRoot)
+ }
+}
+
/// Discriminator for the lifecycle event that triggered the hook.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
@@ -397,6 +464,14 @@ impl HookEnvelope {
let workspace_override = query.workspace.filter(|s| !s.is_empty());
let project_override = query.project.filter(|s| !s.is_empty());
let project_strategy = ProjectStrategy::parse(query.project_strategy.as_deref());
+ // Provenance describes an override, so it is meaningless without one.
+ // Pinning it to `Unspecified` here keeps every downstream check from
+ // having to re-test `project_override.is_some()` alongside it.
+ let project_source = if project_override.is_some() {
+ ProjectSource::parse(query.project_src.as_deref())
+ } else {
+ ProjectSource::Unspecified
+ };
let drop_subagent_requested = query_flag_truthy(query.drop_subagent.as_deref());
let recall_default_global_requested = query_flag_truthy(query.default_global.as_deref());
let all_owners_requested = query_flag_truthy(query.all_owners.as_deref());
@@ -457,6 +532,7 @@ impl HookEnvelope {
workspace_override,
project_override,
project_strategy,
+ project_source,
drop_subagent_requested,
recall_default_global_requested,
all_owners_requested,
@@ -917,6 +993,68 @@ fn normalize_token(value: &str, max_len: usize) -> Option<String> {
mod tests {
use super::*;
+ #[test]
+ fn project_source_parses_both_spellings_and_defaults_closed() {
+ assert_eq!(ProjectSource::parse(Some("marker")), ProjectSource::Marker);
+ assert_eq!(
+ ProjectSource::parse(Some("repo-root")),
+ ProjectSource::RepoRoot
+ );
+ assert_eq!(
+ ProjectSource::parse(Some("repo_root")),
+ ProjectSource::RepoRoot
+ );
+ // Absent (older client) and unknown values both stay authoritative,
+ // so a typo can never downgrade an override into something the
+ // session is allowed to overrule.
+ assert_eq!(ProjectSource::parse(None), ProjectSource::Unspecified);
+ assert_eq!(
+ ProjectSource::parse(Some("REPO-ROOT")),
+ ProjectSource::Unspecified
+ );
+ assert_eq!(
+ ProjectSource::parse(Some("nonsense")),
+ ProjectSource::Unspecified
+ );
+ // Only a host-derived name may yield to the session.
+ assert!(ProjectSource::RepoRoot.yields_to_session());
+ assert!(!ProjectSource::Marker.yields_to_session());
+ assert!(!ProjectSource::Unspecified.yields_to_session());
+ }
+
+ #[test]
+ fn project_source_is_pinned_unspecified_without_an_override() {
+ // Provenance describes an override; a `project_src` arriving without
+ // one is meaningless and must not read as a fell-through signal.
+ let env = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "user-prompt-submit".into(),
+ agent: Some("claude-code".into()),
+ cwd: Some("/checkouts/repo-a".into()),
+ project_src: Some("repo-root".into()),
+ ..Default::default()
+ },
+ serde_json::json!({ "session_id": "s" }),
+ );
+ assert_eq!(env.project_override, None);
+ assert_eq!(env.project_source, ProjectSource::Unspecified);
+
+ // With an override it is carried through verbatim.
+ let env = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "user-prompt-submit".into(),
+ agent: Some("claude-code".into()),
+ cwd: Some("/checkouts/repo-a".into()),
+ project: Some("repo-a".into()),
+ project_src: Some("repo-root".into()),
+ ..Default::default()
+ },
+ serde_json::json!({ "session_id": "s" }),
+ );
+ assert_eq!(env.project_override.as_deref(), Some("repo-a"));
+ assert_eq!(env.project_source, ProjectSource::RepoRoot);
+ }
+
#[test]
fn body_is_subagent_detects_harness_markers() {
// grok tags subagent tool-use events with `subagentType`.
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index bd676429..37a64267 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -15,9 +15,9 @@ use std::sync::{Arc, Weak};
use ai_memory_consolidate::{Consolidator, ConsolidatorError};
use ai_memory_core::{
ActiveProject, ActorKey, AgentKind, DEFAULT_WORKSPACE_NAME, Handoff, IdentityKey,
- MANAGED_WORKSTREAM_PACKET_MARKER, ManagedRunId, NewHandoff, NewObservation, NewSession,
- ObservationKind, ProjectId, Sanitized, Sanitizer, SessionId, WorkspaceId, WorkstreamEvent,
- WorkstreamEventKind,
+ MANAGED_WORKSTREAM_PACKET_MARKER, ManagedRunId, MidSessionRouting, NewHandoff, NewObservation,
+ NewSession, ObservationKind, ProjectId, Sanitized, Sanitizer, SessionId, WorkspaceId,
+ WorkstreamEvent, WorkstreamEventKind,
};
use ai_memory_store::{HookSessionAdmission, IngestObservationOutcome, StoreError, WriterHandle};
use ai_memory_wiki::{AdmissionContext, AdmissionOp, Wiki};
@@ -38,7 +38,8 @@ use crate::capture_policy::{
};
use crate::log;
use crate::payload::{
- HookEnvelope, HookEvent, HookQuery, ProjectStrategy, body_is_subagent, parse_agent,
+ HookEnvelope, HookEvent, HookQuery, ProjectSource, ProjectStrategy, body_is_subagent,
+ parse_agent,
};
use crate::synth::synthesize_session_page;
@@ -493,6 +494,11 @@ pub struct HookState {
pub trusted_proxy_identity: bool,
/// Namespace slot injection by the qualified request identity.
pub per_user_slots: bool,
+ /// `[routing] mid_session`: whether a mid-session event that wandered out
+ /// of the session's tree re-resolves from its own cwd (`follow-cwd`, the
+ /// default and historical behavior) or inherits the session's project
+ /// (`sticky`). Held here because the hooks crate makes no config reads.
+ pub mid_session_routing: ai_memory_core::MidSessionRouting,
}
/// The owner to stamp on the session and handoff rows this event creates
@@ -2114,6 +2120,58 @@ fn sticky_out_of_tree_under_repo_root(
&& meaningful_session_anchor(session_cwd, home_dir).is_some()
}
+/// Whether this event's declared overrides leave room for session-sticky
+/// attribution at all (issue #394's `sticky` knob).
+///
+/// A marker-declared scope is a deliberate rescope in BOTH modes and always
+/// wins — that is the invariant the whole knob is built around. What `sticky`
+/// changes is the other kind of override: under `repo-root` the host hook
+/// derives `project=<checkout name>` from wherever the cwd happens to be, which
+/// carries no operator intent, so an established session may overrule it. The
+/// wire-level [`ProjectSource`] is what makes the two distinguishable; a client
+/// too old to tag its override reports `Unspecified` and keeps today's
+/// behavior, so `sticky` degrades safely rather than silently capturing
+/// deliberate rescopes.
+fn overrides_permit_sticky(
+ workspace_override: Option<&str>,
+ project_override: Option<&str>,
+ project_source: ProjectSource,
+ routing: MidSessionRouting,
+) -> bool {
+ // A workspace override only ever comes from a marker file.
+ if workspace_override.is_some() {
+ return false;
+ }
+ if project_override.is_none() {
+ return true;
+ }
+ routing.overrules_derived_override() && project_source.yields_to_session()
+}
+
+/// Whether the session's cwd anchor and the event's cwd admit stickiness.
+///
+/// `follow-cwd` keeps the two #394 paths: inside the session's own subtree, or
+/// out of tree under `repo-root` where a missing override already proves the
+/// cwd resolved to nothing. `sticky` extends out-of-tree inheritance to every
+/// strategy — the point of the knob is that mid-session navigation never
+/// rescopes, whether the agent wandered into `/tmp` or into a sibling
+/// checkout. The broad-anchor guard is deliberately NOT relaxed: a session
+/// rooted at `/` or `$HOME` still never sticks in either mode, or one stray
+/// session would fold every project beneath it into a single bucket (the #103
+/// catch-all failure mode).
+fn sticky_cwd_admits(
+ session_cwd: Option<&str>,
+ event_cwd: Option<&str>,
+ home_dir: Option<&str>,
+ strategy: ProjectStrategy,
+ routing: MidSessionRouting,
+) -> bool {
+ sticky_within_session_tree(session_cwd, event_cwd, home_dir)
+ || sticky_out_of_tree_under_repo_root(session_cwd, home_dir, strategy)
+ || (routing.overrules_derived_override()
+ && meaningful_session_anchor(session_cwd, home_dir).is_some())
+}
+
async fn process_envelope(
state: Arc<HookState>,
env: HookEnvelope,
@@ -2266,20 +2324,26 @@ async fn process_authorized(
// the user's home — never sticks, or a stray session started in
// `$HOME` would fold every project beneath it into one bucket
// (the same catch-all failure #103 healed for repo_path keys).
- let sticky_scope = if env.project_override.is_none() && env.workspace_override.is_none() {
+ // - Under `[routing] mid_session = "sticky"` the session also overrules a
+ // host-derived `repo-root` override, closing the cross-repo `cd` case;
+ // marker-declared scopes still win. See `overrides_permit_sticky`.
+ let sticky_scope = if overrides_permit_sticky(
+ env.workspace_override.as_deref(),
+ env.project_override.as_deref(),
+ env.project_source,
+ state.mid_session_routing,
+ ) {
state
.reader
.find_session_scope(session_id)
.await?
.filter(|(_, _, session_cwd)| {
- sticky_within_session_tree(
+ sticky_cwd_admits(
session_cwd.as_deref(),
env.cwd.as_deref(),
state.home_dir.as_deref(),
- ) || sticky_out_of_tree_under_repo_root(
- session_cwd.as_deref(),
- state.home_dir.as_deref(),
env.project_strategy,
+ state.mid_session_routing,
)
})
} else {
@@ -3131,6 +3195,7 @@ mod tests {
)),
ingest_gates: IngestGates::default(),
per_user_slots: false,
+ mid_session_routing: MidSessionRouting::default(),
}
}
@@ -3658,6 +3723,90 @@ mod tests {
));
}
+ // The override gate for `[routing] mid_session` (#394). The invariant
+ // under test: a marker-declared project is a deliberate rescope and wins
+ // in BOTH modes; only a host-derived repo-root name may yield, and only
+ // under `sticky`.
+ #[test]
+ fn override_gate_distinguishes_marker_from_derived_project() {
+ use MidSessionRouting::{FollowCwd, Sticky};
+ use ProjectSource::{Marker, RepoRoot, Unspecified};
+
+ // (workspace, project, source, routing, expected)
+ let cases = [
+ // No override at all: both modes may stick (pre-#394 behavior).
+ (None, None, Unspecified, FollowCwd, true),
+ (None, None, Unspecified, Sticky, true),
+ // Marker-declared project: never yields, in either mode.
+ (None, Some("acme"), Marker, FollowCwd, false),
+ (None, Some("acme"), Marker, Sticky, false),
+ // Host-derived repo-root name: yields only under `sticky`. This
+ // is the cross-repo `cd` case the knob exists for.
+ (None, Some("acme"), RepoRoot, FollowCwd, false),
+ (None, Some("acme"), RepoRoot, Sticky, true),
+ // An untagged override from an older client stays authoritative,
+ // so `sticky` degrades safely instead of capturing a rescope.
+ (None, Some("acme"), Unspecified, Sticky, false),
+ // A marker workspace is itself a deliberate scope declaration.
+ (Some("oss"), None, Unspecified, Sticky, false),
+ (Some("oss"), Some("acme"), RepoRoot, Sticky, false),
+ ];
+ for (ws, project, source, routing, expected) in cases {
+ assert_eq!(
+ overrides_permit_sticky(ws, project, source, routing),
+ expected,
+ "ws={ws:?} project={project:?} source={} routing={}",
+ source.as_str(),
+ routing.as_str(),
+ );
+ }
+ }
+
+ // `sticky` extends out-of-tree inheritance to every strategy, but must
+ // NOT relax the broad-anchor guard that keeps a stray `$HOME` session
+ // from becoming a catch-all (#103).
+ #[test]
+ fn sticky_mode_extends_out_of_tree_but_keeps_broad_anchor_guard() {
+ use MidSessionRouting::{FollowCwd, Sticky};
+
+ // Basename strategy, cwd outside the session tree: only `sticky`.
+ assert!(!sticky_cwd_admits(
+ Some("/a/b"),
+ Some("/elsewhere"),
+ Some("/home/user"),
+ ProjectStrategy::Basename,
+ FollowCwd,
+ ));
+ assert!(sticky_cwd_admits(
+ Some("/a/b"),
+ Some("/elsewhere"),
+ Some("/home/user"),
+ ProjectStrategy::Basename,
+ Sticky,
+ ));
+ // Broad anchors refuse in `sticky` too — the guard is not relaxed.
+ for anchor in [Some("/"), Some("/home/user"), None] {
+ assert!(
+ !sticky_cwd_admits(
+ anchor,
+ Some("/elsewhere"),
+ Some("/home/user"),
+ ProjectStrategy::Basename,
+ Sticky,
+ ),
+ "broad anchor {anchor:?} must never stick"
+ );
+ }
+ // In-tree stickiness is unchanged by the mode.
+ assert!(sticky_cwd_admits(
+ Some("/a/b"),
+ Some("/a/b/c"),
+ Some("/home/user"),
+ ProjectStrategy::Basename,
+ FollowCwd,
+ ));
+ }
+
// Session-sticky attribution: a mid-session `cd subdir/` inside a
// NON-GIT project must keep observations in the session's project.
// This is the exact production failure behind the fragment cleanup:
@@ -3901,6 +4050,196 @@ mod tests {
);
}
+ /// Fire a mid-session `cd` from one checkout into a sibling one, with the
+ /// host hook tagging each `project` override by provenance, and report
+ /// where the second observation landed. The shared fixture behind the
+ /// cross-repo cases below (#394).
+ async fn cross_repo_cd(
+ state: &HookState,
+ sid: &str,
+ source: &str,
+ ) -> (ProjectId, Option<ProjectId>) {
+ let fire = |event: &str, cwd: &str, project: &str, project_src: Option<&str>| {
+ HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: event.into(),
+ agent: Some("claude-code".into()),
+ cwd: Some(cwd.to_string()),
+ project: Some(project.to_string()),
+ project_src: project_src.map(str::to_owned),
+ project_strategy: Some("repo-root".into()),
+ ..Default::default()
+ },
+ serde_json::json!({
+ "session_id": sid,
+ "cwd": cwd,
+ "tool_name": "Bash",
+ }),
+ )
+ };
+ process(
+ state,
+ fire("session-start", "/checkouts/repo-a", "repo-a", Some(source)),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ process(
+ state,
+ fire("post-tool-use", "/checkouts/repo-b", "repo-b", Some(source)),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+
+ let session_id: SessionId = sid.parse().unwrap();
+ let observations = state
+ .reader
+ .observations_for_session(session_id)
+ .await
+ .unwrap();
+ assert_eq!(observations.len(), 2);
+ let landed = observations.last().unwrap().project_id;
+ let repo_b = state
+ .reader
+ .find_project(state.workspace_id, "repo-b".to_string())
+ .await
+ .unwrap();
+ (landed, repo_b)
+ }
+
+ // The cross-repo `cd` case #394 left open. Under `sticky`, a mid-session
+ // hop into a sibling checkout keeps the session's project: the override
+ // is host-derived (`project_src=repo-root`), so it carries no operator
+ // intent and yields to the session.
+ #[tokio::test]
+ async fn sticky_routing_keeps_the_session_project_across_a_sibling_checkout() {
+ let tmp = TempDir::new().unwrap();
+ let mut state = make_state(&tmp).await;
+ state.mid_session_routing = MidSessionRouting::Sticky;
+ let sid = "77777777-7777-4777-8777-777777777777";
+
+ let repo_a = state
+ .reader
+ .find_project(state.workspace_id, "repo-a".to_string())
+ .await
+ .unwrap();
+ assert_eq!(repo_a, None, "fixture starts clean");
+
+ let (landed, repo_b) = cross_repo_cd(&state, sid, "repo-root").await;
+ let repo_a = state
+ .reader
+ .find_project(state.workspace_id, "repo-a".to_string())
+ .await
+ .unwrap()
+ .expect("session project exists");
+ assert_eq!(
+ landed, repo_a,
+ "a mid-session hop into a sibling checkout must stay in the session's project"
+ );
+ assert_eq!(
+ repo_b, None,
+ "sticky routing must not split the session's record into a second project"
+ );
+ }
+
+ // The same fixture under the DEFAULT mode must behave exactly as it does
+ // today: the sibling checkout's project is minted and takes the event.
+ // This is the guard that `sticky` is genuinely opt-in.
+ #[tokio::test]
+ async fn follow_cwd_routing_still_splits_across_a_sibling_checkout() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ assert_eq!(
+ state.mid_session_routing,
+ MidSessionRouting::FollowCwd,
+ "follow-cwd must remain the default"
+ );
+ let sid = "88888888-8888-4888-8888-888888888888";
+
+ let (landed, repo_b) = cross_repo_cd(&state, sid, "repo-root").await;
+ let repo_b = repo_b.expect("follow-cwd mints the visited checkout's project");
+ assert_eq!(
+ landed, repo_b,
+ "follow-cwd must keep resolving every event from its own cwd"
+ );
+ }
+
+ // Even under `sticky`, a `.ai-memory.toml` naming the project is a
+ // deliberate rescope and must still win — the invariant the provenance
+ // parameter exists to protect.
+ #[tokio::test]
+ async fn sticky_routing_still_yields_to_a_marker_declared_project() {
+ let tmp = TempDir::new().unwrap();
+ let mut state = make_state(&tmp).await;
+ state.mid_session_routing = MidSessionRouting::Sticky;
+ let sid = "99999999-9999-4999-8999-999999999999";
+
+ let (landed, repo_b) = cross_repo_cd(&state, sid, "marker").await;
+ let repo_b = repo_b.expect("a marker-declared project must still be created");
+ assert_eq!(
+ landed, repo_b,
+ "a marker override is a deliberate rescope and outranks stickiness"
+ );
+ }
+
+ // A client too old to tag its override reports no provenance. `sticky`
+ // must treat that as authoritative rather than assume it was derived,
+ // so a mixed-version fleet cannot silently capture deliberate rescopes.
+ #[tokio::test]
+ async fn sticky_routing_does_not_capture_untagged_overrides_from_old_clients() {
+ let tmp = TempDir::new().unwrap();
+ let mut state = make_state(&tmp).await;
+ state.mid_session_routing = MidSessionRouting::Sticky;
+ let sid = "abababab-abab-4bab-8bab-abababababab";
+ let fire = |event: &str, cwd: &str, project: &str| {
+ HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: event.into(),
+ agent: Some("claude-code".into()),
+ cwd: Some(cwd.to_string()),
+ project: Some(project.to_string()),
+ // No `project_src`: the pre-#394 wire format.
+ project_strategy: Some("repo-root".into()),
+ ..Default::default()
+ },
+ serde_json::json!({
+ "session_id": sid,
+ "cwd": cwd,
+ "tool_name": "Bash",
+ }),
+ )
+ };
+ process(
+ &state,
+ fire("session-start", "/checkouts/legacy-a", "legacy-a"),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ process(
+ &state,
+ fire("post-tool-use", "/checkouts/legacy-b", "legacy-b"),
+ None,
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ state
+ .reader
+ .find_project(state.workspace_id, "legacy-b".to_string())
+ .await
+ .unwrap()
+ .is_some(),
+ "an untagged override must stay authoritative under sticky"
+ );
+ }
+
#[tokio::test]
async fn delayed_hook_tail_does_not_steal_active_project_fallback() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-mcp/tests/autoscope_multiuser.rs b/crates/ai-memory-mcp/tests/autoscope_multiuser.rs
index 8dd2713e..cbd0765e 100644
--- a/crates/ai-memory-mcp/tests/autoscope_multiuser.rs
+++ b/crates/ai-memory-mcp/tests/autoscope_multiuser.rs
@@ -165,6 +165,7 @@ impl MultiUserHarness {
session_consolidation_notify: None,
capture_assistant_enabled: false,
per_user_slots: false,
+ mid_session_routing: ai_memory_core::MidSessionRouting::default(),
subagent_sessions: Arc::new(tokio::sync::Mutex::new(SubagentSessionSet::default())),
ingest_rate: Arc::new(tokio::sync::Mutex::new(
ai_memory_hooks::IngestRateLimiter::disabled(),
diff --git a/crates/ai-memory-mcp/tests/autoscope_stress.rs b/crates/ai-memory-mcp/tests/autoscope_stress.rs
index 83211784..2b0a47f9 100644
--- a/crates/ai-memory-mcp/tests/autoscope_stress.rs
+++ b/crates/ai-memory-mcp/tests/autoscope_stress.rs
@@ -163,6 +163,7 @@ impl Harness {
session_consolidation_notify: None,
capture_assistant_enabled: false,
per_user_slots: false,
+ mid_session_routing: ai_memory_core::MidSessionRouting::default(),
subagent_sessions: Arc::new(tokio::sync::Mutex::new(SubagentSessionSet::default())),
ingest_rate: Arc::new(tokio::sync::Mutex::new(
ai_memory_hooks::IngestRateLimiter::disabled(),
diff --git a/docs/auto-scope.md b/docs/auto-scope.md
index f025aca6..0c335c00 100644
--- a/docs/auto-scope.md
+++ b/docs/auto-scope.md
@@ -112,10 +112,11 @@ can append observations or publish a pointer for the foreign actor.
Owner and agent are what identify a session; scope is not. The same operator's
session legitimately produces events in another project when its cwd moves, so
-a differing `(workspace, project)` is recorded rather than rejected. The one
-exception is a terminal event: a `SessionEnd` naming a different scope than its
-session is not that session's end, so it is dropped rather than ending someone
-else's session.
+a differing `(workspace, project)` is recorded rather than rejected — see
+[`[routing] mid_session`](marker-file.md#mid-session-navigation-routing-mid_session)
+for how those events are attributed. The one exception is a terminal event: a
+`SessionEnd` naming a different scope than its session is not that session's
+end, so it is dropped rather than ending someone else's session.
## Client requirements
diff --git a/docs/marker-file.md b/docs/marker-file.md
index 174480a7..e6cdc490 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -334,6 +334,54 @@ ai-memory's hooks; pass `--project-strategy basename` explicitly to remove it.
Precedence is unchanged: a marker's explicit `project_strategy` or `project`
still wins over the install default.
+## Mid-session navigation: `[routing] mid_session`
+
+Everything above decides where a session *starts*. A long session also moves:
+an agent runs `cd` into a scratch directory, or into a sibling checkout to
+grep a reference. `[routing] mid_session` in `config.toml` decides how those
+mid-session events are attributed. It is server-side runtime config, not a
+marker key.
+
+```toml
+[routing]
+mid_session = "follow-cwd" # default
+# mid_session = "sticky"
+```
+
+- **`follow-cwd`** (default, historical behavior) re-resolves every
+ mid-session event from its own cwd. A `cd` into a sibling checkout records
+ those observations in that checkout's project, so one session's raw record
+ is split across two projects while its session row and compiled page stay
+ in the first.
+- **`sticky`** keeps the session's project wherever the agent wanders. This
+ matches the model the rest of the system already uses: `sessions.project_id`
+ holds exactly one value, and consolidation reads by `session_id` and writes
+ one page in the session's project. Choose it when one agent session means
+ one project.
+
+Two guarantees hold in **both** modes:
+
+- **A marker still wins.** A `.ai-memory.toml` naming a project is a
+ deliberate rescope, not drift, so it is never overruled. The hook tells the
+ server which kind of override it sent (`project_src=marker` vs
+ `project_src=repo-root`), which is what lets `sticky` overrule a derived
+ name while honoring a declared one. A client older than v1.27 sends no
+ provenance, and its overrides stay authoritative.
+- **Broad anchors never stick.** A session rooted at `/` or at `$HOME` is not
+ a meaningful anchor, so it never captures events beneath it — otherwise one
+ stray session started in `$HOME` would fold every project into a single
+ bucket.
+
+Session-creating events are unaffected in both modes: opening a session in a
+plain non-git folder still names the project after that folder.
+
+Independently of this setting, under `project_strategy = "repo-root"` a
+mid-session event whose cwd is outside any git repo *and* any marker (agent
+scratch directories, `/tmp`, data folders) already inherits the session's
+project rather than minting a phantom project named `scratchpad` or `data`.
+The host hook resolves repo-root itself, so a missing override already proves
+the cwd resolved to nothing.
+
## Who reads the marker
Both entry points, as of v1.20:
diff --git a/hooks/_lib.sh b/hooks/_lib.sh
index 064b420b..cf90a0d7 100644
--- a/hooks/_lib.sh
+++ b/hooks/_lib.sh
@@ -219,12 +219,17 @@ ai_memory_marker_qs() {
pr=""
st=""
ds=""
+ # Provenance of `pr`, forwarded as `project_src` so the server can tell a
+ # 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")
if [ -n "$marker" ]; then
ws=$(ai_memory_parse_toml_key "$marker" workspace)
pr=$(ai_memory_parse_toml_key "$marker" project)
st=$(ai_memory_parse_toml_key "$marker" project_strategy)
ds=$(ai_memory_parse_toml_key "$marker" drop_subagent_captures)
+ [ -n "$pr" ] && ps="marker"
fi
# Install-time default baked into the hook command by
# `install-hooks --project-strategy` fills the strategy only when no marker
@@ -240,11 +245,15 @@ ai_memory_marker_qs() {
# keep their existing resolution path.
if [ -z "$pr" ]; then
case "$st" in
- repo-root | repo_root) pr=$(ai_memory_repo_root_project "$cwd") ;;
+ repo-root | repo_root)
+ pr=$(ai_memory_repo_root_project "$cwd")
+ [ -n "$pr" ] && ps="repo-root"
+ ;;
esac
fi
[ -n "$ws" ] && qs="${qs}&workspace=$(ai_memory_url_encode "$ws")"
[ -n "$pr" ] && qs="${qs}&project=$(ai_memory_url_encode "$pr")"
+ [ -n "$ps" ] && qs="${qs}&project_src=$(ai_memory_url_encode "$ps")"
[ -n "$st" ] && qs="${qs}&project_strategy=$(ai_memory_url_encode "$st")"
# Per-project drop_subagent_captures opt-in: forward to the server, which
# interprets truthiness (1/true/...) and scopes the drop to this project.
diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1
index 4f81b4b1..e1b5f69c 100644
--- a/hooks/lib/ai-memory-hook.ps1
+++ b/hooks/lib/ai-memory-hook.ps1
@@ -171,12 +171,17 @@ function Get-AiMemoryMarkerQuery {
$proj = $null
$strategy = $null
$dropSubagent = $null
+ # Provenance of $proj, forwarded as `project_src` so the server can tell a
+ # deliberate marker rescope from a host-derived repo-root name. Only the
+ # latter may yield to session-sticky attribution (#394).
+ $projSrc = $null
$marker = Get-AiMemoryMarkerToml -Cwd $Cwd
if ($marker) {
$ws = Get-AiMemoryTomlKey -File $marker -Key "workspace"
$proj = Get-AiMemoryTomlKey -File $marker -Key "project"
$strategy = Get-AiMemoryTomlKey -File $marker -Key "project_strategy"
$dropSubagent = Get-AiMemoryTomlKey -File $marker -Key "drop_subagent_captures"
+ if ($proj) { $projSrc = "marker" }
}
# Install-time default baked into the hook command by
# `install-hooks --project-strategy` fills the strategy only when no marker
@@ -188,9 +193,11 @@ function Get-AiMemoryMarkerQuery {
# only when no explicit project is pinned. Explicit project always wins.
if (-not $proj -and ($strategy -eq "repo-root" -or $strategy -eq "repo_root")) {
$proj = Get-AiMemoryRepoRootProject -Cwd $Cwd
+ if ($proj) { $projSrc = "repo-root" }
}
if ($ws) { $qs += "&workspace=$([uri]::EscapeDataString($ws))" }
if ($proj) { $qs += "&project=$([uri]::EscapeDataString($proj))" }
+ if ($projSrc) { $qs += "&project_src=$([uri]::EscapeDataString($projSrc))" }
if ($strategy) { $qs += "&project_strategy=$([uri]::EscapeDataString($strategy))" }
# Per-project drop_subagent_captures opt-in: forward to the server, which
# interprets truthiness (1/true/...) and scopes the drop to this project.
diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.sh
index f1c6afda..a2119efe 100755
--- a/tests/hooks/test_lib.sh
+++ b/tests/hooks/test_lib.sh
@@ -156,7 +156,7 @@ assert_eq "marker_qs single key" "&cwd=$(ai_memory_url_encode "$TMP/a/b/c")&work
printf 'workspace = "ws1"\nproject = "p1"\nproject_strategy = "repo-root"\n' >"$TMP/a/b/.ai-memory.toml"
QS2=$(ai_memory_marker_qs "$TMP/a/b/c")
-assert_eq "closer marker wins" "&cwd=$(ai_memory_url_encode "$TMP/a/b/c")&workspace=ws1&project=p1&project_strategy=repo-root" "$QS2"
+assert_eq "closer marker wins" "&cwd=$(ai_memory_url_encode "$TMP/a/b/c")&workspace=ws1&project=p1&project_src=marker&project_strategy=repo-root" "$QS2"
QS3=$(ai_memory_marker_qs "$TMP/nonexistent")
assert_eq "no marker -> cwd only" "&cwd=$(ai_memory_url_encode "$TMP/nonexistent")" "$QS3"
@@ -180,7 +180,7 @@ if command -v git >/dev/null 2>&1; then
printf 'workspace = "oss"\nproject_strategy = "repo-root"\n' >"$REPO/.ai-memory.toml"
QSR=$(ai_memory_marker_qs "$REPO/crates/cli")
assert_eq "repo-root: subdir resolves to repo basename" \
- "&cwd=$(ai_memory_url_encode "$REPO/crates/cli")&workspace=oss&project=acme-api&project_strategy=repo-root" \
+ "&cwd=$(ai_memory_url_encode "$REPO/crates/cli")&workspace=oss&project=acme-api&project_src=repo-root&project_strategy=repo-root" \
"$QSR"
rm -f "$REPO/.ai-memory.toml"
@@ -188,14 +188,14 @@ if command -v git >/dev/null 2>&1; then
export AI_MEMORY_PROJECT_STRATEGY
QSE=$(ai_memory_marker_qs "$REPO/crates/cli")
assert_eq "repo-root env: no marker resolves to repo basename" \
- "&cwd=$(ai_memory_url_encode "$REPO/crates/cli")&project=acme-api&project_strategy=repo-root" \
+ "&cwd=$(ai_memory_url_encode "$REPO/crates/cli")&project=acme-api&project_src=repo-root&project_strategy=repo-root" \
"$QSE"
printf 'workspace = "oss"\nproject = "pinned"\nproject_strategy = "basename"\n' \
>"$REPO/.ai-memory.toml"
QSO=$(ai_memory_marker_qs "$REPO/crates/cli")
assert_eq "marker project strategy overrides env default" \
- "&cwd=$(ai_memory_url_encode "$REPO/crates/cli")&workspace=oss&project=pinned&project_strategy=basename" \
+ "&cwd=$(ai_memory_url_encode "$REPO/crates/cli")&workspace=oss&project=pinned&project_src=marker&project_strategy=basename" \
"$QSO"
unset AI_MEMORY_PROJECT_STRATEGY
@@ -212,7 +212,7 @@ if command -v git >/dev/null 2>&1; then
if git -C "$REPO" worktree add -q "$WT" >/dev/null 2>&1; then
QSW=$(ai_memory_marker_qs "$WT")
assert_eq "repo-root: out-of-tree worktree collapses to main repo" \
- "&cwd=$(ai_memory_url_encode "$WT")&workspace=oss&project=acme-api&project_strategy=repo-root" \
+ "&cwd=$(ai_memory_url_encode "$WT")&workspace=oss&project=acme-api&project_src=repo-root&project_strategy=repo-root" \
"$QSW"
fi
@@ -221,7 +221,7 @@ if command -v git >/dev/null 2>&1; then
>"$REPO/.ai-memory.toml"
QSP=$(ai_memory_marker_qs "$REPO/crates/cli")
assert_eq "explicit project pin beats repo-root" \
- "&cwd=$(ai_memory_url_encode "$REPO/crates/cli")&workspace=oss&project=pinned&project_strategy=repo-root" \
+ "&cwd=$(ai_memory_url_encode "$REPO/crates/cli")&workspace=oss&project=pinned&project_src=marker&project_strategy=repo-root" \
"$QSP"
PSH=""