greentic-bundle 1.1.0

Greentic bundle authoring CLI scaffold with embedded i18n and answer-document contracts.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
//! Extract `dw.agent` references from compiled flow manifests and collect
//! agent ids provided by agentic-worker packs.
//!
//! These two helpers are the read-side primitives for Task 5's auto-wiring
//! resolution pass:
//!
//! * [`referenced_dw_agents`] — scans `manifest.cbor` bytes from application
//!   packs and returns every `(flow_id, node_id, agent_id)` triple where a node
//!   has `component.id == "dw.agent"` and a non-empty `component.operation`.
//!
//! * [`provided_agent_ids`] — reads `dw-agents.json` sidecar bytes (one per
//!   pack) and returns the top-level JSON-object keys (the agent ids declared
//!   by that pack).  The discriminator for "this pack provides agents" is the
//!   **presence of the `dw-agents.json` sidecar** inside the `.gtpack` — NOT
//!   the manifest `kind` field (packc collapses `dw-application` → `application`
//!   and hardcodes the manifest `agents` map empty; the real data lives only in
//!   the sidecar).
//!
//! ## IR shape — `referenced_dw_agents`
//!
//! `flow_manifests` are raw `manifest.cbor` bytes already extracted from a
//! `.gtpack` ZIP.  The manifest.cbor IR uses interned symbol tables:
//! `node.component.id` is an integer index into `symbols.component_ids`, and
//! `node.id` is an integer index into `symbols.node_ids`.  Inline string ids
//! are accepted as a defensive fallback (matching the rule in `greentic-start`'s
//! `agent_preflight`).
//!
//! ## IR shape — `provided_agent_ids`
//!
//! `sidecars` are raw `dw-agents.json` bytes, one per pack (packs that do not
//! contain a `dw-agents.json` file should not contribute a slice at all).  The
//! sidecar is a bare JSON object `{ "<agent_id>": <AgentConfig> }`; the caller
//! (Task 5) is responsible for reading the file from the ZIP.  This matches the
//! wire format produced by `packc agent_pack.rs` and consumed by
//! `greentic-runner pack.rs:2314–2327`.
//!
//! ## Mirror contract
//!
//! The extraction predicate here must stay byte-for-byte identical to
//! `greentic-start`'s `agent_preflight::referenced_dw_agents_from_manifest`
//! so that the bundle build and the runtime guard agree on what "referenced"
//! means.

use std::collections::BTreeSet;

use ciborium::Value;

/// Component id that marks an agentic-worker node in a compiled flow.
const DW_AGENT_COMPONENT_ID: &str = "dw.agent";

/// Scan `flow_manifests` (raw `manifest.cbor` bytes, one per pack) and collect
/// every `dw.agent` node reference.
///
/// Returns `(flow_id, node_id, agent_id)` for each node whose resolved
/// component id equals `"dw.agent"` and whose `component.operation` is
/// non-empty.  Mirrors `greentic-start`'s
/// `agent_preflight::referenced_dw_agents_from_manifest`.
///
/// Invalid / unreadable byte slices are silently skipped (fail-soft); only a
/// genuine `dw.agent` reference is surfaced.
pub(crate) fn referenced_dw_agents(flow_manifests: &[&[u8]]) -> Vec<(String, String, String)> {
    let mut refs = Vec::new();
    for bytes in flow_manifests {
        let Ok(manifest) = ciborium::de::from_reader::<Value, _>(*bytes) else {
            continue;
        };
        extract_dw_agent_refs(&manifest, &mut refs);
    }
    refs
}

