Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
hooks(kimi): briefing once per session in the script path + docs
Lucas Oliveira6f9c89402069
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 25165fd4..cc33e0bd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -30,6 +30,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`user-prompt-submit` event token alongside `user-prompt` for kimi handoffdelivery. Re-run `ai-memory install-hooks --agent kimi-code --apply` afterupgrading.+- The `[briefing]` compiled project brief is now gated to once per session+ for Kimi Code: it rides the first user prompt (kimi discards SessionStart+ hook stdout, so session-start delivery is impossible) and later prompts+ keep fetching the handoff without the briefing params, so the server no+ longer recomposes the brief on every prompt. Re-briefing after `/clear`+ is not supported in v1.## [1.17.3] - 2026-07-22diff --git a/docs/marker-file.md b/docs/marker-file.mdindex 4c300ae3..d8bdda06 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -86,6 +86,10 @@ default_global = "true"# 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.+# Kimi Code note: kimi discards SessionStart hook stdout, so there the+# brief is delivered on the FIRST user prompt of the session instead+# (once per session, same as Claude); re-briefing after /clear is not+# supported in v1.[briefing]inject_on_session_start = "true"diff --git a/hooks/_lib.sh b/hooks/_lib.shindex 78159a07..64056b21 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -37,6 +37,18 @@ ai_memory_parse_toml_key() {"$file" | head -n 1}+# Like ai_memory_parse_toml_key but also accepts a BARE value+# (`key = true` / `key = 6000`), so section-style flags such as+# `[briefing] inject_on_session_start = true` work quoted or not.+# Parity with `parse_toml_flag` in hook_capture.rs: line-based (section+# headers are ignored), first match wins, trailing `# comment` stripped.+ai_memory_parse_toml_flag() {+ file="$1"; key="$2"+ [ -f "$file" ] || return 0+ sed -n -E "s/^[[:space:]]*${key}[[:space:]]*=[[:space:]]*\"?([^\"#]*)\"?.*/\1/p" \+ "$file" | head -n 1 | sed 's/[[:space:]]*$//'+}+# 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@@ -206,6 +218,35 @@ ai_memory_marker_qs() {printf '%s' "$qs"}+# Build `&briefing=<v>[&briefing_budget=<v>]` from the `[briefing]` section+# of the marker walked up from "$1" (inject_on_session_start + optional+# max_chars). Prints nothing when cwd is absent or the repo did not opt in.+# NOT part of ai_memory_marker_qs on purpose: agents that deliver the brief+# once per session (kimi-code, via the first user prompt — kimi discards+# SessionStart hook stdout) append this only on the first fetch, so the+# server does not recompose the brief on every request. Truthiness and the+# char-budget clamp are decided server-side.+ai_memory_briefing_qs() {+ cwd="$1"+ [ -z "$cwd" ] && return 0+ marker=$(ai_memory_find_marker "$cwd")+ [ -n "$marker" ] || return 0+ qs=""+ briefing=$(ai_memory_parse_toml_flag "$marker" inject_on_session_start)+ budget=$(ai_memory_parse_toml_flag "$marker" max_chars)+ [ -n "$briefing" ] && qs="&briefing=$(ai_memory_url_encode "$briefing")"+ [ -n "$budget" ] && qs="${qs}&briefing_budget=$(ai_memory_url_encode "$budget")"+ printf '%s' "$qs"+}++# Path of the once-per-session "brief delivered" marker for "$1" (a session+# id or a caller-built fallback key), sanitized to a safe file name under+# the shared state dir.+ai_memory_briefed_file() {+ key=$(printf '%s' "$1" | tr -c 'A-Za-z0-9._-' '_')+ printf '%s/briefed/%s' "$(ai_memory_state_dir)" "$key"+}+# Local bridge state for agents whose hook payloads do not carry a session id.# The value is intentionally non-secret; the server hashes non-UUID ids into its# typed SessionId domain. `AI_MEMORY_SESSION_ID` may be supplied by advanceddiff --git a/hooks/kimi-code/user-prompt-submit.ps1 b/hooks/kimi-code/user-prompt-submit.ps1index 3ba15eb6..4233b81a 100644--- a/hooks/kimi-code/user-prompt-submit.ps1+++ b/hooks/kimi-code/user-prompt-submit.ps1@@ -1,6 +1,9 @@# Kimi Code injects UserPromptSubmit hook stdout as a user message# (origin hook_result) before the turn, so the pending handoff is-# fetched here. Empty stdout injects nothing.+# fetched here. Empty stdout injects nothing. The compiled project+# brief ([briefing] inject_on_session_start) rides the FIRST prompt of+# the session only — kimi discards SessionStart hook stdout, so this+# is the once-per-session parity with Claude's SessionStart brief.. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"-Invoke-AiMemoryHook -Event "user-prompt" -Agent "kimi-code" -FetchHandoff+Invoke-AiMemoryHook -Event "user-prompt" -Agent "kimi-code" -FetchHandoff -BriefingOncePerSessionexit 0diff --git a/hooks/kimi-code/user-prompt-submit.sh b/hooks/kimi-code/user-prompt-submit.shindex 756f4d40..03b03cf1 100755--- a/hooks/kimi-code/user-prompt-submit.sh+++ b/hooks/kimi-code/user-prompt-submit.sh@@ -8,6 +8,13 @@# deliver it: kimi-code discards SessionStart hook stdout (v0.28.1,# packages/agent-core/src/session/index.ts). Empty stdout injects# nothing, so print only when a handoff exists.+# 3. Delivers the compiled project brief ([briefing]+# inject_on_session_start) on the FIRST prompt of the session only —+# parity with Claude's once-per-SessionStart brief. The handoff fetch+# keeps happening on every prompt (cheap, self-limiting: empty body+# when nothing is pending), but without the briefing params, so the+# server does not recompose the brief per prompt. The marker survives+# /clear, so re-briefing after a context clear is not supported in v1._lib_dir="$(dirname "$0")"[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/..". "$_lib_dir/_lib.sh"@@ -20,9 +27,26 @@ SESSION_ID=$(ai_memory_extract_session_id "$PAYLOAD")SESSION_QS=""[ -n "$SESSION_ID" ] && SESSION_QS="&session_id=$(ai_memory_url_encode "$SESSION_ID")"+# Once-per-session briefing gate, keyed by the native session id (kimi+# always sends `sessionId`); without one, a stable hash of agent+cwd so a+# session-less payload still briefs only once per checkout.+BRIEF_KEY="$SESSION_ID"+if [ -z "$BRIEF_KEY" ]; then+ BRIEF_KEY="kimi-code-$(printf '%s' "kimi-code:$CWD" | cksum | awk '{print $1}')"+fi+BRIEF_FILE=$(ai_memory_briefed_file "$BRIEF_KEY")+BRIEF_QS=""+[ -f "$BRIEF_FILE" ] || BRIEF_QS=$(ai_memory_briefing_qs "$CWD")+printf '%s' "$PAYLOAD" \| ai_memory_post_hook "$SERVER/hook?event=user-prompt&agent=kimi-code${QS}" >/dev/null 2>&1 || true-HANDOFF=$(ai_memory_get_handoff "$SERVER/handoff?agent=kimi-code${QS}${SESSION_QS}" 2>/dev/null || true)+HANDOFF=$(ai_memory_get_handoff "$SERVER/handoff?agent=kimi-code${QS}${SESSION_QS}${BRIEF_QS}" 2>/dev/null || true)+# Mark the session as briefed only AFTER the GET completed — success or+# error. Fail-open on purpose: with the server down, re-sending the+# brief-flagged request on every prompt would deliver nothing anyway, and+# the one lost brief returns on the next session.+mkdir -p "$(dirname "$BRIEF_FILE")" 2>/dev/null || true+: > "$BRIEF_FILE" 2>/dev/null || true[ -n "$HANDOFF" ] && printf '%s\n' "$HANDOFF"exit 0diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index 7b6f2bfb..3556923e 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -61,6 +61,49 @@ function Get-AiMemoryTomlKey {return $null}+# Like Get-AiMemoryTomlKey but also accepts a BARE value (`key = true` /+# `key = 6000`), so section-style flags such as+# `[briefing] inject_on_session_start = true` work quoted or not. Parity+# with `parse_toml_flag` in hook_capture.rs: line-based, first match wins,+# trailing `# comment` stripped.+function Get-AiMemoryTomlFlag {+ param([string] $File, [string] $Key)+ if (-not (Test-Path $File -PathType Leaf)) { return $null }+ foreach ($line in Get-Content $File) {+ $m = [regex]::Match($line, "^\s*$Key\s*=\s*`"?([^`"#]*)`"?\s*(#.*)?$")+ if ($m.Success) { return $m.Groups[1].Value.Trim() }+ }+ return $null+}++# Build `&briefing=<v>[&briefing_budget=<v>]` from the `[briefing]` section+# of the marker walked up from $Cwd. Returns "" when the repo did not opt+# in. Used by agents that deliver the compiled project brief once per+# session (kimi-code, via the first user prompt — kimi discards+# SessionStart hook stdout) so the server does not recompose the brief on+# every request. Truthiness and the char-budget clamp are server-side.+function Get-AiMemoryBriefingQuery {+ param([string] $Cwd)+ if (-not $Cwd) { return "" }+ $marker = Get-AiMemoryMarkerToml -Cwd $Cwd+ if (-not $marker) { return "" }+ $qs = ""+ $briefing = Get-AiMemoryTomlFlag -File $marker -Key "inject_on_session_start"+ $budget = Get-AiMemoryTomlFlag -File $marker -Key "max_chars"+ if ($briefing) { $qs += "&briefing=$([uri]::EscapeDataString($briefing))" }+ if ($budget) { $qs += "&briefing_budget=$([uri]::EscapeDataString($budget))" }+ return $qs+}++# Path of the once-per-session "brief delivered" marker for $Key (a session+# id or a caller-built fallback key), sanitized to a safe file name under+# the shared state dir.+function Get-AiMemoryBriefedFile {+ param([string] $Key)+ $safe = ($Key -replace '[^A-Za-z0-9._-]', '_')+ return (Join-Path (Join-Path (Get-AiMemoryStateDir) "briefed") $safe)+}+# Resolve the basename of the MAIN git repository root for $Cwd, following the# worktree commondir pointer so every linked worktree collapses to one stable# name. Mirrors the POSIX `ai_memory_repo_root_project`: a containerized server@@ -182,7 +225,14 @@ function Invoke-AiMemoryHook {[Parameter(Mandatory = $true)] [string] $Event,[Parameter(Mandatory = $true)] [string] $Agent,[switch] $FetchHandoff,- [switch] $AntigravityPreInvocationOutput+ [switch] $AntigravityPreInvocationOutput,+ # Deliver the `[briefing]` compiled project brief on the FIRST+ # handoff fetch of a session only (kimi-code's user-prompt path:+ # kimi discards SessionStart hook stdout, so the brief rides the+ # first prompt — parity with Claude's once-per-SessionStart brief).+ # Later fetches keep the handoff but drop the briefing params so the+ # server does not recompose the brief per prompt.+ [switch] $BriefingOncePerSession)$Server = if ($env:AI_MEMORY_HOOK_URL) { $env:AI_MEMORY_HOOK_URL } else { "http://127.0.0.1:49374" }@@ -233,11 +283,28 @@ function Invoke-AiMemoryHook {}} catch {}+ # Once-per-session briefing gate, keyed by the native session id+ # (kimi always sends `sessionId`); without one, a stable hash of+ # agent+cwd so a session-less payload still briefs only once.+ $BriefQS = ""+ $BriefFile = $null+ if ($BriefingOncePerSession) {+ $BriefKey = [string]$NativeSessionId+ if (-not $BriefKey) {+ $Sha = [System.Security.Cryptography.SHA256]::Create()+ $Bytes = $Sha.ComputeHash([System.Text.Encoding]::UTF8.GetBytes("$Agent`n$Cwd"))+ $BriefKey = (($Bytes | ForEach-Object { $_.ToString("x2") }) -join "")+ }+ $BriefFile = Get-AiMemoryBriefedFile -Key $BriefKey+ if (-not (Test-Path $BriefFile -PathType Leaf)) {+ $BriefQS = Get-AiMemoryBriefingQuery -Cwd $Cwd+ }+ }try {$Response = Invoke-WebRequest `-UseBasicParsing `-TimeoutSec 2 `- -Uri "$Server/handoff?agent=$Agent$QS$NativeSessionQS" `+ -Uri "$Server/handoff?agent=$Agent$QS$NativeSessionQS$BriefQS" `-Headers $Headersif ($null -ne $Response -and $Response.Content) {if ($AntigravityPreInvocationOutput) {@@ -256,6 +323,14 @@ function Invoke-AiMemoryHook {[Console]::Out.Write("{}")}}+ # Mark the session as briefed only AFTER the GET completed —+ # success or error (fail-open: with the server down, re-sending the+ # brief-flagged request on every prompt would deliver nothing+ # anyway, and the one lost brief returns on the next session).+ if ($BriefFile) {+ New-Item -ItemType Directory -Force -Path (Split-Path $BriefFile -Parent) -ErrorAction SilentlyContinue | Out-Null+ New-Item -ItemType File -Force -Path $BriefFile -ErrorAction SilentlyContinue | Out-Null+ }} elseif ($AntigravityPreInvocationOutput) {[Console]::Out.Write("{}")}