Files
claude-config/agent-shared/sync-memory-block.sh
T

63 lines
2.2 KiB
Bash
Executable File

#!/usr/bin/env bash
# Sync the shared "Persistent Agent Memory" block into every agent file that
# carries the markers. Source of truth: agent-shared/memory-system.md.
# The block is inlined (agent prompts have no @import support), so this script
# is what keeps the copies from silently diverging.
#
# sync-memory-block.sh --check # verify all agents match canonical (exit 1 on drift)
# sync-memory-block.sh --write # rewrite each agent's block from canonical
#
# {{AGENT_NAME}} in the template is replaced with the agent's filename stem
# (which is also its agent-memory/ directory name).
set -euo pipefail
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
canonical="$here/memory-system.md"
agents_dir="$(cd "$here/../agents" && pwd)"
begin='BEGIN shared:memory-system'
end='END shared:memory-system'
mode="${1:---check}"
[ "$mode" = "--check" ] || [ "$mode" = "--write" ] || { echo "usage: $0 [--check|--write]" >&2; exit 2; }
[ -f "$canonical" ] || { echo "missing canonical template: $canonical" >&2; exit 2; }
drift=0
shopt -s nullglob
for file in "$agents_dir"/*.md; do
grep -q "$begin" "$file" || continue
name="$(basename "$file" .md)"
if [ "$(grep -c "$begin" "$file")" -ne 1 ] || [ "$(grep -c "$end" "$file")" -ne 1 ]; then
echo "SKIP $name: expected exactly one $begin and one $end marker" >&2
drift=1; continue
fi
expected="$(sed "s/{{AGENT_NAME}}/$name/g" "$canonical")"
current="$(awk -v e="$end" -v b="$begin" '$0~e{f=0} f{print} $0~b{f=1}' "$file")"
if [ "$current" = "$expected" ]; then
[ "$mode" = "--write" ] && echo "ok $name (already in sync)"
continue
fi
if [ "$mode" = "--check" ]; then
echo "DRIFT $name:"
diff <(printf '%s\n' "$current") <(printf '%s\n' "$expected") || true
drift=1
continue
fi
# --write: pre (through BEGIN marker) + rendered block + post (from END marker)
tmp="$(mktemp)"
{ awk -v b="$begin" '1; $0~b{exit}' "$file"
printf '%s\n' "$expected"
awk -v e="$end" '$0~e{p=1} p' "$file"
} > "$tmp"
mv "$tmp" "$file"
echo "wrote $name"
done
if [ "$mode" = "--check" ]; then
[ "$drift" -eq 0 ] && echo "all agent memory blocks in sync with $canonical" || { echo "drift detected — run: $0 --write" >&2; exit 1; }
fi