/// Extract `dw.agent` references from one decoded `manifest.cbor`.
fn extract_dw_agent_refs(manifest: &Value, refs: &mut Vec<(String, String, String)>) {
    let component_ids = symbol_table(manifest, "component_ids");
    let node_ids = symbol_table(manifest, "node_ids");

    let Some(Value::Array(flows)) = map_get(manifest, "flows") else {
        return;
    };

    for flow_entry in flows {
        let flow_id = map_get(flow_entry, "id")
            .and_then(as_text)
            .unwrap_or_else(|| "<unknown-flow>".to_string());

        let Some(inner) = map_get(flow_entry, "flow") else {
            continue;
        };
        let Some(Value::Array(nodes)) = map_get(inner, "nodes") else {
            continue;
        };
        for node in nodes {
            let Some(component) = map_get(node, "component") else {
                continue;
            };
            let Some(component_id) = resolve_component_id(component, &component_ids) else {
                continue;
            };
            if component_id != DW_AGENT_COMPONENT_ID {
                continue;
            }
            let Some(agent_id) = map_get(component, "operation").and_then(as_text) else {
                continue;
            };
            if agent_id.is_empty() {
                continue;
            }
            let node_id = resolve_node_id(node, &node_ids);
            refs.push((flow_id.clone(), node_id, agent_id));
        }
    }
}

/// Scan `sidecars` (raw `dw-agents.json` bytes, one per pack) and collect
/// agent ids declared by each sidecar.
///
/// Each `&[u8]` is the bytes of one pack's `dw-agents.json` sidecar file.  The
/// sidecar is a bare JSON object `{ "<agent_id>": <AgentConfig> }` written by
/// `packc agent_pack.rs` and consumed by `greentic-runner pack.rs:2314–2327`.
///
/// For each byte slice:
///
/// 1. Parse as JSON.
/// 2. Skip unless the root value is a JSON object.
/// 3. Collect the non-empty top-level keys (the agent ids).
///
/// Malformed or non-object blobs are silently skipped (fail-soft, no panic),
/// mirroring the runner's "ignore malformed dw-agents.json" behavior.  The
/// caller is responsible for only passing slices from packs that actually
/// contain a `dw-agents.json` file; packs without the sidecar provide no
/// agents.
pub(crate) fn provided_agent_ids(sidecars: &[&[u8]]) -> BTreeSet<String> {
    let mut ids = BTreeSet::new();
    for bytes in sidecars {
        let Ok(json_value) = serde_json::from_slice::<serde_json::Value>(bytes) else {
            continue;
        };
        let Some(agent_map) = json_value.as_object() else {
            continue;
        };
        for key in agent_map.keys() {
            if !key.is_empty() {
                ids.insert(key.clone());
            }
        }
    }
    ids
}

// ---------------------------------------------------------------------------
// Auto-wiring resolution pass (Task 5)
// ---------------------------------------------------------------------------

