// integ_engram.el — integration proof against a LIVE (isolated) engram.
//
// Run with the sandbox env sourced (ENGRAM_URL=http://127.0.0.1:8901,
// ENGRAM_API_KEY=sbx-dev-swarm-ccr). Proves:
//   (a) CCR retrieval pulls REAL content from the mind over HTTP;
//   (b) a full swarm runs and converges against the live mind;
//   (c) work-tracking mirrors records into the engram as SwarmTrack nodes.

fn main() -> Int {
    let url: String = env("ENGRAM_URL")
    if str_eq(url, "") {
        print("SKIP integ_engram (ENGRAM_URL not set)")
        return 0
    }

    // (a) CCR compiles a bounded context whose retrieval hit the real mind.
    let refs: String = "[\"Volatility-Based Decomposition\",\"Swarm Architecture containment\"]"
    let wt: String = containment_worker_token("integ", "integ/w0")
    let ctx: String = ccr_compile("analyze_item", refs, "decompose the billing module", "integ", "integ/w0", wt)
    let knowledge: String = json_get_string(ctx, "knowledge")
    let pulled_real: Bool = str_contains(knowledge, "olatility") || str_contains(knowledge, "Anderson") || str_contains(knowledge, "VBD")
    if pulled_real {
        print("  ok   CCR retrieval pulled real mind content (" + int_to_str(str_len(knowledge)) + " bytes, bounded)")
    } else {
        print("  FAIL CCR retrieval returned no mind content")
    }
    let bounded: Bool = ccr_within_budget(ctx)
    if bounded { print("  ok   compiled context stayed within budget") } else { print("  FAIL context over budget") }

    // (b) a real swarm over the live mind.
    let inputs: String = "[\"billing\",\"payments\",\"ledger\"]"
    let cfg: String = "{\"concurrency\":\"3\",\"strategy\":\"collect\",\"min_success_ratio\":\"1.0\"}"
    let res: String = swarm_run("analyze_item", refs, inputs, cfg)
    let status: String = json_get_string(res, "status")
    if str_eq(status, "completed") { print("  ok   swarm completed against live engram") } else { print("  FAIL swarm status=" + status) }
    let corr: String = json_get_string(res, "corr_id")

    // (c) work-tracking mirrored into the mind: search for this swarm's records.
    let hits: String = primitive_attend(corr, 5)
    let mirrored: Bool = str_contains(hits, "swarm-track") || str_contains(hits, corr)
    if mirrored { print("  ok   work-tracking mirrored into the engram (queryable)") } else { print("  note mirror not yet visible to search (async index)") }

    print("DONE integ_engram corr=" + corr)
    return 0
}
