delegation.cpp

src/core/delegation.cpp

@file delegation.cpp @brief DelegationManager implementation.

Owners: @tvanfossen

build_child_context

LoopContext entropic::DelegationManager::build_child_context(const LoopContext &parent_ctx, const ChildContextInfo &info, const std::string &task, const std::vector< ContextRef > &context={})

Build a fresh LoopContext for the child delegation.

src/core/delegation.cpp:742

Source · 52 lines
LoopContext DelegationManager::build_child_context(
    const LoopContext& parent_ctx,
    const ChildContextInfo& info,
    const std::string& task,
    const std::vector<ContextRef>& context) {

    LoopContext child;
    child.delegation_depth = parent_ctx.delegation_depth + 1;
    // gh#48 (regression fix, v2.7.4): propagate the parent conversation id so
    // the storage create_delegation INSERT satisfies the delegations→
    // conversations FK. Without this the row is rejected, the delegations
    // table stays empty, and entropic.followup returns the no-matches
    // sentinel. (Present in build_resumed_child_context; lost here when the
    // child-context builders were extracted.)
    child.parent_conversation_id = parent_ctx.conversation_id;
    // gh#158 (v2.13.0, also gh#162): children inherit the parent's session
    // key. It was left "" here, so every delegated child of every parent ran
    // under the DEFAULT session — one shared KV slot and one shared bucket.
    // Harmless while a handle ran one turn at a time; with concurrent runs
    // two parents' children would collide in that single bucket.
    child.session_key = parent_ctx.session_key;
    // P1-9: propagate ancestor chain + append parent tier so the
    // child can reject cycles (A→B→A) before executing.
    child.delegation_ancestor_tiers = parent_ctx.delegation_ancestor_tiers;
    if (!parent_ctx.locked_tier.empty()) {
        child.delegation_ancestor_tiers.push_back(parent_ctx.locked_tier);
    }
    child.locked_tier = info.system_prompt.empty()
        ? parent_ctx.locked_tier : "";
    child.active_phase = "default";

    // System prompt as first message
    Message sys;
    sys.role = "system";
    sys.content = info.system_prompt;
    child.messages.push_back(std::move(sys));

    // Task as user message (context references, then task, then any
    // completion instructions). gh#162: the block comes FIRST because a
    // small model that reads the task and starts searching has already
    // spent the turn the references were meant to save.
    std::string user_content = format_context_block(context) + task;
    if (!info.completion_instructions.empty()) {
        user_content += "\n\n" + info.completion_instructions;
    }
    Message user;
    user.role = "user";
    user.content = std::move(user_content);
    child.messages.push_back(std::move(user));

    return child;
}
Activity · 21 steps
lines 748–748LoopContext child;lines 749–749child.delegation_depth = parent_ctx.delegation_depth + 1;lines 756–756child.parent_conversation_id = parent_ctx.conversation_id;lines 762–762child.session_key = parent_ctx.session_key;lines 765–765child.delegation_ancestor_tiers = parent_ctx.delegation_ancestor_tiers;lines 766–766◇ if (!parent_ctx.locked_tier.empty())lines 767–767child.delegation_ancestor_tiers.push_back(parent_ctx.locked_tier);lines 769–770child.locked_tier = info.system_prompt.empty() ? parent_ctx.locked_tier : "";lines 771–771child.active_phase = "default";lines 774–774Message sys;lines 775–775sys.role = "system";lines 776–776sys.content = info.system_prompt;lines 777–777child.messages.push_back(std::move(sys));lines 783–783std::string user_content = format_context_block(context) + task;lines 784–784◇ if (!info.completion_instructions.empty())lines 785–785user_content += "\n\n" + info.completion_instructions;lines 787–787Message user;lines 788–788user.role = "user";lines 789–789user.content = std::move(user_content);lines 790–790child.messages.push_back(std::move(user));lines 792–792return child;

Requirements

REQ-DELEG-002

build_child_result

DelegationResult entropic::DelegationManager::build_child_result(const std::string &target_tier, const std::string &task, LoopContext &child_ctx)

Build DelegationResult from a terminated child context.

src/core/delegation.cpp:994

Source · 40 lines
DelegationResult DelegationManager::build_child_result(
    const std::string& target_tier,
    const std::string& task,
    LoopContext& child_ctx) {
    DelegationResult result;
    result.target_tier = target_tier;
    result.task = task;
    auto tr = child_ctx.metadata.find("terminal_reason");
    if (tr != child_ctx.metadata.end()) {
        result.terminal_reason = tr->second;
    }
    result.success = (child_ctx.state == AgentState::COMPLETE
                      && result.terminal_reason.empty());
    result.turns_used = child_ctx.metrics.iterations;
    result.summary = extract_summary(child_ctx);
    // Issue #10 (v2.1.4): hoist coverage_gap signal from child
    // metadata onto DelegationResult so the parent's
    // finalize_delegation_result can branch on it without re-parsing
    // ctx.metadata. dir_complete writes these keys when the child
    // calls entropic.complete with coverage_gap=true.
    auto cg = child_ctx.metadata.find("coverage_gap");
    if (cg != child_ctx.metadata.end() && cg->second == "true") {
        result.coverage_gap = true;
        auto gd = child_ctx.metadata.find("gap_description");
        if (gd != child_ctx.metadata.end()) {
            result.gap_description = gd->second;
        }
        auto sf = child_ctx.metadata.find("suggested_files_json");
        if (sf != child_ctx.metadata.end()) {
            auto parsed = nlohmann::json::parse(
                sf->second, nullptr, false);
            if (parsed.is_array()) {
                result.suggested_files =
                    parsed.get<std::vector<std::string>>();
            }
        }
    }
    result.child_messages = std::move(child_ctx.messages);
    return result;
}
Activity · 22 steps
lines 998–998DelegationResult result;lines 999–999result.target_tier = target_tier;lines 1000–1000result.task = task;lines 1001–1001auto tr = child_ctx.metadata.find("terminal_reason");lines 1002–1002◇ if (tr != child_ctx.metadata.end())lines 1003–1003result.terminal_reason = tr->second;lines 1005–1006result.success = (child_ctx.state == AgentState::COMPLETE && result.terminal_reason.empty());lines 1007–1007result.turns_used = child_ctx.metrics.iterations;lines 1008–1008result.summary = extract_summary(child_ctx);lines 1014–1014auto cg = child_ctx.metadata.find("coverage_gap");lines 1015–1015◇ if (cg != child_ctx.metadata.end() && cg->second == "true")lines 1016–1016result.coverage_gap = true;lines 1017–1017auto gd = child_ctx.metadata.find("gap_description");lines 1018–1018◇ if (gd != child_ctx.metadata.end())lines 1019–1019result.gap_description = gd->second;lines 1021–1021auto sf = child_ctx.metadata.find("suggested_files_json");lines 1022–1022◇ if (sf != child_ctx.metadata.end())lines 1023–1024auto parsed = nlohmann::json::parse( sf->second, nullptr, false);lines 1025–1025◇ if (parsed.is_array())lines 1026–1027result.suggested_files = parsed.get<std::vector<std::string>>();lines 1031–1031result.child_messages = std::move(child_ctx.messages);lines 1032–1032return result;