/// Fetch, verify, and materialize agent packs for every `dw.agent` node that is
/// referenced by `flow_manifests` but not yet in `provided_sidecars`.
///
/// # Parameters
/// * `def` — bundle workspace definition; its `agent_packs` map resolves each
///   missing agent id to a coordinate (`store://<name>@<version>` or
///   `file://<path>`).
/// * `flow_manifests` — raw `manifest.cbor` bytes from already-materialized app
///   packs; passed to [`referenced_dw_agents`].
/// * `provided_sidecars` — raw `dw-agents.json` bytes from already-materialized
///   app packs; passed to [`provided_agent_ids`].
/// * `packs_dir` — directory where resolved agent `.gtpack` files are written.
/// * `cache_dir` — root cache directory for `fetch_store_agentic_worker_verified`.
/// * `offline` — when `true`, no network calls are made (cache only).
/// * `trust` — trusted signing-key set for Ed25519/DSSE verification.  An empty
///   `TrustRoot` falls back to sha256-only (fail-open for that specific check).
///
/// # Returns
/// A sorted, deduplicated list of agent ids that were newly materialized.
///
/// # Errors
/// * An agent id is referenced but has no `agent_packs` mapping → actionable bail.
/// * An agent pack is fetched but its `dw-agents.json` sidecar does not provide
///   the expected agent id → bail naming the mismatch.
/// * Any I/O or network error during fetch → propagated as `anyhow::Error`.
pub fn auto_wire_agent_packs(
    def: &super::BundleWorkspaceDefinition,
    flow_manifests: &[&[u8]],
    provided_sidecars: &[&[u8]],
    packs_dir: &std::path::Path,
    cache_dir: &std::path::Path,
    offline: bool,
    trust: &greentic_distributor_client::signing::TrustRoot,
) -> anyhow::Result<Vec<String>> {
    use anyhow::Context as _;

    let referenced = referenced_dw_agents(flow_manifests);
    let mut provided = provided_agent_ids(provided_sidecars);

    // Also fold in agent ids from packs already materialized in `packs_dir`.
    // This ensures idempotency (a second sync skips packs written by the first)
    // and offline safety (bundles wired online can be rebuilt offline as long as
    // the pack files are present on disk).
    //
    // Fail-soft: a missing or unreadable `packs_dir` (e.g. first run, empty dir)
    // is treated as contributing zero agents — no panic, no error.
    if packs_dir.is_dir()
        && let Ok(entries) = std::fs::read_dir(packs_dir)
    {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().and_then(|ext| ext.to_str()) == Some("gtpack")
                && let Ok(pack_bytes) = std::fs::read(&path)
                && let Some(sidecar_bytes) =
                    read_zip_entry_from_bytes(&pack_bytes, "dw-agents.json")
            {
                provided.extend(provided_agent_ids(&[sidecar_bytes.as_slice()]));
            }
        }
    }

    // Collect missing agent_ids and the flow_id of their first reference for error messages.
    let mut missing_by_id: std::collections::BTreeMap<String, String> =
        std::collections::BTreeMap::new();
    for (flow_id, _node_id, agent_id) in &referenced {
        if !provided.contains(agent_id) {
            missing_by_id
                .entry(agent_id.clone())
                .or_insert_with(|| flow_id.clone());
        }
    }

    if missing_by_id.is_empty() {
        return Ok(Vec::new());
    }

    // Map each missing agent_id to its coordinate — bail immediately on any unmapped id.
    let mut coordinate_to_agents: std::collections::BTreeMap<String, Vec<String>> =
        std::collections::BTreeMap::new();
    for (agent_id, flow_id) in &missing_by_id {
        let coordinate = def.agent_packs.get(agent_id).ok_or_else(|| {
            anyhow::anyhow!(
                "agent \"{agent_id}\" referenced by flow \"{flow_id}\" is not provided \
                 and has no agent_packs mapping — add \
                 agent_packs.{agent_id} = store://\u{2026} or include its pack"
            )
        })?;
        coordinate_to_agents
            .entry(coordinate.clone())
            .or_default()
            .push(agent_id.clone());
    }

    // Derive the store REST API base URL from the environment (test-overridable).
    let store_base = std::env::var("GREENTIC_STORE_URL")
        .unwrap_or_else(|_| "https://store.greentic.cloud".to_string());

    // Ensure the destination directory exists.
    std::fs::create_dir_all(packs_dir)
        .with_context(|| format!("create packs_dir {}", packs_dir.display()))?;

    let mut materialized: Vec<String> = Vec::new();

    for (coordinate, expected_agent_ids) in &coordinate_to_agents {
        let pack_bytes = fetch_coordinate_bytes(coordinate, &store_base, cache_dir, offline, trust)
            .with_context(|| format!("resolve agent pack coordinate {coordinate}"))?;

        // Verify the sidecar provides each expected agent id before writing.
        let sidecar_opt = read_zip_entry_from_bytes(&pack_bytes, "dw-agents.json");
        let actual_ids = match &sidecar_opt {
            Some(bytes) => provided_agent_ids(&[bytes.as_slice()]),
            None => BTreeSet::new(),
        };
        for agent_id in expected_agent_ids {
            if !actual_ids.contains(agent_id) {
                anyhow::bail!(
                    "agent pack at {coordinate} does not provide agent \"{agent_id}\" \
                     — expected it in dw-agents.json sidecar but the pack provides: [{}]",
                    actual_ids.iter().cloned().collect::<Vec<_>>().join(", ")
                );
            }
        }

        // Write the pack to packs_dir using a filesystem-safe filename.
        let filename = pack_filename_for_coordinate(coordinate);
        let dest = packs_dir.join(&filename);
        std::fs::write(&dest, &pack_bytes)
            .with_context(|| format!("write agent pack to {}", dest.display()))?;

        materialized.extend(expected_agent_ids.iter().cloned());
    }

    materialized.sort();
    materialized.dedup();
    Ok(materialized)
}

