Skip to content

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

Rust

feat(hooks): marker-opted project brief on session start (#176)

AkitaOnRailsc2e4aef1e0c4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 575afe82..c462250d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- New `.ai-memory.toml` marker section `[briefing] inject_on_session_start
+ = "true"` ([#176]): the session-start handoff fetch also returns a
+ compiled project brief — pinned / `_rules/` / `_slots/` pages with
+ bodies plus recently-updated page titles — injected as agent context so
+ a fresh session (or a Claude Code `/clear`, which re-fires SessionStart)
+ starts with the architecture instead of re-exploring the codebase.
+ `max_chars` caps the brief (default 4000 chars, clamped to 500–20000);
+ over-budget pages are truncated or listed by path. The brief is
+ recomposed on every opted-in session start (non-consumable, unlike the
+ handoff) and appended after any pending handoff. Off by default — it
+ costs tokens on every session start.
+- Generated OpenCode / OMP / OpenClaw TypeScript integrations now forward
+ the `[recall] default_global` marker flag (previously only the native
+ hook binary did) and the new `[briefing]` keys, accepting bare
+ (unquoted) TOML values for both.
- New `.ai-memory.toml` marker option `[recall] default_global = "true"`
([#177]): sessions in the marked tree make an *unscoped* `memory_query`
behave as `global=true`, so meta-repos that constantly need
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index 65d2efa1..875ebf18 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -54,6 +54,7 @@ pub fn marker_query_suffix(cwd: &str, default_strategy: Option<&str>) -> String
let mut qs = format!("&cwd={}", url_encode(cwd));
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) {
workspace = parse_toml_key(&marker, "workspace");
project = parse_toml_key(&marker, "project");
@@ -62,6 +63,11 @@ pub fn marker_query_suffix(cwd: &str, default_strategy: Option<&str>) -> String
// `[recall] default_global = true` (or top-level; quoted or bare) —
// a meta-repo opts every default-scoped read into a global search.
default_global = parse_toml_flag(&marker, "default_global");
+ // `[briefing] inject_on_session_start = true` + optional
+ // `max_chars = N` — opt this repo into the compiled project brief
+ // appended to the session-start handoff fetch (#176).
+ briefing = parse_toml_flag(&marker, "inject_on_session_start");
+ briefing_budget = parse_toml_flag(&marker, "max_chars");
}
if strategy.is_none() {
strategy = default_strategy.map(str::to_owned);
@@ -90,6 +96,16 @@ pub fn marker_query_suffix(cwd: &str, default_strategy: Option<&str>) -> String
if let Some(val) = default_global.filter(|v| !v.is_empty()) {
qs.push_str(&format!("&default_global={}", url_encode(&val)));
}
+ // Per-repo session-start brief opt-in: forwarded on every request for
+ // simplicity (the capture path ignores it); only the `/handoff` GET at
+ // session start acts on it. Truthiness and the char-budget clamp are
+ // decided server-side.
+ if let Some(val) = briefing.filter(|v| !v.is_empty()) {
+ qs.push_str(&format!("&briefing={}", url_encode(&val)));
+ }
+ if let Some(val) = briefing_budget.filter(|v| !v.is_empty()) {
+ qs.push_str(&format!("&briefing_budget={}", url_encode(&val)));
+ }
qs
}
@@ -584,6 +600,34 @@ drop_subagent_captures = "true"
assert!(!qs.contains("default_global"), "{qs}");
}
+ /// A `[briefing]` section (bare or quoted values) forwards the opt-in
+ /// and the char budget so the session-start `/handoff` GET can compose
+ /// the project brief (#176).
+ #[test]
+ fn marker_query_suffix_appends_briefing_opt_in() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ std::fs::write(
+ tmp.path().join(".ai-memory.toml"),
+ "workspace = \"acme\"\n[briefing]\ninject_on_session_start = true\nmax_chars = 6000\n",
+ )
+ .unwrap();
+ let qs = marker_query_suffix(tmp.path().to_str().unwrap(), None);
+ assert!(qs.contains("&briefing=true"), "{qs}");
+ assert!(qs.contains("&briefing_budget=6000"), "{qs}");
+ }
+
+ #[test]
+ fn marker_query_suffix_omits_briefing_when_unset() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ std::fs::write(
+ tmp.path().join(".ai-memory.toml"),
+ "workspace = \"acme\"\nproject = \"infra\"\n",
+ )
+ .unwrap();
+ let qs = marker_query_suffix(tmp.path().to_str().unwrap(), None);
+ assert!(!qs.contains("briefing"), "{qs}");
+ }
+
#[test]
fn marker_query_suffix_repo_root_non_git_keeps_project_implicit() {
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 9d63140f..941a7e7a 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -1088,7 +1088,9 @@ fn render_opencode_plugin(
/// and repo-root is resolved host-side via `repoRootProject`.
fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
let Some(default) = default_strategy else {
- return r#"function applyMarkerParams(url: URL, cwd: string | undefined): void {
+ return format!(
+ "{TS_TOML_FLAG}\n{}",
+ r#"function applyMarkerParams(url: URL, cwd: string | undefined): void {
const marker = findMarker(cwd);
if (!marker || !cwd) return;
url.searchParams.set("cwd", cwd);
@@ -1098,10 +1100,16 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
const project = tomlKey(body, "project");
const projectStrategy = tomlKey(body, "project_strategy");
const dropSubagent = tomlKey(body, "drop_subagent_captures");
+ const defaultGlobal = tomlFlag(body, "default_global");
+ const briefing = tomlFlag(body, "inject_on_session_start");
+ const briefingBudget = tomlFlag(body, "max_chars");
if (workspace) url.searchParams.set("workspace", workspace);
if (project) url.searchParams.set("project", project);
if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);
if (dropSubagent) url.searchParams.set("drop_subagent", dropSubagent);
+ if (defaultGlobal) url.searchParams.set("default_global", defaultGlobal);
+ if (briefing) url.searchParams.set("briefing", briefing);
+ 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);
@@ -1109,7 +1117,7 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
} catch (_e) {
}
}"#
- .to_string();
+ );
};
let body = r#"function applyMarkerParams(url: URL, cwd: string | undefined): void {
if (!cwd) return;
@@ -1118,6 +1126,9 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
let project: string | undefined;
let projectStrategy: string | undefined;
let dropSubagent: string | undefined;
+ let defaultGlobal: string | undefined;
+ let briefing: string | undefined;
+ let briefingBudget: string | undefined;
const marker = findMarker(cwd);
if (marker) {
try {
@@ -1126,6 +1137,9 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
project = tomlKey(body, "project");
projectStrategy = tomlKey(body, "project_strategy");
dropSubagent = tomlKey(body, "drop_subagent_captures");
+ defaultGlobal = tomlFlag(body, "default_global");
+ briefing = tomlFlag(body, "inject_on_session_start");
+ briefingBudget = tomlFlag(body, "max_chars");
} catch (_e) {
}
}
@@ -1138,13 +1152,30 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {
if (project) url.searchParams.set("project", project);
if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);
if (dropSubagent) url.searchParams.set("drop_subagent", dropSubagent);
+ if (defaultGlobal) url.searchParams.set("default_global", defaultGlobal);
+ if (briefing) url.searchParams.set("briefing", briefing);
+ if (briefingBudget) url.searchParams.set("briefing_budget", briefingBudget);
}"#;
format!(
- "const DEFAULT_PROJECT_STRATEGY = {};\n{body}",
+ "const DEFAULT_PROJECT_STRATEGY = {};\n{TS_TOML_FLAG}\n{body}",
ts_string_literal(default)
)
}
+/// `tomlFlag` mirrors the native hook's `parse_toml_flag`: unlike `tomlKey`
+/// (quoted strings only) it also accepts a bare token (`default_global =
+/// true`, `max_chars = 4000`), so section-style marker keys work whether or
+/// not the operator quotes the value. Emitted next to `applyMarkerParams`
+/// in every generated TypeScript integration.
+pub(crate) const TS_TOML_FLAG: &str = r#"function tomlFlag(text: string, key: string): string | undefined {
+ const re = new RegExp(`^\\s*${key}\\s*=\\s*(?:"([^"]*)"|([^#\\s]+))`);
+ for (const line of text.split(/\r?\n/)) {
+ const match = re.exec(line);
+ if (match) return match[1] ?? match[2];
+ }
+ return undefined;
+}"#;
+
fn build_opencode_plugin(
server_url: &str,
auth_token: Option<&str>,
@@ -3498,6 +3529,10 @@ model = "gpt-5"
assert!(plugin.contains("tomlKey(body, \"drop_subagent_captures\")"));
assert!(plugin.contains("url.searchParams.set(\"project_strategy\", projectStrategy)"));
assert!(plugin.contains("url.searchParams.set(\"drop_subagent\", dropSubagent)"));
+ assert!(plugin.contains("function tomlFlag"));
+ 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)"));
assert!(plugin.contains(
"applyMarkerParams(url, typeof payload.cwd === \"string\" ? payload.cwd : undefined);"
));
@@ -3617,6 +3652,10 @@ model = "gpt-5"
assert!(extension.contains("tomlKey(body, \"drop_subagent_captures\")"));
assert!(extension.contains("url.searchParams.set(\"project_strategy\", projectStrategy)"));
assert!(extension.contains("url.searchParams.set(\"drop_subagent\", dropSubagent)"));
+ assert!(extension.contains("function tomlFlag"));
+ 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)"));
assert!(extension.contains(
"applyMarkerParams(url, typeof payload.cwd === \"string\" ? payload.cwd : undefined);"
));
diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
index 4460d44a..876a1e6d 100644
--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
@@ -202,8 +202,11 @@ pub(crate) fn manifest_json() -> String {
/// `project` / `project_strategy` still win (§3.3). Mirrors the opencode/omp
/// `ts_apply_marker_params` in `install_hooks.rs`.
fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {
+ let toml_flag = super::install_hooks::TS_TOML_FLAG;
let Some(default) = default_strategy else {
- return r#"function applyMarkerParams(url: URL, cwd: string | undefined): void {
+ return format!(
+ "{toml_flag}\n{}",
+ r#"function applyMarkerParams(url: URL, cwd: string | undefined): void {
if (!cwd) return;
url.searchParams.set("cwd", cwd);
const marker = findMarker(cwd);
@@ -214,10 +217,16 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {
const project = tomlKey(body, "project");
const projectStrategy = tomlKey(body, "project_strategy");
const dropSubagent = tomlKey(body, "drop_subagent_captures");
+ const defaultGlobal = tomlFlag(body, "default_global");
+ const briefing = tomlFlag(body, "inject_on_session_start");
+ const briefingBudget = tomlFlag(body, "max_chars");
if (workspace) url.searchParams.set("workspace", workspace);
if (project) url.searchParams.set("project", project);
if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);
if (dropSubagent) url.searchParams.set("drop_subagent", dropSubagent);
+ if (defaultGlobal) url.searchParams.set("default_global", defaultGlobal);
+ if (briefing) url.searchParams.set("briefing", briefing);
+ 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);
@@ -225,7 +234,7 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {
} catch (_e) {
}
}"#
- .to_string();
+ );
};
let body = r#"function applyMarkerParams(url: URL, cwd: string | undefined): void {
if (!cwd) return;
@@ -234,6 +243,9 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {
let project: string | undefined;
let projectStrategy: string | undefined;
let dropSubagent: string | undefined;
+ let defaultGlobal: string | undefined;
+ let briefing: string | undefined;
+ let briefingBudget: string | undefined;
const marker = findMarker(cwd);
if (marker) {
try {
@@ -242,6 +254,9 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {
project = tomlKey(body, "project");
projectStrategy = tomlKey(body, "project_strategy");
dropSubagent = tomlKey(body, "drop_subagent_captures");
+ defaultGlobal = tomlFlag(body, "default_global");
+ briefing = tomlFlag(body, "inject_on_session_start");
+ briefingBudget = tomlFlag(body, "max_chars");
} catch (_e) {
}
}
@@ -254,9 +269,12 @@ fn apply_marker_params_ts(default_strategy: Option<&str>) -> String {
if (project) url.searchParams.set("project", project);
if (projectStrategy) url.searchParams.set("project_strategy", projectStrategy);
if (dropSubagent) url.searchParams.set("drop_subagent", dropSubagent);
+ if (defaultGlobal) url.searchParams.set("default_global", defaultGlobal);
+ if (briefing) url.searchParams.set("briefing", briefing);
+ if (briefingBudget) url.searchParams.set("briefing_budget", briefingBudget);
}"#;
format!(
- "const DEFAULT_PROJECT_STRATEGY = {};\n{body}",
+ "const DEFAULT_PROJECT_STRATEGY = {};\n{toml_flag}\n{body}",
ts_string_literal(default)
)
}
@@ -528,6 +546,10 @@ mod tests {
assert!(plugin.contains("tomlKey(body, \"project_strategy\")"));
assert!(plugin.contains("tomlKey(body, \"drop_subagent_captures\")"));
assert!(plugin.contains("url.searchParams.set(\"drop_subagent\", dropSubagent)"));
+ assert!(plugin.contains("function tomlFlag"));
+ 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)"));
assert!(plugin.contains("import { execFileSync } from \"node:child_process\";"));
assert!(plugin.contains("import { basename, dirname, join, resolve } from \"node:path\";"));
assert!(plugin.contains("function repoRootProject"));
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index bf184edd..87602316 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -718,6 +718,19 @@ pub struct HandoffQuery {
pub project: Option<String>,
/// Project strategy (mirror of `HookQuery.project_strategy`).
pub project_strategy: Option<String>,
+ /// Per-repo opt-in for the session-start project brief, forwarded by
+ /// the host-side hook from `.ai-memory.toml`'s
+ /// `[briefing] inject_on_session_start`. A truthy value makes this
+ /// endpoint append a compiled, char-budgeted brief of the project's
+ /// pinned / `_rules/` / `_slots/` pages after any pending handoff, so
+ /// the agent starts with the architecture context instead of
+ /// re-exploring the codebase (#176). Off when absent.
+ pub briefing: Option<String>,
+ /// Char budget for the brief, forwarded from the marker's
+ /// `[briefing] max_chars`. Clamped server-side to
+ /// [`BRIEF_BUDGET_MIN`], [`BRIEF_BUDGET_MAX`]; defaults to
+ /// [`BRIEF_BUDGET_DEFAULT`] when absent or unparsable.
+ pub briefing_budget: Option<String>,
}
/// Synchronous endpoint used by `session-start.sh` to discover any
@@ -772,15 +785,144 @@ async fn fetch_and_accept_handoff(
false,
)
.await?;
- let handoff = state
- .reader
- .latest_open_handoff(ws, proj, query.cwd)
- .await?;
- let Some(h) = handoff else {
- return Ok(None);
+ let handoff_md = {
+ let handoff = state
+ .reader
+ .latest_open_handoff(ws, proj, query.cwd)
+ .await?;
+ match handoff {
+ Some(h) => {
+ state.writer.accept_handoff(h.id, agent, None).await?;
+ Some(render_handoff_markdown(&h))
+ }
+ None => None,
+ }
+ };
+ // The brief is additive and non-destructive: unlike the handoff (a
+ // single-use slot consumed above), it is recomposed on every opted-in
+ // session start — exactly what a Claude Code `/clear` needs (#176).
+ let brief_md = if crate::payload::query_flag_truthy(query.briefing.as_deref()) {
+ let budget = query
+ .briefing_budget
+ .as_deref()
+ .and_then(|v| v.trim().parse::<usize>().ok())
+ .unwrap_or(BRIEF_BUDGET_DEFAULT)
+ .clamp(BRIEF_BUDGET_MIN, BRIEF_BUDGET_MAX);
+ let (core, recent) = state
+ .reader
+ .session_brief_pages(ws, proj, BRIEF_CORE_PAGES_LIMIT, BRIEF_RECENT_PAGES_LIMIT)
+ .await?;
+ render_session_brief(&core, &recent, budget)
+ } else {
+ None
};
- state.writer.accept_handoff(h.id, agent, None).await?;
- Ok(Some(render_handoff_markdown(&h)))
+ Ok(match (handoff_md, brief_md) {
+ (Some(h), Some(b)) => Some(format!("{h}\n{b}")),
+ (Some(h), None) => Some(h),
+ (None, Some(b)) => Some(b),
+ (None, None) => None,
+ })
+}
+
+/// Default char budget for the session-start brief (~1k tokens at the
+/// usual ~4 chars/token) — enough for a few rules pages without taxing
+/// every session start.
+const BRIEF_BUDGET_DEFAULT: usize = 4_000;
+/// Floor for the marker-supplied budget: below this the brief can't fit
+/// even one meaningful page plus the headers.
+const BRIEF_BUDGET_MIN: usize = 500;
+/// Ceiling for the marker-supplied budget: the brief is injected into
+/// EVERY opted-in session start, so an unbounded budget would let one
+/// marker line quietly burn five figures of tokens per `/clear`.
+const BRIEF_BUDGET_MAX: usize = 20_000;
+/// How many core (pinned / `_rules/` / `_slots/`) pages the store fetches;
+/// the char budget usually cuts earlier.
+const BRIEF_CORE_PAGES_LIMIT: usize = 24;
+/// How many recently-updated page titles the brief lists as follow-up
+/// pointers.
+const BRIEF_RECENT_PAGES_LIMIT: usize = 10;
+
+/// Truncate to at most `max` bytes without splitting a UTF-8 char.
+fn truncate_at_char_boundary(s: &str, max: usize) -> &str {
+ if s.len() <= max {
+ return s;
+ }
+ let mut end = max;
+ while end > 0 && !s.is_char_boundary(end) {
+ end -= 1;
+ }
+ &s[..end]
+}
+
+/// Render the marker-opted session-start project brief: core pages with
+/// bodies (pinned first) under a char budget, then recently-updated titles
+/// as follow-up pointers. Returns `None` for an empty project so the hook
+/// injects nothing rather than an empty scaffold.
+fn render_session_brief(
+ core: &[ai_memory_store::BriefPageBody],
+ recent: &[ai_memory_store::BriefingPage],
+ budget_chars: usize,
+) -> Option<String> {
+ if core.is_empty() && recent.is_empty() {
+ return None;
+ }
+ let mut buf = String::with_capacity(budget_chars.min(8_192));
+ buf.push_str(
+ "> 🧭 **ai-memory: project brief** (auto-injected — `.ai-memory.toml [briefing]`)\n",
+ );
+
+ let mut omitted: Vec<&str> = Vec::new();
+ for page in core {
+ let pin = if page.pinned { " 📌" } else { "" };
+ let header = format!(
+ "\n## {title}{pin} (`{path}`)\n",
+ title = page.title,
+ path = page.path,
+ );
+ // Reserve room for the footer sections so a single huge page
+ // can't crowd out the recent-pages pointers entirely.
+ let used = buf.len();
+ if used + header.len() >= budget_chars {
+ omitted.push(&page.path);
+ continue;
+ }
+ let remaining = budget_chars - used - header.len();
+ let body = page.body.trim();
+ buf.push_str(&header);
+ if body.len() > remaining {
+ buf.push_str(truncate_at_char_boundary(body, remaining));
+ buf.push_str("\n_[truncated by `[briefing] max_chars`]_\n");
+ } else {
+ buf.push_str(body);
+ buf.push('\n');
+ }
+ }
+ if !omitted.is_empty() {
+ buf.push_str("\n**Core pages omitted by budget** (read via `memory_query` if needed)\n");
+ for path in omitted {
+ buf.push_str(&format!("- `{path}`\n"));
+ }
+ }
+ if !recent.is_empty() {
+ buf.push_str("\n**Recently updated pages** (titles only)\n");
+ for page in recent {
+ buf.push_str(&format!(
+ "- {title} (`{path}`, {kind}, {ts})\n",
+ title = page.title,
+ path = page.path,
+ kind = page.kind,
+ ts = page.updated_at,
+ ));
+ }
+ }
+ buf.push_str(
+ "\n_**To the receiving agent:** this brief is compiled from this \
+ project's pinned / `_rules/` / `_slots/` wiki pages. Treat it as \
+ current architecture and standing-rule context — do NOT re-explore \
+ the codebase to rediscover what is already stated here. Call \
+ `memory_query` for detail beyond this brief._\n",
+ );
+ Some(buf)
}
fn render_handoff_markdown(h: &Handoff) -> String {
@@ -4435,6 +4577,8 @@ mod tests {
workspace: Some("acme".into()),
project: None,
project_strategy: None,
+ briefing: None,
+ briefing_budget: None,
},
None,
)
@@ -4447,6 +4591,184 @@ mod tests {
);
}
+ fn brief_page(
+ ws: ai_memory_core::WorkspaceId,
+ proj: ai_memory_core::ProjectId,
+ path: &str,
+ body: &str,
+ pinned: bool,
+ ) -> ai_memory_core::NewPage {
+ ai_memory_core::NewPage {
+ workspace_id: ws,
+ project_id: proj,
+ path: ai_memory_core::PagePath::new(path).unwrap(),
+ title: path.trim_end_matches(".md").to_string(),
+ body: body.into(),
+ tier: ai_memory_core::Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned,
+ links: Vec::new(),
+ author_id: None,
+ }
+ }
+
+ /// `briefing=true` on the `/handoff` query returns the compiled project
+ /// brief even with NO pending handoff — the `/clear` case of #176 — and
+ /// a truthy value combined with a pending handoff returns both, handoff
+ /// first. A non-truthy value leaves the endpoint's contract unchanged.
+ #[tokio::test]
+ async fn handoff_query_briefing_flag_appends_project_brief() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let cwd = "/home/u/briefed-repo";
+
+ let (ws, proj) = resolve_project_ids(
+ &state,
+ Some(cwd),
+ None,
+ None,
+ ProjectStrategy::Basename,
+ &ai_memory_core::ActorKey::default(),
+ )
+ .await
+ .unwrap();
+ state
+ .writer
+ .upsert_page(brief_page(
+ ws,
+ proj,
+ "_rules/style.md",
+ "always use the single writer actor",
+ false,
+ ))
+ .await
+ .unwrap();
+
+ let query = |briefing: Option<&str>| HandoffQuery {
+ agent: Some("claude-code".into()),
+ cwd: Some(cwd.into()),
+ workspace: None,
+ project: None,
+ project_strategy: None,
+ briefing: briefing.map(str::to_owned),
+ briefing_budget: None,
+ };
+
+ // Non-truthy opt-in: no handoff pending, nothing to inject.
+ let rendered = fetch_and_accept_handoff(&state, query(Some("false")), None)
+ .await
+ .unwrap();
+ assert!(
+ rendered.is_none(),
+ "non-truthy briefing flag must not inject anything"
+ );
+
+ // Truthy opt-in, no pending handoff: brief alone (the /clear case).
+ let rendered = fetch_and_accept_handoff(&state, query(Some("true")), None)
+ .await
+ .unwrap()
+ .expect("brief must be injected without a pending handoff");
+ assert!(
+ rendered.contains("project brief") && rendered.contains("single writer actor"),
+ "brief must carry the rules page body: {rendered}"
+ );
+ assert!(
+ rendered.contains("do NOT re-explore"),
+ "brief must end with the agent-facing reading instructions"
+ );
+
+ // Truthy opt-in with a pending handoff: handoff first, brief after.
+ state
+ .writer
+ .insert_handoff(NewHandoff {
+ workspace_id: ws,
+ project_id: proj,
+ from_session_id: None,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: Some(std::path::PathBuf::from(cwd)),
+ summary: "resume the auth refactor".to_string(),
+ open_questions: Vec::new(),
+ next_steps: Vec::new(),
+ files_touched: Vec::new(),
+ })
+ .await
+ .unwrap();
+ let rendered = fetch_and_accept_handoff(&state, query(Some("true")), None)
+ .await
+ .unwrap()
+ .expect("handoff + brief must both be injected");
+ let handoff_pos = rendered.find("resume the auth refactor").unwrap();
+ let brief_pos = rendered.find("project brief").unwrap();
+ assert!(
+ handoff_pos < brief_pos,
+ "pending handoff must precede the brief"
+ );
+ }
+
+ /// The brief renderer respects the char budget: an over-budget body is
+ /// truncated with a visible note, fully crowded-out core pages are
+ /// listed as omitted, and an empty project renders nothing at all.
+ #[test]
+ fn render_session_brief_enforces_budget() {
+ let core = vec![
+ ai_memory_store::BriefPageBody {
+ path: "_rules/a.md".into(),
+ title: "a".into(),
+ body: "x".repeat(2_000),
+ pinned: true,
+ updated_at: "2026-07-12T00:00:00Z".into(),
+ },
+ ai_memory_store::BriefPageBody {
+ path: "_rules/b.md".into(),
+ title: "b".into(),
+ body: "never truncated into view".into(),
+ pinned: false,
+ updated_at: "2026-07-12T00:00:00Z".into(),
+ },
+ ];
+ let recent = vec![ai_memory_store::BriefingPage {
+ path: "concepts/q.md".into(),
+ title: "queue".into(),
+ kind: "fact".into(),
+ updated_at: "2026-07-12T00:00:00Z".into(),
+ }];
+
+ let out = render_session_brief(&core, &recent, BRIEF_BUDGET_MIN).unwrap();
+ assert!(
+ out.contains("[truncated by `[briefing] max_chars`]"),
+ "over-budget body must be visibly truncated: {out}"
+ );
+ assert!(
+ out.contains("Core pages omitted by budget") && out.contains("`_rules/b.md`"),
+ "crowded-out core pages must be listed by path: {out}"
+ );
+ assert!(
+ !out.contains("never truncated into view"),
+ "omitted page bodies must not leak: {out}"
+ );
+ assert!(
+ out.contains("Recently updated pages") && out.contains("concepts/q.md"),
+ "recent pointers survive the budget cut: {out}"
+ );
+
+ // Multi-byte safety: a body of 4-byte chars must cut on a boundary.
+ let emoji_core = vec![ai_memory_store::BriefPageBody {
+ path: "_rules/e.md".into(),
+ title: "e".into(),
+ body: "🦀".repeat(1_000),
+ pinned: false,
+ updated_at: "2026-07-12T00:00:00Z".into(),
+ }];
+ let out = render_session_brief(&emoji_core, &[], BRIEF_BUDGET_MIN).unwrap();
+ assert!(out.is_char_boundary(out.len()), "must remain valid UTF-8");
+
+ assert!(
+ render_session_brief(&[], &[], BRIEF_BUDGET_DEFAULT).is_none(),
+ "empty project must inject nothing"
+ );
+ }
+
#[tokio::test]
async fn handoff_with_no_marker_uses_cwd_basename_project() {
let tmp = TempDir::new().unwrap();
@@ -4488,6 +4810,8 @@ mod tests {
workspace: None,
project: None,
project_strategy: None,
+ briefing: None,
+ briefing_budget: None,
},
None,
)
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 16903f9a..631db471 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -36,7 +36,7 @@ pub use decay::{DecayParams, retention_score};
pub use error::{StoreError, StoreResult};
pub use ops::{DeleteWorkspaceSummary, EmbeddingWrite, MoveSummary, PurgeSummary, ReorgSummary};
pub use reader::{
- ActivityWindow, AutoImproveCandidateSession, BriefingPage, BriefingSnapshot,
+ ActivityWindow, AutoImproveCandidateSession, BriefPageBody, BriefingPage, BriefingSnapshot,
ContaminationFinding, ContaminationReport, ContaminationSummary, DecayCandidate,
DerivedIndexStatus, EmbeddingTripleCount, HealthDetail, HealthPage, ObservationHit,
OpenSession, PageAuthor, PageHit, PageHitWithMeta, PageLinks, PageMeta, PageSummary,
@@ -1609,6 +1609,92 @@ mod tests {
);
}
+ /// `session_brief_pages` returns pinned / `_rules/` / `_slots/` pages
+ /// WITH bodies (pinned first, then path order), recent titles for the
+ /// whole project, and never leaks a sibling project's pages.
+ #[tokio::test]
+ async fn session_brief_pages_selects_core_pages_and_isolates_projects() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "app", None)
+ .await
+ .unwrap();
+ let other = store
+ .writer
+ .get_or_create_project(ws, "other", None)
+ .await
+ .unwrap();
+
+ let mut adr = sample_page(ws, proj, "decisions/adr-001.md", "single writer actor");
+ adr.pinned = true;
+ store.writer.upsert_page(adr).await.unwrap();
+ store
+ .writer
+ .upsert_page(sample_page(
+ ws,
+ proj,
+ "_rules/style.md",
+ "no unwrap in runtime",
+ ))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(sample_page(ws, proj, "_slots/focus.md", "shipping v2 auth"))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(sample_page(ws, proj, "concepts/queue.md", "ordinary page"))
+ .await
+ .unwrap();
+ store
+ .writer
+ .upsert_page(sample_page(ws, other, "_rules/other.md", "sibling rule"))
+ .await
+ .unwrap();
+
+ let (core, recent) = store
+ .reader
+ .session_brief_pages(ws, proj, 24, 10)
+ .await
+ .unwrap();
+
+ let core_paths: Vec<&str> = core.iter().map(|p| p.path.as_str()).collect();
+ assert_eq!(
+ core_paths,
+ vec!["decisions/adr-001.md", "_rules/style.md", "_slots/focus.md"],
+ "core = pinned first, then _rules/ + _slots/ by path; no ordinary pages"
+ );
+ assert!(core[0].pinned, "pinned flag must survive the round-trip");
+ assert_eq!(
+ core[1].body, "no unwrap in runtime",
+ "core pages carry bodies"
+ );
+
+ let recent_paths: Vec<&str> = recent.iter().map(|p| p.path.as_str()).collect();
+ assert_eq!(
+ recent.len(),
+ 4,
+ "recent lists every latest page in the project"
+ );
+ assert!(
+ recent_paths.contains(&"concepts/queue.md"),
+ "ordinary pages appear as recent pointers"
+ );
+ assert!(
+ !recent_paths.contains(&"_rules/other.md") && core.len() == 3,
+ "sibling project pages must not leak into the brief"
+ );
+ }
+
#[tokio::test]
async fn cross_project_links_surface_in_graph_briefing_and_lint() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 884ec25c..73c103f2 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -373,6 +373,25 @@ pub struct BriefingPage {
pub updated_at: String,
}
+/// One core page of the session-start project brief — body included,
+/// because the brief is injected as agent context and the whole point is
+/// sparing the agent a re-exploration round-trip. Returned by
+/// [`ReaderPool::session_brief_pages`].
+#[derive(Debug, Clone, Serialize)]
+pub struct BriefPageBody {
+ /// Relative wiki path.
+ pub path: String,
+ /// Page title (first H1 / frontmatter title).
+ pub title: String,
+ /// Full markdown body of the latest version. The hooks-side renderer
+ /// applies the char budget; the store returns it whole.
+ pub body: String,
+ /// Whether the page is pinned (decay-immune, operator-curated).
+ pub pinned: bool,
+ /// ISO-8601 timestamp of the last update.
+ pub updated_at: String,
+}
+
/// One row per (workspace, project) with aggregate stats.
/// Returned by [`ReaderPool::list_projects_with_stats`].
#[derive(Debug, Clone, Serialize)]
@@ -2098,6 +2117,101 @@ impl ReaderPool {
.await
}
+ /// Fetch the pages that make up a session-start project brief: the
+ /// "core" pages WITH bodies (pinned, plus everything under `_rules/`
+ /// and `_slots/` — the operator-curated, highest-signal memory), and
+ /// the most-recently-updated page titles WITHOUT bodies (pointers the
+ /// agent can follow up on via `memory_query`).
+ ///
+ /// Core pages are ordered pinned-first then by path, so a char-budget
+ /// cut in the renderer drops the least-curated content last. Both
+ /// limits are clamped defensively; the renderer applies the actual
+ /// byte budget.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn session_brief_pages(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ core_pages_limit: usize,
+ recent_pages_limit: usize,
+ ) -> StoreResult<(Vec<BriefPageBody>, Vec<BriefingPage>)> {
+ let core_limit = core_pages_limit.clamp(1, 100) as i64;
+ let recent_limit = recent_pages_limit.clamp(1, 100) as i64;
+ self.with_conn(move |conn| {
+ let mut core_stmt = conn.prepare_cached(
+ "SELECT path, title, body, pinned, updated_at \
+ FROM pages \
+ WHERE workspace_id = ?1 AND project_id = ?2 AND is_latest = 1 \
+ AND (pinned = 1 OR path GLOB '_rules/*' OR path GLOB '_slots/*') \
+ ORDER BY pinned DESC, path ASC \
+ LIMIT ?3",
+ )?;
+ let core: Vec<BriefPageBody> = core_stmt
+ .query_map(
+ params![workspace_id.as_bytes(), project_id.as_bytes(), core_limit],
+ |row| {
+ let updated_us: i64 = row.get(4)?;
+ Ok((
+ row.get::<_, String>(0)?,
+ row.get::<_, String>(1)?,
+ row.get::<_, String>(2)?,
+ row.get::<_, i64>(3)? != 0,
+ updated_us,
+ ))
+ },
+ )?
+ .collect::<Result<Vec<_>, _>>()?
+ .into_iter()
+ .map(|(path, title, body, pinned, updated_us)| {
+ jiff::Timestamp::from_microsecond(updated_us)
+ .map(|ts| BriefPageBody {
+ path,
+ title,
+ body,
+ pinned,
+ updated_at: ts.to_string(),
+ })
+ .map_err(|e| {
+ StoreError::Memory(ai_memory_core::MemoryError::MalformedRecord(
+ format!("bad updated_at: {e}"),
+ ))
+ })
+ })
+ .collect::<StoreResult<Vec<_>>>()?;
+
+ let mut recent_stmt = conn.prepare_cached(
+ "SELECT path, title, \
+ COALESCE( \
+ json_extract(frontmatter_json, '$.kind'), \
+ CASE \
+ WHEN path LIKE '\\_rules/%' ESCAPE '\\' THEN 'rule' \
+ WHEN path LIKE 'decisions/%' THEN 'decision' \
+ WHEN path LIKE 'gotchas/%' THEN 'gotcha' \
+ ELSE 'fact' \
+ END \
+ ) AS kind, \
+ updated_at \
+ FROM pages \
+ WHERE workspace_id = ?1 AND project_id = ?2 AND is_latest = 1 \
+ ORDER BY updated_at DESC \
+ LIMIT ?3",
+ )?;
+ let recent: Vec<BriefingPage> = recent_stmt
+ .query_map(
+ params![workspace_id.as_bytes(), project_id.as_bytes(), recent_limit],
+ briefing_page_from_row,
+ )?
+ .collect::<Result<Vec<_>, _>>()?
+ .into_iter()
+ .collect::<Result<Vec<_>, _>>()?;
+
+ Ok((core, recent))
+ })
+ .await
+ }
+
/// Return the latest open handoff for the workspace, aggregating
/// across all of its projects (no project filter).
///
diff --git a/docs/marker-file.md b/docs/marker-file.md
index e0badd40..0d68f5f9 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -33,8 +33,8 @@ handoff lookups.
The marker path is shared by the POSIX/PowerShell hook scripts and the
generated OpenCode / OMP / OpenClaw TypeScript integrations. In all cases,
hook capture and handoff lookup send the same `cwd`, `workspace`, `project`,
-`project_strategy`, and `drop_subagent` query params to the server when a
-marker is present;
+`project_strategy`, `drop_subagent`, `default_global`, `briefing`, and
+`briefing_budget` query params to the server when a marker declares them;
handoff lookup also sends `cwd` when no marker exists so the default
`project = basename(cwd)` route works consistently.
@@ -74,6 +74,25 @@ drop_subagent_captures = "true"
# pages still appear, annotated, among the global results).
[recall]
default_global = "true"
+
+# Optional. Inject a compiled project brief at session start (and after a
+# context clear — Claude Code re-fires SessionStart on /clear): the
+# session-start handoff fetch also returns this project's pinned /
+# `_rules/` / `_slots/` wiki pages (bodies included) plus recently-updated
+# page titles, so the agent starts with the architecture context instead
+# of re-exploring the codebase. Appended AFTER any pending handoff, and
+# unlike the handoff it is not consumed — it is recomposed every opted-in
+# session start. Only agents whose session-start hook injects stdout as
+# context benefit (Claude Code, Codex, OpenCode, …). Off by default: the
+# brief costs tokens on EVERY session start, so opt in per repo.
+[briefing]
+inject_on_session_start = "true"
+
+# Optional. Char budget for the brief (~4 chars per token). Bodies over
+# budget are truncated with a visible note; crowded-out core pages are
+# listed by path so the agent can `memory_query` them. Clamped
+# server-side to [500, 20000]; defaults to 4000.
+max_chars = 4000
```
**Naming rules** for `workspace` and `project`, validated server-side:
@@ -88,6 +107,11 @@ defensively but the server's regex is the source of truth.
`project_strategy` accepts `repo-root` (or `repo_root`) only. Unknown
values are ignored and behave like the default `basename(cwd)` strategy.
+`default_global` and `inject_on_session_start` accept a truthy value
+(`true` / `1` / `yes` / `on`, quoted or bare — section-style keys are
+parsed leniently); anything else behaves as absent. `max_chars` is a
+plain integer.
+
`drop_subagent_captures` accepts a truthy string (`"true"` / `"1"` /
`"yes"` / `"on"`); any other value, or its absence, leaves this project's
subagent captures stored as usual. Top-level (non-subagent) sessions are