context_manager.cpp

src/core/context_manager.cpp

@file context_manager.cpp @brief Context management implementation.

Owners: @tvanfossen

check_compaction

void entropic::ContextManager::check_compaction(LoopContext &ctx, bool force=false)

Check and perform compaction if needed.

src/core/context_manager.cpp:224

Source · 20 lines
void ContextManager::check_compaction(
    LoopContext& ctx,
    bool force) {
    int cur = compaction_.counter.count_messages(ctx.messages);
    int max = compaction_.counter.max_tokens;
    if (max > 0) {
        int pct = (cur * 100) / max;
        logger->info("Context: {}/{} tokens ({}%)", cur, max, pct);
    }

    if (fire_pre_compact_hook(ctx, force)) { return; }

    auto result = compaction_.check_and_compact(
        ctx.messages, force, ctx.conversation_id);

    if (result.compacted) {
        fire_post_compact_hooks(ctx, result.old_token_count,
                                result.new_token_count);
    }
}
Activity · 10 steps
lines 227–227int cur = compaction_.counter.count_messages(ctx.messages);lines 228–228int max = compaction_.counter.max_tokens;lines 229–229◇ if (max > 0)lines 230–230int pct = (cur * 100) / max;lines 231–231logger->info("Context: {}/{} tokens ({}%)", cur, max, pct);lines 234–234◇ if (fire_pre_compact_hook(ctx, force))lines 234–234return;lines 236–237auto result = compaction_.check_and_compact( ctx.messages, force, ctx.conversation_id);lines 239–239◇ if (result.compacted)lines 240–241fire_post_compact_hooks(ctx, result.old_token_count, result.new_token_count);

Requirements

REQ-COMPACT-001 REQ-HOOK-002

fire_post_compact_hooks

void entropic::ContextManager::fire_post_compact_hooks(LoopContext &ctx, int old_count, int new_count)

Fire post-compaction callbacks + ON_POST_COMPACT hook.

src/core/context_manager.cpp:280

Source · 23 lines
void ContextManager::fire_post_compact_hooks(LoopContext& ctx, int old_count,
                                             int new_count) {
    logger->info("Compacted: {} -> {} tokens", old_count, new_count);
    if (callbacks_.on_compaction != nullptr) {
        std::string json = "{\"old\":" + std::to_string(old_count)
            + ",\"new\":" + std::to_string(new_count) + "}";
        callbacks_.on_compaction(json.c_str(), callbacks_.user_data);
    }

    // Hook: ON_POST_COMPACT (v1.9.1)
    if (hook_iface_.fire_post != nullptr) {
        std::string json = "{\"tokens_before\":" + std::to_string(old_count)
            + ",\"tokens_after\":" + std::to_string(new_count) + "}";
        char* out = nullptr;
        hook_iface_.fire_post(hook_iface_.registry,
            ENTROPIC_HOOK_ON_POST_COMPACT, json.c_str(), &out);
        free(out);
    }

    if (hooks_.after_compaction) {
        hooks_.after_compaction(ctx);
    }
}
Activity · 11 steps
lines 282–282logger->info("Compacted: {} -> {} tokens", old_count, new_count);lines 283–283◇ if (callbacks_.on_compaction != nullptr)lines 284–285std::string json = "{\"old\":" + std::to_string(old_count) + ",\"new\":" + std::to_string(new_count) + "}";lines 286–286callbacks_.on_compaction(json.c_str(), callbacks_.user_data);lines 290–290◇ if (hook_iface_.fire_post != nullptr)lines 291–292std::string json = "{\"tokens_before\":" + std::to_string(old_count) + ",\"tokens_after\":" + std::to_string(new_count) + "}";lines 293–293char* out = nullptr;lines 294–295hook_iface_.fire_post(hook_iface_.registry, ENTROPIC_HOOK_ON_POST_COMPACT, json.c_str(), &out);lines 296–296free(out);lines 299–299◇ if (hooks_.after_compaction)lines 300–300hooks_.after_compaction(ctx);