/// Fetch the raw `.gtpack` bytes for a coordinate.
fn fetch_coordinate_bytes(
    coordinate: &str,
    store_base: &str,
    cache_dir: &std::path::Path,
    offline: bool,
    trust: &greentic_distributor_client::signing::TrustRoot,
) -> anyhow::Result<Vec<u8>> {
    use anyhow::Context as _;
    use greentic_distributor_client::store_agentic_worker::fetch_store_agentic_worker_verified;

    if let Some(name_version) = coordinate.strip_prefix("store://") {
        let (name, version) = parse_store_name_version(name_version)
            .with_context(|| format!("parse store coordinate store://{name_version}"))?;
        return fetch_store_agentic_worker_verified(
            store_base, &name, &version, cache_dir, offline, trust,
        )
        .with_context(|| format!("fetch store agentic worker {name}@{version}"));
    }

    if let Some(path_str) = coordinate.strip_prefix("file://") {
        let path = std::path::PathBuf::from(path_str);
        return std::fs::read(&path)
            .with_context(|| format!("read agent pack from {}", path.display()));
    }

    anyhow::bail!(
        "unsupported agent pack coordinate scheme: \"{coordinate}\" \
         (expected store:// or file://)"
    )
}

/// Parse `<name>@<version>` from the path segment of a `store://` coordinate.
fn parse_store_name_version(name_version: &str) -> anyhow::Result<(String, String)> {
    let (name, version) = name_version.split_once('@').ok_or_else(|| {
        anyhow::anyhow!(
            "store coordinate must be in the form <name>@<version>, got: \"{name_version}\""
        )
    })?;
    if name.is_empty() {
        anyhow::bail!("store coordinate name is empty in \"{name_version}\"");
    }
    if version.is_empty() {
        anyhow::bail!("store coordinate version is empty in \"{name_version}\"");
    }
    Ok((name.to_string(), version.to_string()))
}

/// Derive a filesystem-safe `.gtpack` filename from a coordinate.
///
/// * `store://greentic.agentic-research-tavily-agent@0.1.0`
///   → `greentic.agentic-research-tavily-agent.gtpack`
/// * `file:///path/to/my-agent.gtpack`
///   → `my-agent.gtpack`
fn pack_filename_for_coordinate(coordinate: &str) -> String {
    if let Some(name_version) = coordinate.strip_prefix("store://") {
        let name = name_version.split('@').next().unwrap_or(name_version);
        return format!("{name}.gtpack");
    }
    if let Some(path_str) = coordinate.strip_prefix("file://") {
        let path = std::path::Path::new(path_str);
        if let Some(filename) = path.file_name() {
            let s = filename.to_string_lossy();
            if !s.ends_with(".gtpack") {
                return format!("{s}.gtpack");
            }
            return s.into_owned();
        }
    }
    // Fallback: sanitize the entire coordinate.
    let sanitized = coordinate
        .replace(['/', '\\', ':', '@', ' '], "_")
        .trim_matches('_')
        .to_string();
    format!("{sanitized}.gtpack")
}

/// Read a named entry from a `.gtpack` ZIP given its raw bytes.
///
/// Returns `None` when the entry is absent or the zip cannot be parsed.
pub(crate) fn read_zip_entry_from_bytes(pack_bytes: &[u8], entry_name: &str) -> Option<Vec<u8>> {
    use std::io::{Cursor, Read};
    let cursor = Cursor::new(pack_bytes);
    let mut archive = zip::ZipArchive::new(cursor).ok()?;
    let mut entry = archive.by_name(entry_name).ok()?;
    let mut buf = Vec::new();
    entry.read_to_end(&mut buf).ok()?;
    Some(buf)
}

// ---------------------------------------------------------------------------
// CBOR helpers — self-contained, using ciborium::Value.
// Mirrors greentic-start's agent_preflight helpers (same logic; different
// CBOR library: greentic-bundle uses ciborium, greentic-start uses serde_cbor).
// ---------------------------------------------------------------------------