Requirements

REQ-DELEG-002 REQ-DELEG-003

build_resumed_child_context

LoopContext entropic::DelegationManager::build_resumed_child_context(const LoopContext &parent_ctx, const ChildContextInfo &info, const std::string &target_tier, const std::string &task, std::vector< Message > seed_history)

Build a resumed child context (gh#32, v2.1.6).

src/core/delegation.cpp:469

Source · 36 lines
LoopContext DelegationManager::build_resumed_child_context(
        const LoopContext& parent_ctx,
        const ChildContextInfo& info,
        const std::string& target_tier,
        const std::string& task,
        std::vector<Message> seed_history) {
    LoopContext child_ctx;
    child_ctx.delegation_depth = parent_ctx.delegation_depth + 1;
    child_ctx.delegation_ancestor_tiers =
        parent_ctx.delegation_ancestor_tiers;
    child_ctx.delegation_ancestor_tiers.push_back(target_tier);
    child_ctx.parent_conversation_id = parent_ctx.conversation_id;
    // gh#158: see build_child_context — both builders inherit the key, or
    // the resumed path reintroduces the shared-bucket collision on its own.
    child_ctx.session_key = parent_ctx.session_key;
    child_ctx.active_phase = "default";
    child_ctx.locked_tier = target_tier;
    child_ctx.messages = std::move(seed_history);
    bool has_system = !child_ctx.messages.empty()
                       && child_ctx.messages.front().role == "system";
    if (!has_system && !info.system_prompt.empty()) {
        Message sys;
        sys.role = "system";
        sys.content = info.system_prompt;
        child_ctx.messages.insert(child_ctx.messages.begin(),
                                  std::move(sys));
    }
    Message user;
    user.role = "user";
    user.content = task;
    if (!info.completion_instructions.empty()) {
        user.content += "\n\n" + info.completion_instructions;
    }
    child_ctx.messages.push_back(std::move(user));
    return child_ctx;
}
Activity · 22 steps
lines 475–475LoopContext child_ctx;lines 476–476child_ctx.delegation_depth = parent_ctx.delegation_depth + 1;lines 477–478child_ctx.delegation_ancestor_tiers = parent_ctx.delegation_ancestor_tiers;lines 479–479child_ctx.delegation_ancestor_tiers.push_back(target_tier);lines 480–480child_ctx.parent_conversation_id = parent_ctx.conversation_id;lines 483–483child_ctx.session_key = parent_ctx.session_key;lines 484–484child_ctx.active_phase = "default";lines 485–485child_ctx.locked_tier = target_tier;lines 486–486child_ctx.messages = std::move(seed_history);lines 487–488bool has_system = !child_ctx.messages.empty() && child_ctx.messages.front().role == "system";lines 489–489◇ if (!has_system && !info.system_prompt.empty())lines 490–490Message sys;lines 491–491sys.role = "system";lines 492–492sys.content = info.system_prompt;lines 493–494child_ctx.messages.insert(child_ctx.messages.begin(), std::move(sys));lines 496–496Message user;lines 497–497user.role = "user";lines 498–498user.content = task;lines 499–499◇ if (!info.completion_instructions.empty())lines 500–500user.content += "\n\n" + info.completion_instructions;lines 502–502child_ctx.messages.push_back(std::move(user));lines 503–503return child_ctx;

Requirements

REQ-DELEG-002

check_delegation_preconditions

std::optional< DelegationResult > entropic::DelegationManager::check_delegation_preconditions(const ChildContextInfo &info, const std::string &target_tier, const std::string &task, const std::string &del_id, int depth, std::optional< SandboxInfo > &sb_info_out)

Run the three pre-flight checks for a single delegation.

src/core/delegation.cpp:349

Source · 39 lines
DelegationManager::check_delegation_preconditions(
    const ChildContextInfo& info,
    const std::string& target_tier,
    const std::string& task,
    const std::string& del_id,
    int depth,
    std::optional<SandboxInfo>& sb_info) {
    std::optional<DelegationResult> early;
    if (!info.valid) {
        logger->error("Tier '{}' not found", target_tier);
        early = DelegationResult{
            "Unknown tier: " + target_tier, false, target_tier, task};
    } else if (fire_start_cb(del_id, target_tier, task, depth, false)
               == ENT_DECISION_REJECT) {
        logger->info("Delegation {} ({}) rejected by start callback",
                     del_id, target_tier);
        early = DelegationResult{
            "Delegation rejected by consumer", false, target_tier, task};
    } else if (sandbox_mgr_ != nullptr) {
        sb_info = sandbox_mgr_->create_sandbox(del_id);
        // gh#160: `del_id` is already unique per sibling (see
        // `mint_delegation_id`); the sandbox dir and the pending patch
        // therefore no longer collide between two delegations at one depth.
        if (!sb_info.has_value()) {
            // gh#33 bug 2 (v2.1.6): pre-2.1.6 a failed create_sandbox
            // silently fell through to running the child against the
            // parent's cwd and surfaced an opaque
            // "(No response from delegate)" on later failure. The
            // sandbox-unavailable mode is now consumer-visible.
            logger->error(
                "Delegation {} ({}): session sandbox unavailable",
                del_id, target_tier);
            early = DelegationResult{
                "(DELEGATION FAILED: session sandbox unavailable)",
                false, target_tier, task};
        }
    }
    return early;
}
Activity · 15 steps
lines 356–356std::optional<DelegationResult> early;lines 357–357◇ if (!info.valid)lines 358–358logger->error("Tier '{}' not found", target_tier);lines 359–360early = DelegationResult{ "Unknown tier: " + target_tier, false, target_tier, task};lines 361–361elselines 361–362◇ if (fire_start_cb(del_id, target_tier, task, depth, false) == ENT_DECISION_REJECT)lines 363–364logger->info("Delegation {} ({}) rejected by start callback", del_id, target_tier);lines 365–366early = DelegationResult{ "Delegation rejected by consumer", false, target_tier, task};lines 367–367elselines 367–367◇ if (sandbox_mgr_ != nullptr)lines 368–368sb_info = sandbox_mgr_->create_sandbox(del_id);lines 372–372◇ if (!sb_info.has_value())lines 378–380logger->error( "Delegation {} ({}): session sandbox unavailable", del_id, target_tier);lines 381–383early = DelegationResult{ "(DELEGATION FAILED: session sandbox unavailable)", false, target_tier, task};lines 386–386return early;

Requirements

REQ-DELEG-002

complete_storage_record

void entropic::DelegationManager::complete_storage_record(const std::string &delegation_id, const DelegationResult &result)

Complete delegation storage record.

src/core/delegation.cpp:891

Show on the map →

Called by run_child

Calls none

Source · 12 lines
void DelegationManager::complete_storage_record(
    const std::string& delegation_id,
    const DelegationResult& result) {
    if (!storage_ || !storage_->complete_delegation
        || delegation_id.empty()) {
        return;
    }
    const char* status = result.success ? "completed" : "failed";
    storage_->complete_delegation(
        delegation_id.c_str(), status,
        result.summary.c_str(), storage_->user_data);
}
Activity · 4 steps
lines 894–895◇ if (!storage_ || !storage_->complete_delegation || delegation_id.empty())lines 896–896return;lines 898–898const char* status = result.success ? "completed" : "failed";lines 899–901storage_->complete_delegation( delegation_id.c_str(), status, result.summary.c_str(), storage_->user_data);

Requirements

REQ-DELEG-002

create_storage_record

std::string entropic::DelegationManager::create_storage_record(LoopContext &child_ctx, const std::string &target_tier, const std::string &task, std::optional< int > max_turns)

Create delegation storage record.

src/core/delegation.cpp:866

Show on the map →

Called by run_child

Calls none

Source · 17 lines
std::string DelegationManager::create_storage_record(
    LoopContext& child_ctx, const std::string& target_tier,
    const std::string& task, std::optional<int> max_turns) {
    if (!storage_ || !storage_->create_delegation) {
        return "";
    }
    std::string del_id, child_conv_id;
    auto src_tier = child_ctx.locked_tier.empty()
        ? "root" : child_ctx.locked_tier.c_str();
    storage_->create_delegation(
        child_ctx.parent_conversation_id.c_str(),
        src_tier, target_tier.c_str(), task.c_str(),
        max_turns.value_or(0), del_id, child_conv_id,
        storage_->user_data);
    child_ctx.conversation_id = child_conv_id;
    return del_id;
}
Activity · 7 steps
lines 869–869◇ if (!storage_ || !storage_->create_delegation)lines 870–870return "";lines 872–872std::string del_id, child_conv_id;lines 873–874auto src_tier = child_ctx.locked_tier.empty() ? "root" : child_ctx.locked_tier.c_str();lines 875–879storage_->create_delegation( child_ctx.parent_conversation_id.c_str(), src_tier, target_tier.c_str(), task.c_str(), max_turns.value_or(0), del_id, child_conv_id, storage_->user_data);lines 880–880child_ctx.conversation_id = child_conv_id;lines 881–881return del_id;

Requirements

REQ-DELEG-002

execute_delegation

DelegationResult entropic::DelegationManager::execute_delegation(LoopContext &parent_ctx, const std::string &target_tier, const std::string &task, std::optional< int > max_turns=std::nullopt, const std::vector< ContextRef > &context={})

Run a child inference loop for the target tier.

src/core/delegation.cpp:399

Source · 44 lines
DelegationResult DelegationManager::execute_delegation(
    LoopContext& parent_ctx,
    const std::string& target_tier,
    const std::string& task,
    std::optional<int> max_turns,
    const std::vector<ContextRef>& context) {

    logger->info("Delegation: target_tier='{}', task='{}', depth={}",
                 target_tier, task,
                 parent_ctx.delegation_depth + 1);
    auto info = tier_res_.resolve_tier
        ? tier_res_.resolve_tier(target_tier, tier_res_.user_data)
        : ChildContextInfo{};

    std::string del_id = mint_delegation_id(
        "d" + std::to_string(parent_ctx.delegation_depth + 1));
    std::optional<SandboxInfo> sb_info;
    if (auto early = check_delegation_preconditions(
            info, target_tier, task, del_id,
            parent_ctx.delegation_depth + 1, sb_info)) {
        return *early;
    }

    auto child_ctx = build_child_context(parent_ctx, info, task, context);
    child_ctx.locked_tier = target_tier;

    // gh#162: the storage record keeps what the child was actually given,
    // so "what did this child know" is answerable after the fact.
    const std::string recorded = format_context_block(context) + task;
    DelegationResult result;

    if (sb_info && swap_dir_fn_ != nullptr) {
        child_ctx.active_root = sb_info->path.string();
        ScopedSandbox scope(swap_dir_fn_, swap_dir_data_,
                            parent_ctx.session_key, sb_info->path,
                            restore_root_for(parent_ctx));
        result = run_child(child_ctx, target_tier, recorded, max_turns);
    } else {
        result = run_child(child_ctx, target_tier, recorded, max_turns);
    }

    finalize_sandbox_for(sb_info, result);
    return result;
}
Activity · 18 steps
lines 406–408logger->info("Delegation: target_tier='{}', task='{}', depth={}", target_tier, task, parent_ctx.delegation_depth + 1);lines 409–411auto info = tier_res_.resolve_tier ? tier_res_.resolve_tier(target_tier, tier_res_.user_data) : ChildContextInfo{};lines 413–414std::string del_id = mint_delegation_id( "d" + std::to_string(parent_ctx.delegation_depth + 1));lines 415–415std::optional<SandboxInfo> sb_info;lines 416–418◇ if (auto early = check_delegation_preconditions( info, target_tier, task, del_id, parent_ctx.delegation_depth + 1, sb_info))lines 419–419return *early;lines 422–422auto child_ctx = build_child_context(parent_ctx, info, task, context);lines 423–423child_ctx.locked_tier = target_tier;lines 427–427const std::string recorded = format_context_block(context) + task;lines 428–428DelegationResult result;lines 430–430◇ if (sb_info && swap_dir_fn_ != nullptr)lines 431–431child_ctx.active_root = sb_info->path.string();lines 432–434ScopedSandbox scope(swap_dir_fn_, swap_dir_data_, parent_ctx.session_key, sb_info->path, restore_root_for(parent_ctx));lines 435–435result = run_child(child_ctx, target_tier, recorded, max_turns);lines 436–436elselines 437–437result = run_child(child_ctx, target_tier, recorded, max_turns);lines 440–440finalize_sandbox_for(sb_info, result);lines 441–441return result;

Requirements

REQ-DELEG-002

execute_pipeline

DelegationResult entropic::DelegationManager::execute_pipeline(LoopContext &parent_ctx, const std::vector< std::string > &stages, const std::string &task, std::vector< DelegationResult > &stage_log, const std::vector< ContextRef > &context={})

Run a multi-stage delegation pipeline sequentially.

src/core/delegation.cpp:614

Source · 50 lines
DelegationResult DelegationManager::execute_pipeline(
    LoopContext& parent_ctx,
    const std::vector<std::string>& stages,
    const std::string& task,
    std::vector<DelegationResult>& stage_log,
    const std::vector<ContextRef>& context) {

    logger->info("Pipeline: {} stages, task='{}'", stages.size(), task);

    // gh#29 (v2.1.5): single pre-flight gate for the whole pipeline.
    auto first = stages.empty() ? std::string{} : stages.front();
    if (fire_start_cb("pipeline", first, task,
                      parent_ctx.delegation_depth + 1, true)
        == ENT_DECISION_REJECT) {
        logger->info("Pipeline rejected by start callback");
        return {"Pipeline rejected by consumer", false, first, task};
    }

    // Shared sandbox for the entire pipeline (gh#29). Each stage runs
    // inside the same directory so later stages observe earlier stages'
    // file edits — preserving the v2.1.4 forward-carry behavior.
    std::optional<SandboxInfo> shared_sb;
    if (sandbox_mgr_ != nullptr) {
        shared_sb = sandbox_mgr_->create_sandbox(
            mint_delegation_id("pipeline"));
        if (!shared_sb.has_value()) {
            // gh#33 bug 2 (v2.1.6): see execute_delegation comment.
            logger->error(
                "Pipeline ({} stages): session sandbox unavailable",
                stages.size());
            return {"(DELEGATION FAILED: session sandbox unavailable)",
                    false, first, task};
        }
    }

    DelegationResult last_result;
    last_result.task = task;

    for (size_t i = 0; i < stages.size(); ++i) {
        // gh#162: every stage opens with the same seeded references.
        if (!run_pipeline_stage(parent_ctx, stages, i,
                                format_context_block(context) + task,
                                shared_sb, stage_log, last_result)) {
            break;
        }
    }

    finalize_sandbox_for(shared_sb, last_result);
    return last_result;
}
Activity · 18 steps
lines 621–621logger->info("Pipeline: {} stages, task='{}'", stages.size(), task);lines 624–624auto first = stages.empty() ? std::string{} : stages.front();lines 625–627◇ if (fire_start_cb("pipeline", first, task, parent_ctx.delegation_depth + 1, true) == ENT_DECISION_REJECT)lines 628–628logger->info("Pipeline rejected by start callback");lines 629–629return {"Pipeline rejected by consumer", false, first, task};lines 635–635std::optional<SandboxInfo> shared_sb;lines 636–636◇ if (sandbox_mgr_ != nullptr)lines 637–638shared_sb = sandbox_mgr_->create_sandbox( mint_delegation_id("pipeline"));lines 639–639◇ if (!shared_sb.has_value())lines 641–643logger->error( "Pipeline ({} stages): session sandbox unavailable", stages.size());lines 644–645return {"(DELEGATION FAILED: session sandbox unavailable)", false, first, task};lines 649–649DelegationResult last_result;lines 650–650last_result.task = task;lines 652–652◇ for (size_t i = 0; i < stages.size(); ++i)lines 654–656◇ if (!run_pipeline_stage(parent_ctx, stages, i, format_context_block(context) + task, shared_sb, stage_log, last_result))lines 657–657break;lines 661–661finalize_sandbox_for(shared_sb, last_result);lines 662–662return last_result;

Requirements

REQ-DELEG-004

execute_resume_delegation

DelegationResult entropic::DelegationManager::execute_resume_delegation(LoopContext &parent_ctx, const std::string &target_tier, const std::string &task, std::vector< Message > seed_history, std::optional< int > max_turns=std::nullopt, const std::vector< ContextRef > &context={})

Resume a prior delegation with pre-loaded conversation history.

src/core/delegation.cpp:513

Source · 42 lines
DelegationResult DelegationManager::execute_resume_delegation(
    LoopContext& parent_ctx,
    const std::string& target_tier,
    const std::string& task,
    std::vector<Message> seed_history,
    std::optional<int> max_turns,
    const std::vector<ContextRef>& context) {

    logger->info("Resume delegation: target_tier='{}' task='{}' "
                 "history_messages={}",
                 target_tier, task, seed_history.size());
    auto info = tier_res_.resolve_tier
        ? tier_res_.resolve_tier(target_tier, tier_res_.user_data)
        : ChildContextInfo{};

    std::string del_id = mint_delegation_id(
        "d" + std::to_string(parent_ctx.delegation_depth + 1) + "r");
    std::optional<SandboxInfo> sb_info;
    if (auto early = check_delegation_preconditions(
            info, target_tier, task, del_id,
            parent_ctx.delegation_depth + 1, sb_info)) {
        return *early;
    }

    const std::string recorded = format_context_block(context) + task;
    auto child_ctx = build_resumed_child_context(
        parent_ctx, info, target_tier, recorded,  // gh#162
        std::move(seed_history));

    DelegationResult result;
    if (sb_info && swap_dir_fn_ != nullptr) {
        child_ctx.active_root = sb_info->path.string();
        ScopedSandbox scope(swap_dir_fn_, swap_dir_data_,
                            parent_ctx.session_key, sb_info->path,
                            restore_root_for(parent_ctx));
        result = run_child(child_ctx, target_tier, recorded, max_turns);
    } else {
        result = run_child(child_ctx, target_tier, recorded, max_turns);
    }
    finalize_sandbox_for(sb_info, result);
    return result;
}
Activity · 17 steps
lines 521–523logger->info("Resume delegation: target_tier='{}' task='{}' " "history_messages={}", target_tier, task, seed_history.size());lines 524–526auto info = tier_res_.resolve_tier ? tier_res_.resolve_tier(target_tier, tier_res_.user_data) : ChildContextInfo{};lines 528–529std::string del_id = mint_delegation_id( "d" + std::to_string(parent_ctx.delegation_depth + 1) + "r");lines 530–530std::optional<SandboxInfo> sb_info;lines 531–533◇ if (auto early = check_delegation_preconditions( info, target_tier, task, del_id, parent_ctx.delegation_depth + 1, sb_info))lines 534–534return *early;lines 537–537const std::string recorded = format_context_block(context) + task;lines 538–540auto child_ctx = build_resumed_child_context( parent_ctx, info, target_tier, recorded, // gh#162 std::move(seed_history));lines 542–542DelegationResult result;lines 543–543◇ if (sb_info && swap_dir_fn_ != nullptr)lines 544–544child_ctx.active_root = sb_info->path.string();lines 545–547ScopedSandbox scope(swap_dir_fn_, swap_dir_data_, parent_ctx.session_key, sb_info->path, restore_root_for(parent_ctx));lines 548–548result = run_child(child_ctx, target_tier, recorded, max_turns);lines 549–549elselines 550–550result = run_child(child_ctx, target_tier, recorded, max_turns);lines 552–552finalize_sandbox_for(sb_info, result);lines 553–553return result;

Requirements

REQ-DELEG-002

extract_summary

std::string entropic::DelegationManager::extract_summary(const LoopContext &child_ctx) const

Extract the delegation summary from child context.

src/core/delegation.cpp:827

Source · 18 lines
std::string DelegationManager::extract_summary(
    const LoopContext& child_ctx) const {
    // Prefer explicit completion summary
    auto it = child_ctx.metadata.find("explicit_completion_summary");
    if (it != child_ctx.metadata.end() && !it->second.empty()) {
        return mcp::sanitize_utf8(it->second);
    }

    // Fall back to last assistant message
    for (auto rit = child_ctx.messages.rbegin();
         rit != child_ctx.messages.rend(); ++rit) {
        if (rit->role == "assistant" && !rit->content.empty()) {
            return mcp::sanitize_utf8(rit->content);
        }
    }

    return "(No response from delegate)";
}
Activity · 7 steps
lines 830–830auto it = child_ctx.metadata.find("explicit_completion_summary");lines 831–831◇ if (it != child_ctx.metadata.end() && !it->second.empty())lines 832–832return mcp::sanitize_utf8(it->second);lines 836–836◇ for (auto rit = child_ctx.messages.rbegin(); rit != child_ctx.messages.rend(); ++rit)lines 838–838◇ if (rit->role == "assistant" && !rit->content.empty())lines 839–839return mcp::sanitize_utf8(rit->content);lines 843–843return "(No response from delegate)";

Requirements

REQ-DELEG-002

fire_start_cb

ent_decision_t entropic::DelegationManager::fire_start_cb(const std::string &delegation_id, const std::string &target_tier, const std::string &task, int depth, bool is_pipeline)

Invoke delegation_start_cb_ if set; return its decision.

src/core/delegation.cpp:163

Source · 29 lines
ent_decision_t DelegationManager::fire_start_cb(
    const std::string& delegation_id,
    const std::string& target_tier,
    const std::string& task,
    int depth,
    bool is_pipeline) {
    if (delegation_start_cb_ == nullptr) {
        return ENT_DECISION_ACCEPT;
    }
    ent_delegation_request_t req{};
    req.delegation_id = delegation_id.c_str();
    req.target_tier  = target_tier.c_str();
    req.task         = task.c_str();
    req.depth        = depth;
    req.is_pipeline  = is_pipeline ? 1 : 0;
    // Exception shield: per docs/architecture-cpp.md design rule #6,
    // exceptions do not cross .so boundaries. A buggy consumer
    // throwing a C++ exception out of the callback would otherwise
    // unwind through the engine's stack with undefined cleanup. Fail
    // safe by treating a throw as REJECT (gh#29 hardening).
    try {
        return delegation_start_cb_(&req, delegation_cb_data_);
    } catch (...) {
        logger->warn("delegation_start_cb threw for {}; treating as "
                     "REJECT (gh#29 exception shield)",
                     delegation_id);
        return ENT_DECISION_REJECT;
    }
}
Activity · 9 steps
lines 169–169◇ if (delegation_start_cb_ == nullptr)lines 170–170return ENT_DECISION_ACCEPT;lines 172–172ent_delegation_request_t req{};lines 173–173req.delegation_id = delegation_id.c_str();lines 174–174req.target_tier = target_tier.c_str();lines 175–175req.task = task.c_str();lines 176–176req.depth = depth;lines 177–177req.is_pipeline = is_pipeline ? 1 : 0;lines 183–190try { return delegation_start_cb_(&req, delegation_cb_data_); } catch (...) { logger->warn("delegation_start_cb threw for {}; treating as " "REJECT (gh#29 exception shield)", delegation_id); return ENT_DECISION_REJECT; }

Requirements

REQ-DELEG-002 REQ-DELEG-004

format_context_block

std::string entropic::DelegationManager::format_context_block(const std::vector< ContextRef > &context)

Render seeded file references as a [CONTEXT] block (gh#162).

src/core/delegation.cpp:802

Source · 17 lines
std::string DelegationManager::format_context_block(
    const std::vector<ContextRef>& context) {
    if (context.empty()) {
        return "";
    }
    std::string block =
        "[CONTEXT] The lead already located these files. Read them "
        "directly instead of searching:\n";
    for (const auto& ref : context) {
        block += "- " + ref.path;
        if (!ref.lines.empty()) { block += " (lines " + ref.lines + ")"; }
        if (!ref.note.empty()) { block += " — " + ref.note; }
        block += "\n";
    }
    block += "\n";
    return block;
}
Activity · 12 steps
lines 804–804◇ if (context.empty())lines 805–805return "";lines 807–809std::string block = "[CONTEXT] The lead already located these files. Read them " "directly instead of searching:\n";lines 810–810◇ for (const auto& ref : context)lines 811–811block += "- " + ref.path;lines 812–812◇ if (!ref.lines.empty())lines 812–812block += " (lines " + ref.lines + ")";lines 813–813◇ if (!ref.note.empty())lines 813–813block += " — " + ref.note;lines 814–814block += "\n";lines 816–816block += "\n";lines 817–817return block;

Requirements

REQ-DELEG-006

invoke_complete_cb

ent_decision_t entropic::DelegationManager::invoke_complete_cb(const ent_delegation_result_t &res, const std::string &delegation_id)

Invoke delegation_complete_cb_ under an exception shield.

src/core/delegation.cpp:287

Show on the map →

Called by deliver_sandbox_result

Calls none

Source · 13 lines
ent_decision_t DelegationManager::invoke_complete_cb(
    const ent_delegation_result_t& res, const std::string& delegation_id) {
    // Exception shield: a buggy consumer must never unwind through the
    // engine. Treat throw as REJECT so the patch is preserved on disk
    // for inspection (gh#29 hardening — same policy as fire_start_cb).
    try {
        return delegation_complete_cb_(&res, delegation_cb_data_);
    } catch (...) {
        logger->warn("delegation_complete_cb threw for {}; treating as "
                     "REJECT (patch preserved to pending/)", delegation_id);
        return ENT_DECISION_REJECT;
    }
}
Activity · 1 steps
lines 292–298try { return delegation_complete_cb_(&res, delegation_cb_data_); } catch (...) { logger->warn("delegation_complete_cb threw for {}; treating as " "REJECT (patch preserved to pending/)", delegation_id); return ENT_DECISION_REJECT; }

Requirements

REQ-DELEG-002

mint_delegation_id

std::string entropic::DelegationManager::mint_delegation_id(const std::string &prefix)

Mint a delegation id no sibling can collide with (gh#160).

src/core/delegation.cpp:100

Source · 7 lines
std::string DelegationManager::mint_delegation_id(
    const std::string& prefix) {
    if (sandbox_mgr_ == nullptr) {
        return prefix;
    }
    return sandbox_mgr_->next_delegation_id(prefix);
}
Activity · 3 steps
lines 102–102◇ if (sandbox_mgr_ == nullptr)lines 103–103return prefix;lines 105–105return sandbox_mgr_->next_delegation_id(prefix);

Requirements

REQ-DELEG-005

pipeline_context

static std::string entropic::pipeline_context(size_t stage_idx, size_t total, const std::vector< std::string > &stages, const std::string &prior_output)

Build pipeline context prefix for a stage.

src/core/delegation.cpp:579

Source · 18 lines
static std::string pipeline_context(
    size_t stage_idx, size_t total,
    const std::vector<std::string>& stages,
    const std::string& prior_output) {
    std::string ctx = "[PIPELINE CONTEXT]\n";
    ctx += "Stage " + std::to_string(stage_idx + 1) +
           " of " + std::to_string(total) + "\n";
    ctx += "Role: " + stages[stage_idx] + "\n";
    ctx += "Stay within your role. Do not perform work "
           "outside your stage's responsibility.\n";
    if (!prior_output.empty()) {
        ctx += "\n[PRIOR STAGE OUTPUT]\n";
        ctx += prior_output;
        ctx += "\n";
    }
    ctx += "\n";
    return ctx;
}
Activity · 10 steps
lines 583–583std::string ctx = "[PIPELINE CONTEXT]\n";lines 584–585ctx += "Stage " + std::to_string(stage_idx + 1) + " of " + std::to_string(total) + "\n";lines 586–586ctx += "Role: " + stages[stage_idx] + "\n";lines 587–588ctx += "Stay within your role. Do not perform work " "outside your stage's responsibility.\n";lines 589–589◇ if (!prior_output.empty())lines 590–590ctx += "\n[PRIOR STAGE OUTPUT]\n";lines 591–591ctx += prior_output;lines 592–592ctx += "\n";lines 594–594ctx += "\n";lines 595–595return ctx;

Requirements

REQ-DELEG-004

restore_root_for

std::filesystem::path entropic::DelegationManager::restore_root_for(const LoopContext &parent_ctx) const

Directory a finishing delegation restores the tools to.

src/core/delegation.cpp:121

Source · 7 lines
std::filesystem::path DelegationManager::restore_root_for(
    const LoopContext& parent_ctx) const {
    if (!parent_ctx.active_root.empty()) {
        return std::filesystem::path(parent_ctx.active_root);
    }
    return repo_dir_;
}
Activity · 3 steps
lines 123–123◇ if (!parent_ctx.active_root.empty())lines 124–124return std::filesystem::path(parent_ctx.active_root);lines 126–126return repo_dir_;

Requirements

REQ-DELEG-005

run_child

DelegationResult entropic::DelegationManager::run_child(LoopContext &child_ctx, const std::string &target_tier, const std::string &task, std::optional< int > max_turns)

Run child loop with todo save/restore.

src/core/delegation.cpp:917

Source · 55 lines
DelegationResult DelegationManager::run_child(
    LoopContext& child_ctx,
    const std::string& target_tier,
    const std::string& task,
    std::optional<int> max_turns) {

    // Save parent todo list
    std::string saved_todo;
    if (todo_callbacks_.save != nullptr) {
        saved_todo = todo_callbacks_.save(todo_callbacks_.user_data);
    }
    if (todo_callbacks_.install_fresh != nullptr) {
        todo_callbacks_.install_fresh(todo_callbacks_.user_data);
    }

    auto delegation_id = create_storage_record(
        child_ctx, target_tier, task, max_turns);

    // gh#182 (v2.13.0): until now `max_turns` reached the storage row and
    // stopped — `run_child_fn_` takes no limit, so an argument the model is
    // SHOWN in delegate.json (minimum 1, maximum 30) and allowed to set
    // bounded nothing. Carrying it on the child context is what lets
    // AgentEngine::resolve_max_iterations see it; that resolver takes the
    // stricter of this and the operator's own limit, so a request larger
    // than the tier or engine allows still cannot raise the bound.
    if (max_turns.has_value() && *max_turns > 0) {
        child_ctx.delegated_max_turns = *max_turns;
        logger->info("Child loop bound requested by model: tier={} "
                     "max_turns={}", target_tier, *max_turns);
    }

    logger->info("Running child loop: tier={} depth={} msgs={} "
                 "system_hash={:016x}",
                 target_tier, child_ctx.delegation_depth,
                 child_ctx.messages.size(),
                 std::hash<std::string>{}(
                     child_ctx.messages.empty()
                         ? std::string{}
                         : child_ctx.messages[0].content));

    if (run_child_fn_ != nullptr) {
        run_child_fn_(child_ctx, run_child_data_);
    }

    // Restore parent todo list
    if (todo_callbacks_.restore != nullptr && !saved_todo.empty()) {
        todo_callbacks_.restore(saved_todo, todo_callbacks_.user_data);
    }

    auto result = build_child_result(
        target_tier, task, child_ctx);
    complete_storage_record(delegation_id, result);
    log_child_result(result);
    return result;
}
Activity · 18 steps
lines 924–924std::string saved_todo;lines 925–925◇ if (todo_callbacks_.save != nullptr)lines 926–926saved_todo = todo_callbacks_.save(todo_callbacks_.user_data);lines 928–928◇ if (todo_callbacks_.install_fresh != nullptr)lines 929–929todo_callbacks_.install_fresh(todo_callbacks_.user_data);lines 932–933auto delegation_id = create_storage_record( child_ctx, target_tier, task, max_turns);lines 942–942◇ if (max_turns.has_value() && *max_turns > 0)lines 943–943child_ctx.delegated_max_turns = *max_turns;lines 944–945logger->info("Child loop bound requested by model: tier={} " "max_turns={}", target_tier, *max_turns);lines 948–955logger->info("Running child loop: tier={} depth={} msgs={} " "system_hash={:016x}", target_tier, child_ctx.delegation_depth, child_ctx.messages.size(), std::hash<std::string>{}( child_ctx.messages.empty() ? std::string{} : child_ctx.messages[0].content));lines 957–957◇ if (run_child_fn_ != nullptr)lines 958–958run_child_fn_(child_ctx, run_child_data_);lines 962–962◇ if (todo_callbacks_.restore != nullptr && !saved_todo.empty())lines 963–963todo_callbacks_.restore(saved_todo, todo_callbacks_.user_data);lines 966–967auto result = build_child_result( target_tier, task, child_ctx);lines 968–968complete_storage_record(delegation_id, result);lines 969–969log_child_result(result);lines 970–970return result;

Requirements

REQ-DELEG-002

run_pipeline_stage

bool entropic::DelegationManager::run_pipeline_stage(LoopContext &parent_ctx, const std::vector< std::string > &stages, size_t stage_idx, const std::string &task, const std::optional< SandboxInfo > &shared_sb, std::vector< DelegationResult > &stage_log, DelegationResult &last_result)

Run one pipeline stage; returns false to stop pipeline.

src/core/delegation.cpp:684

Source · 46 lines
bool DelegationManager::run_pipeline_stage(
    LoopContext& parent_ctx,
    const std::vector<std::string>& stages,
    size_t stage_idx,
    const std::string& task,
    const std::optional<SandboxInfo>& shared_sb,
    std::vector<DelegationResult>& stage_log,
    DelegationResult& last_result) {

    const auto& tier_name = stages[stage_idx];
    std::string prior = (stage_idx == 0) ? std::string{} : last_result.summary;
    std::string stage_task =
        pipeline_context(stage_idx, stages.size(), stages, prior) + task;

    auto info = tier_res_.resolve_tier
        ? tier_res_.resolve_tier(tier_name, tier_res_.user_data)
        : ChildContextInfo{};

    if (!info.valid) {
        logger->error("Pipeline stage {}: tier '{}' not found",
                      stage_idx, tier_name);
        last_result.success = false;
        last_result.summary = "Unknown tier: " + tier_name;
        return false;
    }

    auto child_ctx = build_child_context(parent_ctx, info, stage_task);
    child_ctx.locked_tier = tier_name;

    if (shared_sb && swap_dir_fn_ != nullptr) {
        child_ctx.active_root = shared_sb->path.string();
        ScopedSandbox scope(swap_dir_fn_, swap_dir_data_,
                            parent_ctx.session_key, shared_sb->path,
                            restore_root_for(parent_ctx));
        last_result = run_child(child_ctx, tier_name, stage_task,
                                std::nullopt);
    } else {
        last_result = run_child(child_ctx, tier_name, stage_task,
                                std::nullopt);
    }

    stage_log.push_back(last_result);
    logger->info("Pipeline stage {} ({}): {}", stage_idx, tier_name,
                 last_result.success ? "complete" : "failed");
    return last_result.success;
}
Activity · 20 steps
lines 693–693const auto& tier_name = stages[stage_idx];lines 694–694std::string prior = (stage_idx == 0) ? std::string{} : last_result.summary;lines 695–696std::string stage_task = pipeline_context(stage_idx, stages.size(), stages, prior) + task;lines 698–700auto info = tier_res_.resolve_tier ? tier_res_.resolve_tier(tier_name, tier_res_.user_data) : ChildContextInfo{};lines 702–702◇ if (!info.valid)lines 703–704logger->error("Pipeline stage {}: tier '{}' not found", stage_idx, tier_name);lines 705–705last_result.success = false;lines 706–706last_result.summary = "Unknown tier: " + tier_name;lines 707–707return false;lines 710–710auto child_ctx = build_child_context(parent_ctx, info, stage_task);lines 711–711child_ctx.locked_tier = tier_name;lines 713–713◇ if (shared_sb && swap_dir_fn_ != nullptr)lines 714–714child_ctx.active_root = shared_sb->path.string();lines 715–717ScopedSandbox scope(swap_dir_fn_, swap_dir_data_, parent_ctx.session_key, shared_sb->path, restore_root_for(parent_ctx));lines 718–719last_result = run_child(child_ctx, tier_name, stage_task, std::nullopt);lines 720–720elselines 721–722last_result = run_child(child_ctx, tier_name, stage_task, std::nullopt);lines 725–725stage_log.push_back(last_result);lines 726–727logger->info("Pipeline stage {} ({}): {}", stage_idx, tier_name, last_result.success ? "complete" : "failed");lines 728–728return last_result.success;

Requirements

REQ-DELEG-004

set_delegation_callbacks

void entropic::DelegationManager::set_delegation_callbacks(ent_decision_t(*on_start)(const ent_delegation_request_t *, void *), ent_decision_t(*on_complete)(const ent_delegation_result_t *, void *), void *user_data)

Set delegation start/complete callbacks (gh#29, v2.1.5).

src/core/delegation.cpp:137

Source · 8 lines
void DelegationManager::set_delegation_callbacks(
    ent_decision_t (*on_start)(const ent_delegation_request_t*, void*),
    ent_decision_t (*on_complete)(const ent_delegation_result_t*, void*),
    void* user_data) {
    delegation_start_cb_ = on_start;
    delegation_complete_cb_ = on_complete;
    delegation_cb_data_ = user_data;
}
Activity · 3 steps
lines 141–141delegation_start_cb_ = on_start;lines 142–142delegation_complete_cb_ = on_complete;lines 143–143delegation_cb_data_ = user_data;

Requirements

REQ-DELEG-002