Requirements

REQ-COMPACT-001 REQ-HOOK-002

fire_pre_compact_hook

bool entropic::ContextManager::fire_pre_compact_hook(LoopContext &ctx, bool force)

Fire ON_PRE_COMPACT; report whether compaction was cancelled.

src/core/context_manager.cpp:254

Source · 16 lines
bool ContextManager::fire_pre_compact_hook(LoopContext& ctx, bool force) {
    if (hook_iface_.fire_pre == nullptr) { return false; }
    int tok = compaction_.counter.count_messages(ctx.messages);
    std::string json = "{\"token_count\":"
        + std::to_string(tok) + ",\"force\":"
        + (force ? "true" : "false") + "}";
    char* mod = nullptr;
    int rc = hook_iface_.fire_pre(hook_iface_.registry,
        ENTROPIC_HOOK_ON_PRE_COMPACT, json.c_str(), &mod);
    free(mod);
    if (rc != 0) {
        logger->info("ON_PRE_COMPACT hook cancelled compaction");
        return true;
    }
    return false;
}
Activity · 11 steps
lines 255–255◇ if (hook_iface_.fire_pre == nullptr)lines 255–255return false;lines 256–256int tok = compaction_.counter.count_messages(ctx.messages);lines 257–259std::string json = "{\"token_count\":" + std::to_string(tok) + ",\"force\":" + (force ? "true" : "false") + "}";lines 260–260char* mod = nullptr;lines 261–262int rc = hook_iface_.fire_pre(hook_iface_.registry, ENTROPIC_HOOK_ON_PRE_COMPACT, json.c_str(), &mod);lines 263–263free(mod);lines 264–264◇ if (rc != 0)lines 265–265logger->info("ON_PRE_COMPACT hook cancelled compaction");lines 266–266return true;lines 268–268return false;

Requirements

REQ-COMPACT-001 REQ-HOOK-002

inject_context_warning

void entropic::ContextManager::inject_context_warning(LoopContext &ctx)

Inject context usage warning if over threshold.

src/core/context_manager.cpp:187

Source · 28 lines
void ContextManager::inject_context_warning(LoopContext& ctx) {
    float threshold = compaction_.config.warning_threshold_percent;
    float usage = compaction_.counter.usage_percent(ctx.messages);
    if (usage < threshold) {
        return;
    }

    auto last = ctx.metadata.find("last_warning_iteration");
    std::string iter_str = std::to_string(ctx.metrics.iterations);
    if (last != ctx.metadata.end() && last->second == iter_str) {
        return;
    }

    int max_tok = compaction_.counter.max_tokens;
    int cur_tok = compaction_.counter.count_messages(ctx.messages);
    int pct = static_cast<int>(usage * 100.0f);

    Message warning;
    warning.role = "user";
    warning.content = "[CONTEXT WARNING] Context at "
        + std::to_string(pct) + "% capacity ("
        + std::to_string(cur_tok) + "/" + std::to_string(max_tok)
        + " tokens). Capture findings with entropic.todo if needed,"
          " then call entropic.prune_context.";
    ctx.messages.push_back(std::move(warning));
    ctx.metadata["last_warning_iteration"] = iter_str;
    logger->info("[WARNING] Context at {}% — warning injected", pct);
}
Activity · 17 steps
lines 188–188float threshold = compaction_.config.warning_threshold_percent;lines 189–189float usage = compaction_.counter.usage_percent(ctx.messages);lines 190–190◇ if (usage < threshold)lines 191–191return;lines 194–194auto last = ctx.metadata.find("last_warning_iteration");lines 195–195std::string iter_str = std::to_string(ctx.metrics.iterations);lines 196–196◇ if (last != ctx.metadata.end() && last->second == iter_str)lines 197–197return;lines 200–200int max_tok = compaction_.counter.max_tokens;lines 201–201int cur_tok = compaction_.counter.count_messages(ctx.messages);lines 202–202int pct = static_cast<int>(usage * 100.0f);lines 204–204Message warning;lines 205–205warning.role = "user";lines 206–210warning.content = "[CONTEXT WARNING] Context at " + std::to_string(pct) + "% capacity (" + std::to_string(cur_tok) + "/" + std::to_string(max_tok) + " tokens). Capture findings with entropic.todo if needed," " then call entropic.prune_context.";lines 211–211ctx.messages.push_back(std::move(warning));lines 212–212ctx.metadata["last_warning_iteration"] = iter_str;lines 213–213logger->info("[WARNING] Context at {}% — warning injected", pct);