/// Return `map[key]` for a text key, or `None` if the value is not a map or
/// the key is absent.
fn map_get<'a>(value: &'a Value, key: &str) -> Option<&'a Value> {
    let Value::Map(map) = value else {
        return None;
    };
    map.iter()
        .find(|(k, _)| matches!(k, Value::Text(t) if t == key))
        .map(|(_, v)| v)
}

fn as_text(value: &Value) -> Option<String> {
    match value {
        Value::Text(text) => Some(text.clone()),
        _ => None,
    }
}

/// Convert a CBOR integer to a `usize` index; returns `None` for negative
/// values or out-of-range conversions.
fn as_index(value: &Value) -> Option<usize> {
    if let Value::Integer(int) = value {
        let n: i128 = (*int).into();
        usize::try_from(n).ok()
    } else {
        None
    }
}

/// Read `manifest.symbols.<name>` as a vector of interned strings.
fn symbol_table(manifest: &Value, name: &str) -> Vec<String> {
    let Some(symbols) = map_get(manifest, "symbols") else {
        return Vec::new();
    };
    let Some(Value::Array(items)) = map_get(symbols, name) else {
        return Vec::new();
    };
    items.iter().filter_map(as_text).collect()
}

/// Resolve a node's component id from either an inline string (defensive) or
/// a symbol-table index (the normal compiled form).
fn resolve_component_id(component: &Value, component_ids: &[String]) -> Option<String> {
    let id = map_get(component, "id")?;
    if let Some(text) = as_text(id) {
        return Some(text);
    }
    let index = as_index(id)?;
    component_ids.get(index).cloned()
}

