2026-02-04 11:06:13 +00:00
package agent
import (
2026-04-24 10:14:28 +00:00
"context"
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
"errors"
2026-02-04 11:06:13 +00:00
"fmt"
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
"io/fs"
2026-02-04 11:06:13 +00:00
"os"
"path/filepath"
2026-02-10 08:05:23 +00:00
"runtime"
2026-02-27 08:35:07 +00:00
"slices"
2026-02-10 08:05:23 +00:00
"strings"
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
"sync"
2026-02-04 11:06:13 +00:00
"time"
2026-04-21 08:30:02 +00:00
"unicode/utf8"
2026-02-04 11:06:13 +00:00
2026-03-10 09:42:05 +00:00
"github.com/sipeed/picoclaw/pkg/config"
2026-02-10 08:05:23 +00:00
"github.com/sipeed/picoclaw/pkg/logger"
2026-02-04 11:06:13 +00:00
"github.com/sipeed/picoclaw/pkg/providers"
"github.com/sipeed/picoclaw/pkg/skills"
2026-03-07 08:48:44 +00:00
"github.com/sipeed/picoclaw/pkg/utils"
2026-02-04 11:06:13 +00:00
)
type ContextBuilder struct {
2026-04-24 11:36:46 +00:00
workspace string
skillsLoader * skills . SkillsLoader
memory * MemoryStore
splitOnMarker bool
2026-05-07 16:26:09 +00:00
agentDiscovery func ( agentID string ) [ ] AgentDescriptor
2026-04-24 11:36:46 +00:00
promptRegistry * PromptRegistry
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
// Cache for system prompt to avoid rebuilding on every call.
// This fixes issue #607: repeated reprocessing of the entire context.
// The cache auto-invalidates when workspace source files change (mtime check).
systemPromptMutex sync . RWMutex
cachedSystemPrompt string
cachedAt time . Time // max observed mtime across tracked paths at cache build time
// existedAtCache tracks which source file paths existed the last time the
// cache was built. This lets sourceFilesChanged detect files that are newly
// created (didn't exist at cache time, now exist) or deleted (existed at
// cache time, now gone) — both of which should trigger a cache rebuild.
existedAtCache map [ string ] bool
2026-03-03 10:25:00 +00:00
// skillFilesAtCache snapshots the skill tree file set and mtimes at cache
// build time. This catches nested file creations/deletions/mtime changes
// that may not update the top-level skill root directory mtime.
skillFilesAtCache map [ string ] time . Time
2026-02-04 11:06:13 +00:00
}
2026-03-09 17:21:49 +00:00
func ( cb * ContextBuilder ) WithToolDiscovery ( useBM25 , useRegex bool ) * ContextBuilder {
2026-04-24 11:36:46 +00:00
if useBM25 || useRegex {
if err := cb . RegisterPromptContributor ( toolDiscoveryPromptContributor {
useBM25 : useBM25 ,
useRegex : useRegex ,
} ) ; err != nil {
2026-05-22 02:06:40 +00:00
logger . WarnCF (
"agent" ,
"Failed to register tool discovery prompt contributor" ,
map [ string ] any {
"error" : err . Error ( ) ,
} ,
)
2026-04-24 11:36:46 +00:00
}
}
2026-03-09 17:21:49 +00:00
return cb
}
2026-03-25 17:33:49 +00:00
func ( cb * ContextBuilder ) WithSplitOnMarker ( enabled bool ) * ContextBuilder {
cb . splitOnMarker = enabled
return cb
}
2026-03-29 11:58:19 +00:00
func ( cb * ContextBuilder ) WithAgentDiscovery (
2026-05-07 16:26:09 +00:00
agentID string ,
discover func ( agentID string ) [ ] AgentDescriptor ,
2026-03-29 11:58:19 +00:00
) * ContextBuilder {
cb . agentDiscovery = discover
2026-05-07 11:16:30 +00:00
if discover != nil {
if err := cb . RegisterPromptContributor ( agentDiscoveryPromptContributor {
2026-05-07 16:26:09 +00:00
agentID : agentID ,
discover : discover ,
2026-05-07 11:16:30 +00:00
} ) ; err != nil {
2026-05-22 02:06:40 +00:00
logger . WarnCF (
"agent" ,
"Failed to register agent discovery prompt contributor" ,
map [ string ] any {
"error" : err . Error ( ) ,
} ,
)
2026-05-07 11:16:30 +00:00
}
}
2026-03-29 11:58:19 +00:00
return cb
}
2026-02-10 15:33:28 +00:00
func getGlobalConfigDir ( ) string {
2026-03-28 17:14:39 +00:00
return config . GetHome ( )
2026-02-10 15:33:28 +00:00
}
2026-02-11 11:27:36 +00:00
func NewContextBuilder ( workspace string ) * ContextBuilder {
// builtin skills: skills directory in current project
// Use the skills/ directory under the current working directory
2026-03-18 10:03:24 +00:00
builtinSkillsDir := strings . TrimSpace ( os . Getenv ( config . EnvBuiltinSkills ) )
2026-03-03 10:25:00 +00:00
if builtinSkillsDir == "" {
2026-06-08 08:52:00 +00:00
wd , err := os . Getwd ( )
if err != nil {
// os.Getwd failure is extremely rare; fall back to empty
// string so that filepath.Join produces a relative "skills"
// path, preserving the original lookup behavior.
wd = ""
}
2026-03-03 10:25:00 +00:00
builtinSkillsDir = filepath . Join ( wd , "skills" )
}
2026-02-10 15:33:28 +00:00
globalSkillsDir := filepath . Join ( getGlobalConfigDir ( ) , "skills" )
2026-02-04 11:06:13 +00:00
return & ContextBuilder {
2026-04-24 10:14:28 +00:00
workspace : workspace ,
skillsLoader : skills . NewSkillsLoader ( workspace , globalSkillsDir , builtinSkillsDir ) ,
memory : NewMemoryStore ( workspace ) ,
promptRegistry : NewPromptRegistry ( ) ,
2026-02-04 11:06:13 +00:00
}
}
2026-04-24 10:14:28 +00:00
func ( cb * ContextBuilder ) RegisterPromptSource ( desc PromptSourceDescriptor ) error {
2026-04-24 11:36:46 +00:00
err := cb . promptRegistryOrDefault ( ) . RegisterSource ( desc )
if err == nil {
cb . InvalidateCache ( )
}
return err
2026-04-24 10:14:28 +00:00
}
func ( cb * ContextBuilder ) RegisterPromptContributor ( contributor PromptContributor ) error {
2026-04-24 11:36:46 +00:00
err := cb . promptRegistryOrDefault ( ) . RegisterContributor ( contributor )
if err == nil {
cb . InvalidateCache ( )
}
return err
2026-04-24 10:14:28 +00:00
}
func ( cb * ContextBuilder ) promptRegistryOrDefault ( ) * PromptRegistry {
if cb . promptRegistry == nil {
cb . promptRegistry = NewPromptRegistry ( )
2026-02-04 11:06:13 +00:00
}
2026-04-24 10:14:28 +00:00
return cb . promptRegistry
2026-02-04 11:06:13 +00:00
}
2026-05-22 02:06:40 +00:00
func ( cb * ContextBuilder ) getIdentity ( includeToolUseRule bool ) string {
2026-02-04 11:06:13 +00:00
workspacePath , _ := filepath . Abs ( filepath . Join ( cb . workspace ) )
2026-03-10 09:42:05 +00:00
version := config . FormatVersion ( )
2026-05-22 02:06:40 +00:00
rules := [ ] string { }
if includeToolUseRule {
rules = append ( rules , toolUseSystemPromptRule ( ) )
}
accuracyRule := "**Be helpful and accurate** - Briefly explain what you're doing."
if includeToolUseRule {
accuracyRule = "**Be helpful and accurate** - When using tools, briefly explain what you're doing."
}
rules = append (
rules ,
accuracyRule ,
"**Context summaries** - Conversation summaries provided as context are approximate references only. They may be incomplete or outdated. Always defer to explicit user instructions over summary content." ,
)
if includeToolUseRule {
rules = append (
rules ,
fmt . Sprintf (
"**Memory** - When interacting with me if something seems memorable, update %s/memory/MEMORY.md" ,
workspacePath ,
) ,
)
}
for i , rule := range rules {
rules [ i ] = fmt . Sprintf ( "%d. %s" , i + 1 , rule )
}
2026-02-04 11:06:13 +00:00
2026-03-10 09:42:05 +00:00
return fmt . Sprintf (
` # picoclaw 🦞 ( % s )
2026-02-04 11:06:13 +00:00
2026-02-10 15:33:28 +00:00
You are picoclaw , a helpful AI assistant .
2026-02-04 11:06:13 +00:00
# # Workspace
Your workspace is at : % s
2026-02-10 15:33:28 +00:00
- Memory : % s / memory / MEMORY . md
- Daily Notes : % s / memory / YYYYMM / YYYYMMDD . md
- Skills : % s / skills / { skill - name } / SKILL . md
2026-02-11 10:43:21 +00:00
# # Important Rules
2026-05-22 02:06:40 +00:00
% s
` ,
version ,
workspacePath ,
workspacePath ,
workspacePath ,
workspacePath ,
strings . Join ( rules , "\n\n" ) ,
)
2026-03-09 17:21:49 +00:00
}
2026-04-24 11:36:46 +00:00
func formatToolDiscoveryRule ( useBM25 , useRegex bool ) string {
if ! useBM25 && ! useRegex {
2026-03-09 17:21:49 +00:00
return ""
}
var toolNames [ ] string
2026-04-24 11:36:46 +00:00
if useBM25 {
2026-03-09 17:21:49 +00:00
toolNames = append ( toolNames , ` "tool_search_tool_bm25" ` )
}
2026-04-24 11:36:46 +00:00
if useRegex {
2026-03-09 17:21:49 +00:00
toolNames = append ( toolNames , ` "tool_search_tool_regex" ` )
}
return fmt . Sprintf (
` 5. **Tool Discovery** - Your visible tools are limited to save memory, but a vast hidden library exists. If you lack the right tool for a task, BEFORE giving up, you MUST search using the %s tool. Do not refuse a request unless the search returns nothing. Found tools will temporarily unlock for your next turn. ` ,
strings . Join ( toolNames , " or " ) ,
)
2026-02-10 08:05:23 +00:00
}
func ( cb * ContextBuilder ) BuildSystemPrompt ( ) string {
2026-04-24 10:14:28 +00:00
return renderPromptPartsLegacy ( cb . BuildSystemPromptParts ( ) )
}
func ( cb * ContextBuilder ) BuildSystemPromptParts ( ) [ ] PromptPart {
2026-05-22 02:06:40 +00:00
return cb . buildSystemPromptParts ( systemPromptBuildOptions {
IncludeSkillCatalog : true ,
IncludeToolUseRule : true ,
} )
}
type systemPromptBuildOptions struct {
IncludeSkillCatalog bool
IncludeToolUseRule bool
AllowedSkills [ ] string
AllowedTools [ ] string
}
func ( cb * ContextBuilder ) buildSystemPromptParts ( opts systemPromptBuildOptions ) [ ] PromptPart {
2026-04-24 10:14:28 +00:00
stack := NewPromptStack ( cb . promptRegistryOrDefault ( ) )
add := func ( part PromptPart ) {
if err := stack . Add ( part ) ; err != nil {
logger . WarnCF ( "agent" , "Skipping invalid prompt part" , map [ string ] any {
"id" : part . ID ,
"layer" : part . Layer ,
"slot" : part . Slot ,
"source" : part . Source . ID ,
"error" : err . Error ( ) ,
} )
}
}
2026-02-10 08:05:23 +00:00
// Core identity section
2026-04-24 10:14:28 +00:00
add ( PromptPart {
ID : "kernel.identity" ,
Layer : PromptLayerKernel ,
Slot : PromptSlotIdentity ,
Source : PromptSource { ID : PromptSourceKernel , Name : "identity" } ,
Title : "picoclaw identity" ,
2026-05-22 02:06:40 +00:00
Content : cb . getIdentity ( opts . IncludeToolUseRule ) ,
2026-04-24 10:14:28 +00:00
Stable : true ,
Cache : PromptCacheEphemeral ,
} )
2026-02-10 08:05:23 +00:00
// Bootstrap files
bootstrapContent := cb . LoadBootstrapFiles ( )
if bootstrapContent != "" {
2026-04-24 10:14:28 +00:00
add ( PromptPart {
ID : "instruction.workspace" ,
Layer : PromptLayerInstruction ,
Slot : PromptSlotWorkspace ,
Source : PromptSource { ID : PromptSourceWorkspace , Name : "workspace" } ,
Title : "workspace instructions" ,
Content : bootstrapContent ,
Stable : true ,
Cache : PromptCacheEphemeral ,
} )
2026-02-10 08:05:23 +00:00
}
2026-02-10 15:33:28 +00:00
// Skills - show summary, AI can read full content with read_file tool
2026-05-22 02:06:40 +00:00
skillsSummary := ""
if opts . IncludeSkillCatalog {
skillsSummary = cb . buildSkillsSummary ( opts . AllowedSkills )
}
2026-02-10 08:05:23 +00:00
if skillsSummary != "" {
2026-05-22 02:06:40 +00:00
skillIntro := "The following skills extend your capabilities."
readFileAllowed := promptAllowsTool (
PromptBuildRequest { AllowedTools : opts . AllowedTools } ,
"read_file" ,
)
if opts . IncludeToolUseRule && readFileAllowed {
skillIntro += " To use a skill, read its SKILL.md file using the read_file tool."
}
2026-04-24 10:14:28 +00:00
add ( PromptPart {
ID : "capability.skill_catalog" ,
Layer : PromptLayerCapability ,
Slot : PromptSlotSkillCatalog ,
Source : PromptSource { ID : PromptSourceSkillCatalog , Name : "skill:index" } ,
Title : "skill catalog" ,
Content : fmt . Sprintf ( ` # Skills
2026-02-10 08:05:23 +00:00
2026-05-22 02:06:40 +00:00
% s
2026-02-10 08:05:23 +00:00
2026-05-22 02:06:40 +00:00
% s ` , skillIntro , skillsSummary ) ,
2026-04-24 10:14:28 +00:00
Stable : true ,
Cache : PromptCacheEphemeral ,
} )
2026-02-10 08:05:23 +00:00
}
// Memory context
memoryContext := cb . memory . GetMemoryContext ( )
if memoryContext != "" {
2026-04-24 10:14:28 +00:00
add ( PromptPart {
ID : "context.memory" ,
Layer : PromptLayerContext ,
Slot : PromptSlotMemory ,
Source : PromptSource { ID : PromptSourceMemory , Name : "memory:workspace" } ,
Title : "memory" ,
Content : "# Memory\n\n" + memoryContext ,
Stable : true ,
Cache : PromptCacheEphemeral ,
} )
2026-02-10 08:05:23 +00:00
}
2026-03-25 17:33:49 +00:00
// Multi-Message Sending (if enabled)
if cb . splitOnMarker {
2026-04-24 10:14:28 +00:00
add ( PromptPart {
ID : "context.output_policy.split_on_marker" ,
Layer : PromptLayerContext ,
Slot : PromptSlotOutput ,
Source : PromptSource { ID : PromptSourceOutputPolicy , Name : "split_on_marker" } ,
Title : "multi-message output policy" ,
Content : ` # MULTI - MESSAGE OUTPUT
2026-03-25 17:33:49 +00:00
You MUST frequently use < | [ SPLIT ] | > to break your responses into multiple short messages . NEVER output a single long wall of text . Actively split distinct concepts or parts . Example : Message part 1 < | [ SPLIT ] | > Message part 2 < | [ SPLIT ] | > Message part 3
2026-04-24 10:14:28 +00:00
Each part separated by the marker will be sent as an independent message . ` ,
Stable : true ,
Cache : PromptCacheEphemeral ,
} )
2026-03-25 17:33:49 +00:00
}
2026-04-24 10:14:28 +00:00
stack . Seal ( )
return stack . Parts ( )
2026-02-04 11:06:13 +00:00
}
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
// BuildSystemPromptWithCache returns the cached system prompt if available
// and source files haven't changed, otherwise builds and caches it.
// Source file changes are detected via mtime checks (cheap stat calls).
func ( cb * ContextBuilder ) BuildSystemPromptWithCache ( ) string {
// Try read lock first — fast path when cache is valid
cb . systemPromptMutex . RLock ( )
if cb . cachedSystemPrompt != "" && ! cb . sourceFilesChangedLocked ( ) {
result := cb . cachedSystemPrompt
cb . systemPromptMutex . RUnlock ( )
return result
}
cb . systemPromptMutex . RUnlock ( )
// Acquire write lock for building
cb . systemPromptMutex . Lock ( )
defer cb . systemPromptMutex . Unlock ( )
// Double-check: another goroutine may have rebuilt while we waited
if cb . cachedSystemPrompt != "" && ! cb . sourceFilesChangedLocked ( ) {
return cb . cachedSystemPrompt
}
// Snapshot the baseline (existence + max mtime) BEFORE building the prompt.
// This way cachedAt reflects the pre-build state: if a file is modified
// during BuildSystemPrompt, its new mtime will be > baseline.maxMtime,
// so the next sourceFilesChangedLocked check will correctly trigger a
// rebuild. The alternative (baseline after build) risks caching stale
// content with a too-new baseline, making the staleness invisible.
baseline := cb . buildCacheBaseline ( )
prompt := cb . BuildSystemPrompt ( )
cb . cachedSystemPrompt = prompt
cb . cachedAt = baseline . maxMtime
cb . existedAtCache = baseline . existed
2026-03-03 10:25:00 +00:00
cb . skillFilesAtCache = baseline . skillFiles
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
logger . DebugCF ( "agent" , "System prompt cached" ,
map [ string ] any {
"length" : len ( prompt ) ,
} )
return prompt
}
2026-05-22 02:06:40 +00:00
func ( cb * ContextBuilder ) buildSystemPromptForRequest (
req PromptBuildRequest ,
) ( string , [ ] providers . ContentBlock ) {
if req . SuppressDefaultSystemPrompt {
return "" , nil
}
useDefaultCache := ! req . SuppressSkillContext &&
! req . SuppressToolUseRule &&
len ( req . AllowedSkills ) == 0 &&
len ( req . AllowedTools ) == 0
if useDefaultCache {
staticPrompt := cb . BuildSystemPromptWithCache ( )
return staticPrompt , [ ] providers . ContentBlock {
promptContentBlock ( PromptPart {
ID : "kernel.static" ,
Layer : PromptLayerKernel ,
Slot : PromptSlotIdentity ,
Source : PromptSource { ID : PromptSourceKernel , Name : "static" } ,
Content : staticPrompt ,
} , & providers . CacheControl { Type : "ephemeral" } ) ,
}
}
parts := cb . buildSystemPromptParts ( systemPromptBuildOptions {
IncludeSkillCatalog : ! req . SuppressSkillContext ,
IncludeToolUseRule : ! req . SuppressToolUseRule ,
AllowedSkills : req . AllowedSkills ,
AllowedTools : req . AllowedTools ,
} )
staticPrompt := renderPromptPartsLegacy ( parts )
blocks := make ( [ ] providers . ContentBlock , 0 , len ( parts ) )
for _ , part := range parts {
if strings . TrimSpace ( part . Content ) == "" {
continue
}
blocks = append ( blocks , promptContentBlock ( part , cacheControlForPromptPart ( part ) ) )
}
return staticPrompt , blocks
}
func ( cb * ContextBuilder ) buildSkillsSummary ( allowed [ ] string ) string {
if cb . skillsLoader == nil {
return ""
}
if len ( allowed ) == 0 {
return cb . skillsLoader . BuildSkillsSummary ( )
}
allowedSet := cleanAllowedSet ( allowed )
if len ( allowedSet ) == 0 {
return ""
}
var lines [ ] string
lines = append ( lines , "<skills>" )
for _ , s := range cb . skillsLoader . ListSkills ( ) {
if _ , ok := allowedSet [ strings . ToLower ( strings . TrimSpace ( s . Name ) ) ] ; ! ok {
continue
}
lines = append ( lines , " <skill>" )
lines = append ( lines , fmt . Sprintf ( " <name>%s</name>" , xmlEscapeForPrompt ( s . Name ) ) )
lines = append (
lines ,
fmt . Sprintf ( " <description>%s</description>" , xmlEscapeForPrompt ( s . Description ) ) ,
)
lines = append (
lines ,
fmt . Sprintf ( " <location>%s</location>" , xmlEscapeForPrompt ( s . Path ) ) ,
)
lines = append ( lines , fmt . Sprintf ( " <source>%s</source>" , xmlEscapeForPrompt ( s . Source ) ) )
lines = append ( lines , " </skill>" )
}
if len ( lines ) == 1 {
return ""
}
lines = append ( lines , "</skills>" )
return strings . Join ( lines , "\n" )
}
func xmlEscapeForPrompt ( s string ) string {
replacer := strings . NewReplacer (
"&" , "&" ,
"<" , "<" ,
">" , ">" ,
"\"" , """ ,
"'" , "'" ,
)
return replacer . Replace ( s )
}
2026-04-21 08:30:02 +00:00
// EstimateSystemTokens estimates the token count of the full system message
// that would be sent to the LLM, mirroring the composition logic in BuildMessages.
// It includes: static prompt, dynamic context, active skills, and summary with
// wrapping prefixes and separators. This avoids needing all per-request parameters
// that BuildMessages requires (media, channel, chatID, sender, etc.).
func ( cb * ContextBuilder ) EstimateSystemTokens ( summary string , activeSkills [ ] string ) int {
staticPrompt := cb . BuildSystemPromptWithCache ( )
// Dynamic context is small and varies per request; use a representative estimate.
// Actual buildDynamicContext produces ~200-400 chars of time/runtime/session info.
const dynamicContextChars = 300
totalChars := utf8 . RuneCountInString ( staticPrompt ) + dynamicContextChars
if skillsText := cb . buildActiveSkillsContext ( activeSkills ) ; skillsText != "" {
totalChars += utf8 . RuneCountInString ( skillsText )
totalChars += 7 // separator \n\n---\n\n
}
2026-04-24 11:36:46 +00:00
if contributedParts , err := cb . promptRegistryOrDefault ( ) . Collect ( context . Background ( ) , PromptBuildRequest {
Summary : summary ,
ActiveSkills : append ( [ ] string ( nil ) , activeSkills ... ) ,
} ) ; err == nil {
for _ , part := range contributedParts {
if strings . TrimSpace ( part . Content ) == "" {
continue
}
totalChars += utf8 . RuneCountInString ( part . Content )
totalChars += 7 // separator
}
}
2026-04-21 08:30:02 +00:00
if summary != "" {
// Matches the CONTEXT_SUMMARY: prefix added in BuildMessages
const summaryPrefix = "CONTEXT_SUMMARY: The following is an approximate summary of prior conversation " +
"for reference only. It may be incomplete or outdated — always defer to explicit instructions.\n\n"
totalChars += utf8 . RuneCountInString ( summaryPrefix ) + utf8 . RuneCountInString ( summary )
totalChars += 7 // separator
}
return totalChars * 2 / 5 // same heuristic as tokenizer.EstimateMessageTokens
}
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
// InvalidateCache clears the cached system prompt.
// Normally not needed because the cache auto-invalidates via mtime checks,
// but this is useful for tests or explicit reload commands.
func ( cb * ContextBuilder ) InvalidateCache ( ) {
cb . systemPromptMutex . Lock ( )
defer cb . systemPromptMutex . Unlock ( )
cb . cachedSystemPrompt = ""
cb . cachedAt = time . Time { }
cb . existedAtCache = nil
2026-03-03 10:25:00 +00:00
cb . skillFilesAtCache = nil
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
logger . DebugCF ( "agent" , "System prompt cache invalidated" , nil )
}
2026-03-03 10:25:00 +00:00
// sourcePaths returns non-skill workspace source files tracked for cache
// invalidation (bootstrap files + memory). Skill roots are handled separately
// because they require both directory-level and recursive file-level checks.
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
func ( cb * ContextBuilder ) sourcePaths ( ) [ ] string {
2026-03-22 11:21:58 +00:00
agentDefinition := cb . LoadAgentDefinition ( )
paths := agentDefinition . trackedPaths ( cb . workspace )
paths = append ( paths , filepath . Join ( cb . workspace , "memory" , "MEMORY.md" ) )
return uniquePaths ( paths )
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
}
2026-03-03 10:25:00 +00:00
// skillRoots returns all skill root directories that can affect
// BuildSkillsSummary output (workspace/global/builtin).
func ( cb * ContextBuilder ) skillRoots ( ) [ ] string {
if cb . skillsLoader == nil {
return [ ] string { filepath . Join ( cb . workspace , "skills" ) }
}
roots := cb . skillsLoader . SkillRoots ( )
if len ( roots ) == 0 {
return [ ] string { filepath . Join ( cb . workspace , "skills" ) }
}
return roots
}
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
// cacheBaseline holds the file existence snapshot and the latest observed
// mtime across all tracked paths. Used as the cache reference point.
type cacheBaseline struct {
2026-03-03 10:25:00 +00:00
existed map [ string ] bool
skillFiles map [ string ] time . Time
maxMtime time . Time
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
}
// buildCacheBaseline records which tracked paths currently exist and computes
// the latest mtime across all tracked files + skills directory contents.
// Called under write lock when the cache is built.
func ( cb * ContextBuilder ) buildCacheBaseline ( ) cacheBaseline {
2026-03-03 10:25:00 +00:00
skillRoots := cb . skillRoots ( )
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
2026-03-03 10:25:00 +00:00
// All paths whose existence we track: source files + all skill roots.
allPaths := append ( cb . sourcePaths ( ) , skillRoots ... )
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
existed := make ( map [ string ] bool , len ( allPaths ) )
2026-03-03 10:25:00 +00:00
skillFiles := make ( map [ string ] time . Time )
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
var maxMtime time . Time
for _ , p := range allPaths {
info , err := os . Stat ( p )
existed [ p ] = err == nil
if err == nil && info . ModTime ( ) . After ( maxMtime ) {
maxMtime = info . ModTime ( )
}
}
2026-03-03 10:25:00 +00:00
// Walk all skill roots recursively to snapshot skill files and mtimes.
// Use os.Stat (not d.Info) for consistency with sourceFilesChanged checks.
for _ , root := range skillRoots {
_ = filepath . WalkDir ( root , func ( path string , d fs . DirEntry , walkErr error ) error {
if walkErr == nil && ! d . IsDir ( ) {
if info , err := os . Stat ( path ) ; err == nil {
skillFiles [ path ] = info . ModTime ( )
if info . ModTime ( ) . After ( maxMtime ) {
maxMtime = info . ModTime ( )
}
}
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
}
2026-03-03 10:25:00 +00:00
return nil
} )
}
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
// If no tracked files exist yet (empty workspace), maxMtime is zero.
// Use a very old non-zero time so that:
// 1. cachedAt.IsZero() won't trigger perpetual rebuilds.
// 2. Any real file created afterwards has mtime > cachedAt, so it
// will be detected by fileChangedSince (unlike time.Now() which
// could race with a file whose mtime <= Now).
if maxMtime . IsZero ( ) {
maxMtime = time . Unix ( 1 , 0 )
}
2026-03-03 10:25:00 +00:00
return cacheBaseline { existed : existed , skillFiles : skillFiles , maxMtime : maxMtime }
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
}
// sourceFilesChangedLocked checks whether any workspace source file has been
// modified, created, or deleted since the cache was last built.
//
// IMPORTANT: The caller MUST hold at least a read lock on systemPromptMutex.
// Go's sync.RWMutex is not reentrant, so this function must NOT acquire the
// lock itself (it would deadlock when called from BuildSystemPromptWithCache
// which already holds RLock or Lock).
func ( cb * ContextBuilder ) sourceFilesChangedLocked ( ) bool {
if cb . cachedAt . IsZero ( ) {
return true
}
// Check tracked source files (bootstrap + memory).
2026-02-27 08:35:07 +00:00
if slices . ContainsFunc ( cb . sourcePaths ( ) , cb . fileChangedSince ) {
return true
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
}
2026-03-03 10:25:00 +00:00
// --- Skill roots (workspace/global/builtin) ---
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
//
2026-03-03 10:25:00 +00:00
// For each root:
// 1. Creation/deletion and root directory mtime changes are tracked by fileChangedSince.
// 2. Nested file create/delete/mtime changes are tracked by the skill file snapshot.
for _ , root := range cb . skillRoots ( ) {
if cb . fileChangedSince ( root ) {
return true
}
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
}
2026-03-03 10:25:00 +00:00
if skillFilesChangedSince ( cb . skillRoots ( ) , cb . skillFilesAtCache ) {
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
return true
}
return false
}
// fileChangedSince returns true if a tracked source file has been modified,
// newly created, or deleted since the cache was built.
//
// Four cases:
// - existed at cache time, exists now -> check mtime
// - existed at cache time, gone now -> changed (deleted)
// - absent at cache time, exists now -> changed (created)
// - absent at cache time, gone now -> no change
func ( cb * ContextBuilder ) fileChangedSince ( path string ) bool {
2026-02-25 12:44:07 +00:00
// Defensive: if existedAtCache was never initialized, treat as changed
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
// so the cache rebuilds rather than silently serving stale data.
if cb . existedAtCache == nil {
return true
}
existedBefore := cb . existedAtCache [ path ]
info , err := os . Stat ( path )
existsNow := err == nil
if existedBefore != existsNow {
return true // file was created or deleted
}
if ! existsNow {
return false // didn't exist before, doesn't exist now
}
return info . ModTime ( ) . After ( cb . cachedAt )
}
// errWalkStop is a sentinel error used to stop filepath.WalkDir early.
// Using a dedicated error (instead of fs.SkipAll) makes the early-exit
// intent explicit and avoids the nilerr linter warning that would fire
// if the callback returned nil when its err parameter is non-nil.
var errWalkStop = errors . New ( "walk stop" )
2026-03-03 10:25:00 +00:00
// skillFilesChangedSince compares the current recursive skill file tree
// against the cache-time snapshot. Any create/delete/mtime drift invalidates
// the cache.
func skillFilesChangedSince ( skillRoots [ ] string , filesAtCache map [ string ] time . Time ) bool {
// Defensive: if the snapshot was never initialized, force rebuild.
if filesAtCache == nil {
return true
}
// Check cached files still exist and keep the same mtime.
for path , cachedMtime := range filesAtCache {
info , err := os . Stat ( path )
if err != nil {
// A previously tracked file disappeared (or became inaccessible):
// either way, cached skill summary may now be stale.
return true
}
if ! info . ModTime ( ) . Equal ( cachedMtime ) {
return true
}
}
// Check no new files appeared under any skill root.
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
changed := false
2026-03-03 10:25:00 +00:00
for _ , root := range skillRoots {
if strings . TrimSpace ( root ) == "" {
continue
}
err := filepath . WalkDir ( root , func ( path string , d fs . DirEntry , walkErr error ) error {
if walkErr != nil {
// Treat unexpected walk errors as changed to avoid stale cache.
if ! os . IsNotExist ( walkErr ) {
changed = true
return errWalkStop
}
return nil
}
if d . IsDir ( ) {
return nil
}
if _ , ok := filesAtCache [ path ] ; ! ok {
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
changed = true
2026-03-03 10:25:00 +00:00
return errWalkStop
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
}
2026-03-03 10:25:00 +00:00
return nil
} )
if changed {
return true
}
if err != nil && ! errors . Is ( err , errWalkStop ) && ! os . IsNotExist ( err ) {
logger . DebugCF ( "agent" , "skills walk error" , map [ string ] any { "error" : err . Error ( ) } )
return true
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
}
}
2026-03-03 10:25:00 +00:00
return false
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
}
2026-02-04 11:06:13 +00:00
func ( cb * ContextBuilder ) LoadBootstrapFiles ( ) string {
2026-03-22 11:21:58 +00:00
var sb strings . Builder
agentDefinition := cb . LoadAgentDefinition ( )
if agentDefinition . Agent != nil {
label := string ( agentDefinition . Source )
if label == "" {
label = relativeWorkspacePath ( cb . workspace , agentDefinition . Agent . Path )
}
fmt . Fprintf ( & sb , "## %s\n\n%s\n\n" , label , agentDefinition . Agent . Body )
}
if agentDefinition . Soul != nil {
fmt . Fprintf (
& sb ,
"## %s\n\n%s\n\n" ,
relativeWorkspacePath ( cb . workspace , agentDefinition . Soul . Path ) ,
agentDefinition . Soul . Content ,
)
}
if agentDefinition . User != nil {
fmt . Fprintf ( & sb , "## %s\n\n%s\n\n" , "USER.md" , agentDefinition . User . Content )
2026-02-04 11:06:13 +00:00
}
2026-03-22 11:21:58 +00:00
if agentDefinition . Source != AgentDefinitionSourceAgent {
filePath := filepath . Join ( cb . workspace , "IDENTITY.md" )
2026-02-04 11:06:13 +00:00
if data , err := os . ReadFile ( filePath ) ; err == nil {
2026-03-22 11:21:58 +00:00
fmt . Fprintf ( & sb , "## %s\n\n%s\n\n" , "IDENTITY.md" , data )
2026-02-04 11:06:13 +00:00
}
}
2026-02-20 07:06:33 +00:00
return sb . String ( )
2026-02-04 11:06:13 +00:00
}
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
// buildDynamicContext returns a short dynamic context string with per-request info.
// This changes every request (time, session) so it is NOT part of the cached prompt.
// LLM-side KV cache reuse is achieved by each provider adapter's native mechanism:
// - Anthropic: per-block cache_control (ephemeral) on the static SystemParts block
// - OpenAI / Codex: prompt_cache_key for prefix-based caching
//
// See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
// See: https://platform.openai.com/docs/guides/prompt-caching
2026-03-17 15:31:56 +00:00
func formatCurrentSenderLine ( senderID , senderDisplayName string ) string {
senderID = strings . TrimSpace ( senderID )
senderDisplayName = strings . TrimSpace ( senderDisplayName )
switch {
case senderDisplayName != "" && senderID != "" :
return fmt . Sprintf ( "Current sender: %s (ID: %s)" , senderDisplayName , senderID )
case senderDisplayName != "" :
return fmt . Sprintf ( "Current sender: %s" , senderDisplayName )
case senderID != "" :
return fmt . Sprintf ( "Current sender: %s" , senderID )
default :
return ""
}
}
2026-03-29 11:58:19 +00:00
func ( cb * ContextBuilder ) buildDynamicContext (
channel , chatID , senderID , senderDisplayName string ,
) string {
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
now := time . Now ( ) . Format ( "2006-01-02 15:04 (Monday)" )
rt := fmt . Sprintf ( "%s %s, Go %s" , runtime . GOOS , runtime . GOARCH , runtime . Version ( ) )
var sb strings . Builder
fmt . Fprintf ( & sb , "## Current Time\n%s\n\n## Runtime\n%s" , now , rt )
if channel != "" && chatID != "" {
fmt . Fprintf ( & sb , "\n\n## Current Session\nChannel: %s\nChat ID: %s" , channel , chatID )
}
2026-03-17 15:31:56 +00:00
if senderLine := formatCurrentSenderLine ( senderID , senderDisplayName ) ; senderLine != "" {
fmt . Fprintf ( & sb , "\n\n## Current Sender\n%s" , senderLine )
}
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
return sb . String ( )
}
2026-02-20 18:03:11 +00:00
func ( cb * ContextBuilder ) BuildMessages (
history [ ] providers . Message ,
summary string ,
currentMessage string ,
media [ ] string ,
2026-03-17 15:31:56 +00:00
channel , chatID , senderID , senderDisplayName string ,
2026-03-22 14:33:25 +00:00
activeSkills ... string ,
2026-02-20 18:03:11 +00:00
) [ ] providers . Message {
2026-04-24 10:14:28 +00:00
return cb . BuildMessagesFromPrompt ( PromptBuildRequest {
History : history ,
Summary : summary ,
CurrentMessage : currentMessage ,
Media : media ,
Channel : channel ,
ChatID : chatID ,
SenderID : senderID ,
SenderDisplayName : senderDisplayName ,
ActiveSkills : append ( [ ] string ( nil ) , activeSkills ... ) ,
} )
}
func ( cb * ContextBuilder ) BuildMessagesFromPrompt ( req PromptBuildRequest ) [ ] providers . Message {
2026-02-04 11:06:13 +00:00
messages := [ ] providers . Message { }
2026-05-22 02:06:40 +00:00
// The default static part (identity, bootstrap, skills, memory) is cached
// locally to avoid repeated file I/O and string building on every call
// (fixes issue #607). Profile-customized static prompts are built on demand.
// Dynamic parts (time, session, summary) are appended per request unless the
// profile suppresses PicoClaw system context.
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
// Everything is sent as a single system message for provider compatibility:
// - Anthropic adapter extracts messages[0] (Role=="system") and maps its content
// to the top-level "system" parameter in the Messages API request. A single
// contiguous system block makes this extraction straightforward.
// - Codex maps only the first system message to its instructions field.
// - OpenAI-compat passes messages through as-is.
2026-05-22 02:06:40 +00:00
staticPrompt , contentBlocks := cb . buildSystemPromptForRequest ( req )
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
// Compose a single system message: static (cached) + dynamic + optional summary.
// Keeping all system content in one message ensures every provider adapter can
// extract it correctly (Anthropic adapter -> top-level system param,
// Codex -> instructions field).
//
// SystemParts carries the same content as structured blocks so that
// cache-aware adapters (Anthropic) can set per-block cache_control.
// The static block is marked "ephemeral" — its prefix hash is stable
// across requests, enabling LLM-side KV cache reuse.
2026-05-22 02:06:40 +00:00
var stringParts [ ] string
if strings . TrimSpace ( staticPrompt ) != "" {
stringParts = append ( stringParts , staticPrompt )
2026-03-29 11:58:19 +00:00
}
2026-04-24 10:14:28 +00:00
promptParts := append ( [ ] PromptPart ( nil ) , req . Overlays ... )
2026-05-22 02:06:40 +00:00
if ! req . SuppressDefaultSystemPrompt && ! req . SuppressSkillContext {
activeSkills := append ( [ ] string ( nil ) , req . ActiveSkills ... )
if len ( req . AllowedSkills ) > 0 {
activeSkills = filterNamesByTurnProfile ( activeSkills , req . AllowedSkills )
}
promptParts = append ( promptParts , cb . buildActiveSkillsPromptParts ( activeSkills ) ... )
}
if ! req . SuppressDefaultSystemPrompt {
if contributedParts , err := cb . promptRegistryOrDefault ( ) . Collect ( context . Background ( ) , req ) ; err != nil {
logger . WarnCF ( "agent" , "Prompt contributor collection failed" , map [ string ] any {
"error" : err . Error ( ) ,
} )
} else {
promptParts = append ( promptParts , contributedParts ... )
}
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
}
2026-02-04 11:06:13 +00:00
2026-04-24 10:14:28 +00:00
if len ( promptParts ) > 0 {
for _ , overlay := range sortPromptParts ( promptParts ) {
if strings . TrimSpace ( overlay . Content ) == "" {
continue
}
if err := cb . promptRegistryOrDefault ( ) . ValidatePart ( overlay ) ; err != nil {
logger . WarnCF ( "agent" , "Skipping invalid prompt overlay" , map [ string ] any {
"id" : overlay . ID ,
"layer" : overlay . Layer ,
"slot" : overlay . Slot ,
"source" : overlay . Source . ID ,
"error" : err . Error ( ) ,
} )
continue
}
stringParts = append ( stringParts , overlay . Content )
contentBlocks = append ( contentBlocks , promptContentBlock ( overlay , nil ) )
}
2026-03-22 14:33:25 +00:00
}
2026-05-22 02:06:40 +00:00
dynamicChars := 0
if ! req . SuppressDefaultSystemPrompt {
// Build short dynamic context (time, runtime, session) — changes per request
dynamicCtx := cb . buildDynamicContext (
req . Channel ,
req . ChatID ,
req . SenderID ,
req . SenderDisplayName ,
)
dynamicChars = len ( dynamicCtx )
runtimePart := PromptPart {
ID : "context.runtime" ,
Layer : PromptLayerContext ,
Slot : PromptSlotRuntime ,
Source : PromptSource { ID : PromptSourceRuntime , Name : "runtime" } ,
Title : "runtime context" ,
Content : dynamicCtx ,
Stable : false ,
Cache : PromptCacheNone ,
}
stringParts = append ( stringParts , dynamicCtx )
contentBlocks = append ( contentBlocks , promptContentBlock ( runtimePart , nil ) )
if req . Summary != "" {
summaryPart := PromptPart {
ID : "context.summary" ,
Layer : PromptLayerContext ,
Slot : PromptSlotSummary ,
Source : PromptSource { ID : PromptSourceSummary , Name : "context.summary" } ,
Title : "context summary" ,
Content : fmt . Sprintf (
"CONTEXT_SUMMARY: The following is an approximate summary of prior conversation " +
"for reference only. It may be incomplete or outdated — always defer to explicit instructions.\n\n%s" ,
req . Summary ,
) ,
Stable : false ,
Cache : PromptCacheNone ,
}
stringParts = append ( stringParts , summaryPart . Content )
contentBlocks = append ( contentBlocks , promptContentBlock ( summaryPart , nil ) )
}
2026-04-24 10:14:28 +00:00
}
2026-05-22 02:06:40 +00:00
if len ( stringParts ) == 0 && req . ToolUseFallback {
fallbackPart := PromptPart {
ID : "kernel.tool_use_fallback" ,
Layer : PromptLayerKernel ,
Slot : PromptSlotIdentity ,
Source : PromptSource { ID : PromptSourceKernel , Name : "tool_use_fallback" } ,
Title : "tool use fallback" ,
Content : toolUseSystemPromptRule ( ) ,
Stable : true ,
Cache : PromptCacheEphemeral ,
2026-04-24 10:14:28 +00:00
}
2026-05-22 02:06:40 +00:00
stringParts = append ( stringParts , fallbackPart . Content )
contentBlocks = append ( contentBlocks , promptContentBlock ( fallbackPart , nil ) )
2026-02-04 11:06:13 +00:00
}
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
fullSystemPrompt := strings . Join ( stringParts , "\n\n---\n\n" )
// Log system prompt summary for debugging (debug mode only).
// Read cachedSystemPrompt under lock to avoid a data race with
// concurrent InvalidateCache / BuildSystemPromptWithCache writes.
cb . systemPromptMutex . RLock ( )
isCached := cb . cachedSystemPrompt != ""
cb . systemPromptMutex . RUnlock ( )
2026-02-10 15:33:28 +00:00
logger . DebugCF ( "agent" , "System prompt built" ,
2026-02-20 18:03:11 +00:00
map [ string ] any {
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
"static_chars" : len ( staticPrompt ) ,
2026-05-22 02:06:40 +00:00
"dynamic_chars" : dynamicChars ,
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
"total_chars" : len ( fullSystemPrompt ) ,
2026-04-24 10:14:28 +00:00
"has_summary" : req . Summary != "" ,
"overlays" : len ( req . Overlays ) ,
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
"cached" : isCached ,
2026-02-10 08:05:23 +00:00
} )
2026-02-10 15:33:28 +00:00
// Log preview of system prompt (avoid logging huge content)
2026-03-07 08:48:44 +00:00
preview := utils . Truncate ( fullSystemPrompt , 500 )
2026-02-10 15:33:28 +00:00
logger . DebugCF ( "agent" , "System prompt preview" ,
2026-02-20 18:03:11 +00:00
map [ string ] any {
2026-02-10 15:33:28 +00:00
"preview" : preview ,
} )
2026-02-04 11:06:13 +00:00
2026-04-24 10:14:28 +00:00
history := sanitizeHistoryForProvider ( req . History )
2026-02-12 06:42:40 +00:00
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
// Single system message containing all context — compatible with all providers.
// SystemParts enables cache-aware adapters to set per-block cache_control;
// Content is the concatenated fallback for adapters that don't read SystemParts.
2026-05-22 02:06:40 +00:00
if strings . TrimSpace ( fullSystemPrompt ) != "" {
messages = append ( messages , providers . Message {
Role : "system" ,
Content : fullSystemPrompt ,
SystemParts : contentBlocks ,
} )
}
2026-02-04 11:06:13 +00:00
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
// Add conversation history
2026-02-04 11:06:13 +00:00
messages = append ( messages , history ... )
2026-04-03 06:15:20 +00:00
// Add current user message. Media-only turns must still be preserved so
// multimodal providers receive the uploaded image even when the user sends
// no accompanying text.
2026-04-24 10:14:28 +00:00
if strings . TrimSpace ( req . CurrentMessage ) != "" || len ( req . Media ) > 0 {
messages = append ( messages , userPromptMessage ( req . CurrentMessage , req . Media ) )
2026-02-17 05:59:29 +00:00
}
2026-05-22 02:06:40 +00:00
if len ( messages ) == 0 {
messages = append ( messages , userPromptMessage ( "" , nil ) )
}
2026-02-04 11:06:13 +00:00
return messages
}
2026-02-17 05:59:29 +00:00
func sanitizeHistoryForProvider ( history [ ] providers . Message ) [ ] providers . Message {
if len ( history ) == 0 {
return history
}
sanitized := make ( [ ] providers . Message , 0 , len ( history ) )
for _ , msg := range history {
switch msg . Role {
fix: cache system prompt with mtime-based auto-invalidation (#607)
Avoid rebuilding the entire system prompt on every BuildMessages() call
by caching the static portion (identity, bootstrap, skills summary,
memory) and only recomputing it when workspace source files change.
Key changes:
- ContextBuilder caches the static prompt behind an RWMutex with
double-checked locking. Source file changes are detected via cheap
os.Stat mtime checks so no explicit invalidation is needed.
- Track file existence at cache time (existedAtCache map) so that
newly created or deleted bootstrap/memory files also trigger a
rebuild — the old modifiedSince() silently returned false on
os.IsNotExist.
- Walk the skills directory recursively with filepath.WalkDir to
catch content-only edits at any nesting depth; directory mtime
alone misses in-place file modifications on most filesystems.
- ToolRegistry.sortedToolNames() sorts tool names before iteration,
ensuring deterministic tool definition order across calls — a
prerequisite for LLM-side prefix/KV cache reuse.
- Merge all context (static + dynamic + summary) into a single
system message for provider compatibility: the Anthropic adapter
extracts messages[0] as the top-level system parameter, and Codex
reads only the first system message as instructions.
- Fix a data race in BuildMessages() where cachedSystemPrompt was
read without holding the lock in a debug log statement.
- Add tests: single system message invariant, mtime auto-invalidation,
new-file creation detection, skill file content change, explicit
InvalidateCache, cache stability, concurrent access (20 goroutines
x 50 iterations, passes go test -race), and a benchmark.
2026-02-25 02:34:54 +00:00
case "system" :
// Drop system messages from history. BuildMessages always
// constructs its own single system message (static + dynamic +
// summary); extra system messages would break providers that
// only accept one (Anthropic, Codex).
logger . DebugCF ( "agent" , "Dropping system message from history" , map [ string ] any { } )
continue
2026-02-17 05:59:29 +00:00
case "tool" :
if len ( sanitized ) == 0 {
2026-02-20 18:03:11 +00:00
logger . DebugCF ( "agent" , "Dropping orphaned leading tool message" , map [ string ] any { } )
2026-02-17 05:59:29 +00:00
continue
}
2026-02-24 13:35:15 +00:00
// Walk backwards to find the nearest assistant message,
// skipping over any preceding tool messages (multi-tool-call case).
foundAssistant := false
for i := len ( sanitized ) - 1 ; i >= 0 ; i -- {
if sanitized [ i ] . Role == "tool" {
continue
}
if sanitized [ i ] . Role == "assistant" && len ( sanitized [ i ] . ToolCalls ) > 0 {
foundAssistant = true
}
break
}
if ! foundAssistant {
2026-02-20 18:03:11 +00:00
logger . DebugCF ( "agent" , "Dropping orphaned tool message" , map [ string ] any { } )
2026-02-17 05:59:29 +00:00
continue
}
sanitized = append ( sanitized , msg )
case "assistant" :
if len ( msg . ToolCalls ) > 0 {
if len ( sanitized ) == 0 {
2026-03-29 11:58:19 +00:00
logger . DebugCF (
"agent" ,
"Dropping assistant tool-call turn at history start" ,
map [ string ] any { } ,
)
2026-02-17 05:59:29 +00:00
continue
}
prev := sanitized [ len ( sanitized ) - 1 ]
if prev . Role != "user" && prev . Role != "tool" {
2026-02-20 18:03:11 +00:00
logger . DebugCF (
"agent" ,
"Dropping assistant tool-call turn with invalid predecessor" ,
map [ string ] any { "prev_role" : prev . Role } ,
)
2026-02-17 05:59:29 +00:00
continue
}
}
sanitized = append ( sanitized , msg )
default :
sanitized = append ( sanitized , msg )
}
}
2026-03-06 08:04:31 +00:00
// Second pass: ensure every assistant message with tool_calls has matching
// tool result messages following it. This is required by strict providers
// like DeepSeek that enforce: "An assistant message with 'tool_calls' must
// be followed by tool messages responding to each 'tool_call_id'."
2026-04-15 12:18:09 +00:00
//
// Deduplication is scoped to the contiguous tool-result block that follows a
// single assistant tool-call message. Some providers legitimately reuse call
// IDs across separate turns (for example "call_0"), so global deduplication
// would incorrectly delete later valid tool results and leave an
// assistant(tool_calls) -> assistant sequence behind.
2026-03-06 08:04:31 +00:00
final := make ( [ ] providers . Message , 0 , len ( sanitized ) )
for i := 0 ; i < len ( sanitized ) ; i ++ {
msg := sanitized [ i ]
2026-03-23 09:24:46 +00:00
2026-03-06 08:04:31 +00:00
if msg . Role == "assistant" && len ( msg . ToolCalls ) > 0 {
expected := make ( map [ string ] bool , len ( msg . ToolCalls ) )
2026-04-15 12:18:09 +00:00
invalidToolCallID := false
2026-03-06 08:04:31 +00:00
for _ , tc := range msg . ToolCalls {
2026-04-15 12:18:09 +00:00
if tc . ID == "" {
invalidToolCallID = true
continue
}
2026-03-06 08:04:31 +00:00
expected [ tc . ID ] = false
}
2026-04-15 12:18:09 +00:00
block := make ( [ ] providers . Message , 0 , len ( expected ) )
seenInBlock := make ( map [ string ] bool , len ( expected ) )
j := i + 1
for ; j < len ( sanitized ) ; j ++ {
next := sanitized [ j ]
if next . Role != "tool" {
2026-03-06 08:04:31 +00:00
break
}
2026-04-15 12:18:09 +00:00
if next . ToolCallID == "" {
2026-05-22 02:06:40 +00:00
logger . DebugCF (
"agent" ,
"Dropping tool result without tool_call_id" ,
map [ string ] any { } ,
)
2026-04-15 12:18:09 +00:00
continue
}
if _ , ok := expected [ next . ToolCallID ] ; ! ok {
logger . DebugCF ( "agent" , "Dropping unexpected tool result" , map [ string ] any {
"tool_call_id" : next . ToolCallID ,
} )
continue
2026-03-06 08:04:31 +00:00
}
2026-04-15 12:18:09 +00:00
if seenInBlock [ next . ToolCallID ] {
2026-05-22 02:06:40 +00:00
logger . DebugCF (
"agent" ,
"Dropping duplicate tool result in tool block" ,
map [ string ] any {
"tool_call_id" : next . ToolCallID ,
} ,
)
2026-04-15 12:18:09 +00:00
continue
2026-03-06 08:04:31 +00:00
}
2026-04-15 12:18:09 +00:00
seenInBlock [ next . ToolCallID ] = true
expected [ next . ToolCallID ] = true
block = append ( block , next )
2026-03-06 08:04:31 +00:00
}
2026-04-15 12:18:09 +00:00
allFound := ! invalidToolCallID
if invalidToolCallID {
2026-05-22 02:06:40 +00:00
logger . DebugCF (
"agent" ,
"Dropping assistant message with empty tool_call_id" ,
map [ string ] any { } ,
)
2026-04-15 12:18:09 +00:00
}
2026-03-06 08:04:31 +00:00
for toolCallID , found := range expected {
if ! found {
allFound = false
logger . DebugCF (
"agent" ,
"Dropping assistant message with incomplete tool results" ,
map [ string ] any {
"missing_tool_call_id" : toolCallID ,
"expected_count" : len ( expected ) ,
2026-04-15 12:18:09 +00:00
"found_count" : len ( block ) ,
2026-03-06 08:04:31 +00:00
} ,
)
break
}
}
if ! allFound {
2026-04-15 12:18:09 +00:00
i = j - 1
2026-03-06 08:04:31 +00:00
continue
}
2026-04-15 12:18:09 +00:00
final = append ( final , msg )
final = append ( final , block ... )
i = j - 1
continue
2026-03-06 08:04:31 +00:00
}
2026-04-15 12:18:09 +00:00
if msg . Role == "tool" {
2026-05-22 02:06:40 +00:00
logger . DebugCF (
"agent" ,
"Dropping orphaned tool message after validation" ,
map [ string ] any {
"tool_call_id" : msg . ToolCallID ,
} ,
)
2026-04-15 12:18:09 +00:00
continue
}
2026-03-06 08:04:31 +00:00
final = append ( final , msg )
}
return final
2026-02-17 05:59:29 +00:00
}
2026-02-20 18:03:11 +00:00
func ( cb * ContextBuilder ) AddToolResult (
messages [ ] providers . Message ,
toolCallID , toolName , result string ,
) [ ] providers . Message {
2026-02-04 11:06:13 +00:00
messages = append ( messages , providers . Message {
Role : "tool" ,
Content : result ,
ToolCallID : toolCallID ,
} )
return messages
}
2026-02-20 18:03:11 +00:00
func ( cb * ContextBuilder ) AddAssistantMessage (
messages [ ] providers . Message ,
content string ,
toolCalls [ ] map [ string ] any ,
) [ ] providers . Message {
2026-02-04 11:06:13 +00:00
msg := providers . Message {
Role : "assistant" ,
Content : content ,
}
2026-02-10 15:33:28 +00:00
// Always add assistant message, whether or not it has tool calls
messages = append ( messages , msg )
2026-02-04 11:06:13 +00:00
return messages
}
2026-03-22 14:33:25 +00:00
func ( cb * ContextBuilder ) buildActiveSkillsContext ( skillNames [ ] string ) string {
2026-05-11 08:13:27 +00:00
ordered := cb . ResolveActiveSkillsForContext ( skillNames )
if len ( ordered ) == 0 {
return ""
}
content := cb . skillsLoader . LoadSkillsForContext ( ordered )
if strings . TrimSpace ( content ) == "" {
2026-03-22 14:33:25 +00:00
return ""
}
2026-05-11 08:13:27 +00:00
return fmt . Sprintf ( ` # Active Skills
The following skills are active for this request . Follow them when relevant .
% s ` , content )
}
func ( cb * ContextBuilder ) ResolveActiveSkillsForContext ( skillNames [ ] string ) [ ] string {
if cb . skillsLoader == nil || len ( skillNames ) == 0 {
return nil
}
2026-03-22 14:33:25 +00:00
var ordered [ ] string
seen := make ( map [ string ] struct { } , len ( skillNames ) )
for _ , name := range skillNames {
canonical , ok := cb . ResolveSkillName ( name )
if ! ok {
continue
}
if _ , exists := seen [ canonical ] ; exists {
continue
}
seen [ canonical ] = struct { } { }
ordered = append ( ordered , canonical )
}
if len ( ordered ) == 0 {
2026-05-11 08:13:27 +00:00
return nil
2026-03-22 14:33:25 +00:00
}
2026-05-11 08:13:27 +00:00
return ordered
2026-03-22 14:33:25 +00:00
}
2026-04-24 10:14:28 +00:00
func ( cb * ContextBuilder ) buildActiveSkillsPromptParts ( skillNames [ ] string ) [ ] PromptPart {
skillsText := cb . buildActiveSkillsContext ( skillNames )
if strings . TrimSpace ( skillsText ) == "" {
return nil
}
return [ ] PromptPart {
{
ID : "capability.active_skills" ,
Layer : PromptLayerCapability ,
Slot : PromptSlotActiveSkill ,
Source : PromptSource { ID : PromptSourceActiveSkills , Name : "skill:active" } ,
Title : "active skills" ,
Content : skillsText ,
Stable : false ,
Cache : PromptCacheNone ,
} ,
}
}
2026-03-22 14:33:25 +00:00
func ( cb * ContextBuilder ) ListSkillNames ( ) [ ] string {
if cb . skillsLoader == nil {
return nil
}
allSkills := cb . skillsLoader . ListSkills ( )
names := make ( [ ] string , 0 , len ( allSkills ) )
for _ , skill := range allSkills {
names = append ( names , skill . Name )
}
return names
}
func ( cb * ContextBuilder ) ResolveSkillName ( name string ) ( string , bool ) {
name = strings . TrimSpace ( name )
if name == "" || cb . skillsLoader == nil {
return "" , false
}
for _ , skill := range cb . skillsLoader . ListSkills ( ) {
if strings . EqualFold ( skill . Name , name ) {
return skill . Name , true
}
}
return "" , false
}
2026-02-10 08:05:23 +00:00
// GetSkillsInfo returns information about loaded skills.
2026-02-20 18:03:11 +00:00
func ( cb * ContextBuilder ) GetSkillsInfo ( ) map [ string ] any {
2026-02-10 15:33:28 +00:00
allSkills := cb . skillsLoader . ListSkills ( )
2026-02-10 08:05:23 +00:00
skillNames := make ( [ ] string , 0 , len ( allSkills ) )
for _ , s := range allSkills {
skillNames = append ( skillNames , s . Name )
}
2026-02-20 18:03:11 +00:00
return map [ string ] any {
2026-02-10 16:30:38 +00:00
"total" : len ( allSkills ) ,
"available" : len ( allSkills ) ,
"names" : skillNames ,
2026-02-10 08:05:23 +00:00
}
}