Requirements

REQ-COMPACT-002

prune_old_tool_results

void entropic::ContextManager::prune_old_tool_results(LoopContext &ctx)

Auto-prune tool results older than TTL iterations.

src/core/context_manager.cpp:123

Source · 57 lines
void ContextManager::prune_old_tool_results(LoopContext& ctx) {
    // Gate on context fill — below the warning threshold, pruning has
    // no benefit and only loses evidence the validator + dedup cache
    // depend on. Same threshold ``inject_context_warning`` uses so
    // operators see the warning at exactly the fill where pruning
    // starts engaging. Set ``warning_threshold_percent`` to 0 in
    // config to restore the pre-2.1.3 always-prune behaviour.
    float threshold = compaction_.config.warning_threshold_percent;
    float usage = compaction_.counter.usage_percent(ctx.messages);
    if (usage < threshold) {
        return;
    }

    int ttl = compaction_.config.tool_result_ttl;
    int current = ctx.metrics.iterations;
    int pruned = 0;

    for (auto& msg : ctx.messages) {
        auto tn = msg.metadata.find("tool_name");
        if (tn == msg.metadata.end()) {
            continue;
        }
        if (msg.content.rfind("[Previous:", 0) == 0) {
            continue;
        }
        auto ai = msg.metadata.find("added_at_iteration");
        if (ai == msg.metadata.end()) {
            continue;
        }
        int added = 0;
        try { added = std::stoi(ai->second); }
        catch (...) { continue; }
        if (current - added < ttl) {
            continue;
        }
        // Issue #5 (v2.1.3, companion fix): preserve the original
        // content in metadata before stubbing. The model adapter still
        // sees the stub (which is the whole point of pruning — save
        // context for the agent's next inference), but the
        // constitutional validator's POST_GENERATE hook can read
        // original_content to verify citations against actual evidence
        // instead of the stub. Without this, a long delegation that
        // legitimately fills the context window has its file:line
        // citations false-flagged as hallucinations because the stub
        // is the only evidence the validator sees.
        msg.metadata["original_content"] = msg.content;
        int chars = static_cast<int>(msg.content.size());
        msg.content = "[Previous: " + tn->second + " result — "
                    + std::to_string(chars) + " chars, pruned]";
        ++pruned;
    }

    if (pruned > 0) {
        compaction_.counter.clear_cache();
        logger->info("[AUTO-PRUNE] Pruned {} results (TTL={})", pruned, ttl);
    }
}
Activity · 27 steps
lines 130–130float threshold = compaction_.config.warning_threshold_percent;lines 131–131float usage = compaction_.counter.usage_percent(ctx.messages);lines 132–132◇ if (usage < threshold)lines 133–133return;lines 136–136int ttl = compaction_.config.tool_result_ttl;lines 137–137int current = ctx.metrics.iterations;lines 138–138int pruned = 0;lines 140–140◇ for (auto& msg : ctx.messages)lines 141–141auto tn = msg.metadata.find("tool_name");lines 142–142◇ if (tn == msg.metadata.end())lines 143–143continue;lines 145–145◇ if (msg.content.rfind("[Previous:", 0) == 0)lines 146–146continue;lines 148–148auto ai = msg.metadata.find("added_at_iteration");lines 149–149◇ if (ai == msg.metadata.end())lines 150–150continue;lines 152–152int added = 0;lines 153–154try { added = std::stoi(ai->second); } catch (...) { continue; }lines 155–155◇ if (current - added < ttl)lines 156–156continue;lines 168–168msg.metadata["original_content"] = msg.content;lines 169–169int chars = static_cast<int>(msg.content.size());lines 170–171msg.content = "[Previous: " + tn->second + " result — " + std::to_string(chars) + " chars, pruned]";lines 172–172++pruned;lines 175–175◇ if (pruned > 0)lines 176–176compaction_.counter.clear_cache();lines 177–177logger->info("[AUTO-PRUNE] Pruned {} results (TTL={})", pruned, ttl);