/// Resolve a node's human-readable id, falling back to the raw index string
/// when the symbol table cannot resolve it.
fn resolve_node_id(node: &Value, node_ids: &[String]) -> String {
    match map_get(node, "id") {
        Some(value) => {
            if let Some(text) = as_text(value) {
                return text;
            }
            if let Some(index) = as_index(value) {
                if let Some(name) = node_ids.get(index) {
                    return name.clone();
                }
                return format!("#{index}");
            }
            "<unknown-node>".to_string()
        }
        None => "<unknown-node>".to_string(),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // --- CBOR fixture helpers ------------------------------------------------

    fn cbor_map(pairs: Vec<(&str, Value)>) -> Value {
        Value::Map(
            pairs
                .into_iter()
                .map(|(k, v)| (Value::Text(k.to_string()), v))
                .collect(),
        )
    }

    fn cbor_array(items: Vec<Value>) -> Value {
        Value::Array(items)
    }

    fn text(s: &str) -> Value {
        Value::Text(s.to_string())
    }

    fn int(n: i64) -> Value {
        Value::Integer(ciborium::value::Integer::from(n))
    }

    fn to_cbor_bytes(value: &Value) -> Vec<u8> {
        let mut bytes = Vec::new();
        ciborium::into_writer(value, &mut bytes).expect("CBOR serialization must succeed");
        bytes
    }

    /// A `manifest.cbor` with `component_ids = ["ai.greentic.component-adaptive-card",
    /// "dw.agent"]`, `node_ids = ["reply", "research"]` and one flow whose
    /// `research` node references `tavily_researcher`.
    fn dw_agent_flow_manifest_bytes() -> Vec<u8> {
        let symbols = cbor_map(vec![
            (
                "component_ids",
                cbor_array(vec![
                    text("ai.greentic.component-adaptive-card"),
                    text("dw.agent"),
                ]),
            ),
            (
                "node_ids",
                cbor_array(vec![text("reply"), text("research")]),
            ),
        ]);
        let research_node = cbor_map(vec![
            ("id", int(1)),
            (
                "component",
                cbor_map(vec![
                    ("id", int(1)),
                    ("operation", text("tavily_researcher")),
                ]),
            ),
        ]);
        let reply_node = cbor_map(vec![
            ("id", int(0)),
            (
                "component",
                cbor_map(vec![("id", int(0)), ("operation", text("card"))]),
            ),
        ]);
        let flow_entry = cbor_map(vec![
            ("id", text("on_message")),
            (
                "flow",
                cbor_map(vec![("nodes", cbor_array(vec![research_node, reply_node]))]),
            ),
        ]);
        let manifest = cbor_map(vec![
            ("symbols", symbols),
            ("flows", cbor_array(vec![flow_entry])),
        ]);
        to_cbor_bytes(&manifest)
    }

    // --- referenced_dw_agents ------------------------------------------------

    #[test]
    fn extracts_dw_agent_reference_with_correct_triple() {
        let bytes = dw_agent_flow_manifest_bytes();
        let refs = referenced_dw_agents(&[&bytes]);
        assert_eq!(refs.len(), 1, "expected exactly one dw.agent reference");
        assert_eq!(
            refs[0],
            (
                "on_message".to_string(),
                "research".to_string(),
                "tavily_researcher".to_string()
            )
        );
    }

    #[test]
    fn skips_non_dw_agent_nodes() {
        // The manifest has both a card node (id=0) and a dw.agent node (id=1).
        // Only the dw.agent node must appear in the result.
        let bytes = dw_agent_flow_manifest_bytes();
        let refs = referenced_dw_agents(&[&bytes]);
        assert!(
            refs.iter()
                .all(|(_, _, agent)| agent == "tavily_researcher"),
            "the card node must not appear in the dw.agent references"
        );
    }

    #[test]
    fn empty_operation_node_is_skipped() {
        let symbols = cbor_map(vec![
            ("component_ids", cbor_array(vec![text("dw.agent")])),
            ("node_ids", cbor_array(vec![text("research")])),
        ]);
        let empty_op_node = cbor_map(vec![
            ("id", int(0)),
            (
                "component",
                cbor_map(vec![("id", int(0)), ("operation", text(""))]),
            ),
        ]);
        let flow_entry = cbor_map(vec![
            ("id", text("on_message")),
            (
                "flow",
                cbor_map(vec![("nodes", cbor_array(vec![empty_op_node]))]),
            ),
        ]);
        let manifest = cbor_map(vec![
            ("symbols", symbols),
            ("flows", cbor_array(vec![flow_entry])),
        ]);
        let bytes = to_cbor_bytes(&manifest);
        assert!(
            referenced_dw_agents(&[&bytes]).is_empty(),
            "a dw.agent node with empty operation must be skipped"
        );
    }

    #[test]
    fn multiple_manifests_are_scanned() {
        let bytes_a = dw_agent_flow_manifest_bytes();
        let symbols = cbor_map(vec![
            ("component_ids", cbor_array(vec![text("dw.agent")])),
            ("node_ids", cbor_array(vec![text("helper")])),
        ]);
        let node = cbor_map(vec![
            ("id", int(0)),
            (
                "component",
                cbor_map(vec![("id", int(0)), ("operation", text("demo_assistant"))]),
            ),
        ]);
        let flow_entry = cbor_map(vec![
            ("id", text("demo_flow")),
            ("flow", cbor_map(vec![("nodes", cbor_array(vec![node]))])),
        ]);
        let manifest_b = cbor_map(vec![
            ("symbols", symbols),
            ("flows", cbor_array(vec![flow_entry])),
        ]);
        let bytes_b = to_cbor_bytes(&manifest_b);
        let refs = referenced_dw_agents(&[&bytes_a, &bytes_b]);
        let agents: Vec<&str> = refs.iter().map(|(_, _, a)| a.as_str()).collect();
        assert!(
            agents.contains(&"tavily_researcher"),
            "tavily_researcher from manifest A must be present"
        );
        assert!(
            agents.contains(&"demo_assistant"),
            "demo_assistant from manifest B must be present"
        );
    }

    #[test]
    fn invalid_bytes_are_skipped() {
        let bad_bytes: &[u8] = b"not cbor at all";
        let refs = referenced_dw_agents(&[bad_bytes]);
        assert!(refs.is_empty(), "invalid CBOR must be silently skipped");
    }

    // --- provided_agent_ids (dw-agents.json sidecar) -------------------------

    /// Build a `dw-agents.json` sidecar byte fixture with the given agent ids.
    /// This is the same format packc writes:
    /// `serde_json::to_vec(&BTreeMap<String, serde_json::Value>)`.
    fn dw_agents_sidecar_bytes(agent_ids: &[&str]) -> Vec<u8> {
        let map: std::collections::BTreeMap<String, serde_json::Value> = agent_ids
            .iter()
            .map(|id| (id.to_string(), serde_json::json!({"kind": "placeholder"})))
            .collect();
        serde_json::to_vec(&map).expect("sidecar serialization must succeed")
    }

    #[test]
    fn provided_agent_ids_extracts_keys_from_json_sidecar() {
        // `{"tavily_researcher": {...}, "second_agent": {...}}` as JSON bytes
        let bytes = serde_json::to_vec(&serde_json::json!({
            "tavily_researcher": {"kind": "dw-agent", "llm": "openai"},
            "second_agent": {"kind": "dw-agent"}
        }))
        .unwrap();
        let ids = provided_agent_ids(&[&bytes]);
        assert!(
            ids.contains("tavily_researcher"),
            "tavily_researcher must be in the provided set"
        );
        assert!(
            ids.contains("second_agent"),
            "second_agent must be in the provided set"
        );
        assert_eq!(ids.len(), 2);
    }

    #[test]
    fn malformed_sidecar_blob_is_skipped_gracefully() {
        let bad: &[u8] = b"not json at all {{ broken";
        let ids = provided_agent_ids(&[bad]);
        assert!(
            ids.is_empty(),
            "a malformed sidecar must silently yield an empty set (no panic)"
        );
    }

    #[test]
    fn empty_json_object_yields_empty_set() {
        let bytes: &[u8] = b"{}";
        assert!(
            provided_agent_ids(&[bytes]).is_empty(),
            "an empty JSON object sidecar must yield an empty set"
        );
    }

    #[test]
    fn non_object_json_blob_yields_empty_set() {
        // A JSON array is valid JSON but not the expected object shape.
        let bytes = b"[\"some_key\"]";
        assert!(
            provided_agent_ids(&[bytes]).is_empty(),
            "a non-object JSON blob must be skipped (contributes nothing)"
        );
    }

    #[test]
    fn multiple_sidecars_are_aggregated() {
        let bytes_a = dw_agents_sidecar_bytes(&["agent_a"]);
        let bytes_b = dw_agents_sidecar_bytes(&["agent_b"]);
        let ids = provided_agent_ids(&[&bytes_a, &bytes_b]);
        assert!(
            ids.contains("agent_a"),
            "agent_a from sidecar A must be present"
        );
        assert!(
            ids.contains("agent_b"),
            "agent_b from sidecar B must be present"
        );
        assert_eq!(ids.len(), 2);
    }

    #[test]
    fn round_trip_guard_matches_packc_wire_format() {
        // Build the sidecar bytes EXACTLY as packc does in agent_pack.rs:
        // serde_json::to_vec(&BTreeMap<String, serde_json::Value>).
        // This pins the wire format and guards against future packc drift.
        let mut agents: std::collections::BTreeMap<String, serde_json::Value> =
            std::collections::BTreeMap::new();
        agents.insert(
            "crm_assistant".to_string(),
            serde_json::json!({"kind": "dw-agent", "llm_provider": "openai"}),
        );
        agents.insert(
            "email_drafter".to_string(),
            serde_json::json!({"kind": "dw-agent", "llm_provider": "anthropic"}),
        );
        let sidecar_bytes =
            serde_json::to_vec(&agents).expect("packc-style serialization must succeed");

        let ids = provided_agent_ids(&[&sidecar_bytes]);
        assert!(
            ids.contains("crm_assistant"),
            "crm_assistant must round-trip through the packc wire format"
        );
        assert!(
            ids.contains("email_drafter"),
            "email_drafter must round-trip through the packc wire format"
        );
        assert_eq!(ids.len(), 2, "only the declared agents must be present");
    }
}