Requirements

REQ-COMPACT-002

prune_tool_results

std::pair< int, int > entropic::ContextManager::prune_tool_results(LoopContext &ctx, int keep_recent)

Replace old tool results with stubs.

src/core/context_manager.cpp:60

Show on the map →

Called by dir_prune

Calls clear_cache

Source · 43 lines
std::pair<int, int> ContextManager::prune_tool_results(
    LoopContext& ctx,
    int keep_recent) {
    std::vector<size_t> indices;
    for (size_t i = 0; i < ctx.messages.size(); ++i) {
        auto it = ctx.messages[i].metadata.find("tool_name");
        if (it != ctx.messages[i].metadata.end()) {
            indices.push_back(i);
        }
    }

    size_t cut = 0;
    if (keep_recent > 0
        && indices.size() > static_cast<size_t>(keep_recent)) {
        cut = indices.size() - static_cast<size_t>(keep_recent);
    } else {
        return {0, 0};
    }

    int pruned = 0;
    int freed = 0;
    for (size_t j = 0; j < cut; ++j) {
        auto& msg = ctx.messages[indices[j]];
        if (msg.content.rfind("[Previous:", 0) == 0) {
            continue;
        }
        auto name_it = msg.metadata.find("tool_name");
        std::string name = (name_it != msg.metadata.end())
                             ? name_it->second : "unknown";
        int chars = static_cast<int>(msg.content.size());
        freed += chars;
        msg.content = "[Previous: " + name + " result — "
                    + std::to_string(chars) + " chars, pruned]";
        ++pruned;
    }

    if (pruned > 0) {
        compaction_.counter.clear_cache();
        logger->info("Pruned {} tool result(s), freed {} chars",
                     pruned, freed);
    }
    return {pruned, freed};
}
Activity · 26 steps
lines 63–63std::vector<size_t> indices;lines 64–64◇ for (size_t i = 0; i < ctx.messages.size(); ++i)lines 65–65auto it = ctx.messages[i].metadata.find("tool_name");lines 66–66◇ if (it != ctx.messages[i].metadata.end())lines 67–67indices.push_back(i);lines 71–71size_t cut = 0;lines 72–73◇ if (keep_recent > 0 && indices.size() > static_cast<size_t>(keep_recent))lines 74–74cut = indices.size() - static_cast<size_t>(keep_recent);lines 75–75elselines 76–76return {0, 0};lines 79–79int pruned = 0;lines 80–80int freed = 0;lines 81–81◇ for (size_t j = 0; j < cut; ++j)lines 82–82auto& msg = ctx.messages[indices[j]];lines 83–83◇ if (msg.content.rfind("[Previous:", 0) == 0)lines 84–84continue;lines 86–86auto name_it = msg.metadata.find("tool_name");lines 87–88std::string name = (name_it != msg.metadata.end()) ? name_it->second : "unknown";lines 89–89int chars = static_cast<int>(msg.content.size());lines 90–90freed += chars;lines 91–92msg.content = "[Previous: " + name + " result — " + std::to_string(chars) + " chars, pruned]";lines 93–93++pruned;lines 96–96◇ if (pruned > 0)lines 97–97compaction_.counter.clear_cache();lines 98–99logger->info("Pruned {} tool result(s), freed {} chars", pruned, freed);lines 101–101return {pruned, freed};

Requirements

REQ-COMPACT-002