multicast-workflows 2.0.0

Durable Code Mode workflows attached to multicast CLIs as first-party commands
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
//! Agent archetypes: a named task focus over this CLI's commands and workflows.
//!
//! An archetype is stored as linked parts that share one name:
//!
//! - a summary, the target-neutral fact of what the archetype is for;
//! - instructions, a Prompt Guide telling an agent how to approach the task;
//! - a scope, the names of the commands and workflows the task uses.
//!
//! Activating an archetype is an ordinary read-only command. It returns the
//! guidance and the contracts of the scoped commands and workflows as data.
//! Activation is advisory: nothing outside the scope is hidden or refused, and
//! the activation command's own contract never depends on an archetype's text.
//!
//! Archetypes come from two sources. A CLI author ships them with
//! [`crate::Workflows::archetype`]; each becomes a top-level command. An
//! operator saves them at runtime with `archetypes save`; those are activated
//! through `archetypes activate`. A shipped archetype shadows a saved one with
//! the same name.

use std::sync::Arc;

use async_trait::async_trait;
use multicast::cli::Cli;
use multicast::command::{
    CommandContext, CommandDef, CommandHandler, McpAnnotations, McpCommandOptions,
};
use multicast::output::CommandResult;
use multicast::schema::{FieldMeta, FieldType};
use serde_json::{Value, json};

use crate::database::{Connection, OptionalExtension, params};
use crate::{State, WorkflowDatabase, WorkflowDatabaseKind, error, field, ok, string_arg};

/// Name of the command group that manages archetypes.
pub const ARCHETYPES_GROUP_NAME: &str = "archetypes";

/// Longest accepted archetype instructions, in bytes.
const MAX_INSTRUCTIONS_BYTES: usize = 64 * 1024;

/// Most scope entries an archetype may name.
const MAX_SCOPE: usize = 256;

/// An archetype compiled into the CLI binary.
#[derive(Debug, Clone)]
pub(crate) struct ShippedArchetype {
    pub(crate) name: String,
    pub(crate) summary: String,
    pub(crate) instructions: String,
    pub(crate) scope: Vec<String>,
}

/// An archetype resolved for listing or activation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Archetype {
    pub(crate) name: String,
    pub(crate) summary: String,
    pub(crate) instructions: String,
    pub(crate) scope: Vec<String>,
    pub(crate) origin: &'static str,
}

impl Archetype {
    pub(crate) fn shipped(archetype: &ShippedArchetype) -> Self {
        Self {
            name: archetype.name.clone(),
            summary: archetype.summary.clone(),
            instructions: archetype.instructions.clone(),
            scope: archetype.scope.clone(),
            origin: "shipped",
        }
    }

    /// The listing entry: identity and scope without the guidance text.
    pub(crate) fn summary_json(&self) -> Value {
        json!({
            "name": self.name,
            "summary": self.summary,
            "origin": self.origin,
            "scope": self.scope,
        })
    }

    /// The full definition, including the guidance text.
    pub(crate) fn detail_json(&self) -> Value {
        let mut data = self.summary_json();
        data["instructions"] = Value::String(self.instructions.clone());
        data
    }
}

/// Fixed input description of every activation command.
pub(crate) const TASK_DESCRIPTION: &str =
    "The specific task to focus on; echoed back with the guidance";

/// Fixed output schema of every activation command.
///
/// It is independent of any archetype's summary, instructions, or scope, so
/// changing an archetype's text never changes a tool contract.
pub(crate) fn activation_output_schema() -> Value {
    json!({
        "type": "object",
        "properties": {
            "archetype": {"type": "string"},
            "origin": {"type": "string", "enum": ["shipped", "saved"]},
            "summary": {"type": "string"},
            "guidance": {"type": "string"},
            "task": {"type": ["string", "null"]},
            "tools": {"type": "array", "items": {"type": "object"}},
            "workflows": {"type": "array", "items": {"type": "object"}},
            "unavailable": {"type": "array", "items": {"type": "string"}}
        },
        "required": ["archetype", "origin", "summary", "guidance", "task", "tools", "workflows", "unavailable"]
    })
}

/// Checks the text fields shared by shipped and saved archetypes.
pub(crate) fn check_definition(
    name: &str,
    summary: &str,
    instructions: &str,
    scope: &[String],
) -> Result<(), String> {
    if name.trim().is_empty() || name.chars().any(char::is_whitespace) {
        return Err("Archetype name must be non-empty and contain no whitespace".into());
    }
    if summary.trim().is_empty() {
        return Err(format!("Archetype '{name}' needs a summary"));
    }
    if instructions.trim().is_empty() {
        return Err(format!("Archetype '{name}' needs instructions"));
    }
    if instructions.len() > MAX_INSTRUCTIONS_BYTES {
        return Err(format!(
            "Archetype '{name}' instructions exceed {MAX_INSTRUCTIONS_BYTES} bytes"
        ));
    }
    if scope.is_empty() {
        return Err(format!(
            "Archetype '{name}' must scope at least one command or workflow"
        ));
    }
    if scope.len() > MAX_SCOPE {
        return Err(format!(
            "Archetype '{name}' scopes more than {MAX_SCOPE} entries"
        ));
    }
    let mut seen = std::collections::BTreeSet::new();
    for entry in scope {
        if !seen.insert(entry.as_str()) {
            return Err(format!("Archetype '{name}' scopes '{entry}' twice"));
        }
    }
    Ok(())
}

/// Splits a comma-separated scope given on the command line, or accepts a JSON array.
pub(crate) fn parse_scope(value: Option<&Value>) -> Result<Vec<String>, String> {
    let entries: Vec<String> = match value {
        None | Some(Value::Null) => Vec::new(),
        Some(Value::String(text)) => text.split(',').map(str::to_string).collect(),
        Some(Value::Array(items)) => items
            .iter()
            .map(|item| {
                item.as_str()
                    .map(str::to_string)
                    .ok_or_else(|| "--tools entries must be strings".to_string())
            })
            .collect::<Result<_, _>>()?,
        Some(_) => return Err("--tools must be a comma-separated list".into()),
    };
    Ok(entries
        .into_iter()
        .flat_map(|entry| {
            entry
                .split(',')
                .map(|part| part.trim().to_string())
                .collect::<Vec<_>>()
        })
        .filter(|entry| !entry.is_empty())
        .collect())
}

/// Saved archetypes in a host-owned workflow database.
pub(crate) struct ArchetypeStore {
    connection: Connection,
}

impl ArchetypeStore {
    pub(crate) fn from_database(database: Arc<dyn WorkflowDatabase>) -> Result<Self, String> {
        Self::initialize(Connection::new(database))
    }

    fn initialize(connection: Connection) -> Result<Self, String> {
        connection
            .execute_batch(
                "CREATE TABLE IF NOT EXISTS incurs_archetypes(\
                 name TEXT PRIMARY KEY, summary TEXT NOT NULL, instructions TEXT NOT NULL, \
                 scope TEXT NOT NULL, created_at INTEGER NOT NULL)",
            )
            .map_err(|error| error.to_string())?;
        Ok(Self { connection })
    }

    #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
    pub(crate) fn open(path: &std::path::Path) -> Result<Self, String> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|error| format!("Cannot create archetype store directory: {error}"))?;
        }
        let connection = Connection::open(path).map_err(|error| error.to_string())?;
        Self::initialize(connection)
    }

    pub(crate) fn list(&self) -> Result<Vec<Archetype>, String> {
        let statement = self
            .connection
            .prepare(
                "SELECT name, summary, instructions, scope FROM incurs_archetypes ORDER BY name",
            )
            .map_err(|error| error.to_string())?;
        statement
            .query_map(vec![], row_archetype)
            .map_err(|error| error.to_string())?
            .map(|row| row.map_err(|error| error.to_string()))
            .collect()
    }

    pub(crate) fn get(&self, name: &str) -> Result<Option<Archetype>, String> {
        self.connection
            .query_row(
                "SELECT name, summary, instructions, scope FROM incurs_archetypes WHERE name=?",
                params![name],
                row_archetype,
            )
            .optional()
            .map_err(|error| error.to_string())
    }

    /// Inserts or replaces a saved archetype, keeping its first creation time.
    pub(crate) fn save(&self, archetype: &Archetype, at: u64) -> Result<(), String> {
        let scope = serde_json::to_string(&archetype.scope).map_err(|error| error.to_string())?;
        self.connection
            .execute(
                "INSERT INTO incurs_archetypes(name, summary, instructions, scope, created_at) \
                 VALUES (?,?,?,?,?) ON CONFLICT(name) DO UPDATE SET \
                 summary=excluded.summary, instructions=excluded.instructions, scope=excluded.scope",
                params![
                    archetype.name,
                    archetype.summary,
                    archetype.instructions,
                    scope,
                    at
                ],
            )
            .map(|_| ())
            .map_err(|error| error.to_string())
    }

    pub(crate) fn delete(&self, name: &str) -> Result<bool, String> {
        self.connection
            .execute("DELETE FROM incurs_archetypes WHERE name=?", params![name])
            .map(|changed| changed > 0)
            .map_err(|error| error.to_string())
    }
}

fn row_archetype(row: &crate::database::Row) -> crate::database::Result<Archetype> {
    let scope: String = row.get(3)?;
    Ok(Archetype {
        name: row.get(0)?,
        summary: row.get(1)?,
        instructions: row.get(2)?,
        scope: serde_json::from_str(&scope).map_err(|error| error.to_string())?,
        origin: "saved",
    })
}

/// What one scope entry names.
enum ScopeTarget {
    Command,
    Workflow,
}

impl State {
    /// Opens the saved-archetype store on first use.
    pub(crate) fn archetype_store(&self) -> Result<&ArchetypeStore, String> {
        self.archetype_store
            .get_or_init(|| {
                if let Some(host) = &self.host {
                    return host
                        .database(WorkflowDatabaseKind::Archetypes)
                        .and_then(ArchetypeStore::from_database);
                }
                #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
                {
                    ArchetypeStore::open(&self.store_path.with_extension("archetypes.sqlite"))
                }
                #[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))]
                {
                    Err("A workflow host is required".into())
                }
            })
            .as_ref()
            .map_err(Clone::clone)
    }

    /// Shipped archetypes and the saved archetypes they do not shadow.
    pub(crate) fn catalog_archetypes(&self) -> Result<Vec<Archetype>, String> {
        let mut archetypes: Vec<Archetype> =
            self.archetypes.values().map(Archetype::shipped).collect();
        for saved in self.archetype_store()?.list()? {
            if !self.archetypes.contains_key(&saved.name) {
                archetypes.push(saved);
            }
        }
        Ok(archetypes)
    }

    /// Finds an archetype by name, shipped archetypes first.
    pub(crate) fn resolve_archetype(&self, name: &str) -> Result<Option<Archetype>, String> {
        if let Some(archetype) = self.archetypes.get(name) {
            return Ok(Some(Archetype::shipped(archetype)));
        }
        self.archetype_store()?.get(name)
    }

    /// Classifies a scope entry against this CLI's commands and workflows.
    async fn scope_target(&self, entry: &str) -> Result<Option<ScopeTarget>, String> {
        if self.catalog.get(entry).is_some() {
            return Ok(Some(ScopeTarget::Command));
        }
        Ok(self.resolve(entry).await?.map(|_| ScopeTarget::Workflow))
    }

    /// Rejects a saved archetype whose scope names anything but a command or workflow.
    pub(crate) async fn check_saved_scope(&self, scope: &[String]) -> Result<(), String> {
        let saved: Vec<String> = self
            .archetype_store()?
            .list()?
            .into_iter()
            .map(|archetype| archetype.name)
            .collect();
        for entry in scope {
            if self.archetypes.contains_key(entry) || saved.contains(entry) {
                return Err(format!(
                    "'{entry}' is an archetype; an archetype scopes commands and workflows only"
                ));
            }
            if self.scope_target(entry).await?.is_none() {
                return Err(format!(
                    "'{entry}' is not a command or workflow of '{}'",
                    self.catalog.name()
                ));
            }
        }
        Ok(())
    }

    /// Scope entries that no longer name a command or workflow.
    pub(crate) async fn missing_scope(&self, archetype: &Archetype) -> Result<Vec<String>, String> {
        let mut missing = Vec::new();
        for entry in &archetype.scope {
            if self.scope_target(entry).await?.is_none() {
                missing.push(entry.clone());
            }
        }
        Ok(missing)
    }

    /// Builds the activation result: guidance plus the scoped contracts, as data.
    pub(crate) async fn activate(
        &self,
        archetype: &Archetype,
        task: Option<&str>,
    ) -> Result<Value, String> {
        let mut tools = Vec::new();
        let mut workflows = Vec::new();
        let mut unavailable = Vec::new();
        for entry in &archetype.scope {
            if let Some(definition) = self.catalog.get(entry) {
                let mut tool = json!({
                    "name": definition.name,
                    "description": definition.description,
                    "inputSchema": definition.input_schema,
                });
                if let Some(schema) = &definition.output_schema {
                    tool["outputSchema"] = schema.clone();
                }
                if let Some(annotations) = &definition.annotations {
                    tool["annotations"] = annotations_json(annotations);
                }
                tools.push(tool);
            } else if let Some(workflow) = self.resolve(entry).await? {
                workflows.push(json!({
                    "name": workflow.name,
                    "description": workflow.description,
                    "origin": workflow.origin,
                    "inputSchema": workflow.input_schema,
                }));
            } else {
                unavailable.push(entry.clone());
            }
        }
        Ok(json!({
            "archetype": archetype.name,
            "origin": archetype.origin,
            "summary": archetype.summary,
            "guidance": archetype.instructions,
            "task": task,
            "tools": tools,
            "workflows": workflows,
            "unavailable": unavailable,
        }))
    }
}

/// Tool annotations in their MCP wire form, omitting unset hints.
fn annotations_json(annotations: &McpAnnotations) -> Value {
    let mut wire = serde_json::Map::new();
    if let Some(title) = &annotations.title {
        wire.insert("title".into(), json!(title));
    }
    for (key, hint) in [
        ("readOnlyHint", annotations.read_only_hint),
        ("destructiveHint", annotations.destructive_hint),
        ("idempotentHint", annotations.idempotent_hint),
        ("openWorldHint", annotations.open_world_hint),
    ] {
        if let Some(hint) = hint {
            wire.insert(key.into(), Value::Bool(hint));
        }
    }
    Value::Object(wire)
}

/// Current Unix time in milliseconds.
pub(crate) fn now_ms() -> u64 {
    web_time::SystemTime::now()
        .duration_since(web_time::UNIX_EPOCH)
        .map_or(0, |elapsed| elapsed.as_millis() as u64)
}

/// Fixed `task` option shared by every activation command.
fn task_option() -> FieldMeta {
    field("task", FieldType::String, false, Some(TASK_DESCRIPTION))
}

/// Annotations for a command that only reads archetypes.
fn read_only() -> McpAnnotations {
    McpAnnotations {
        read_only_hint: Some(true),
        destructive_hint: Some(false),
        idempotent_hint: Some(true),
        open_world_hint: Some(false),
        title: None,
    }
}

/// Builds the activation command of one shipped archetype.
///
/// Its description is the archetype's summary; its options and output schema
/// are the same for every archetype.
pub(crate) fn shipped_command(state: Arc<State>, archetype: &ShippedArchetype) -> CommandDef {
    let mut def = CommandDef::build(
        archetype.name.clone(),
        ShippedArchetypeHandler {
            state,
            name: archetype.name.clone(),
        },
    )
    .description(archetype.summary.clone())
    .mcp(McpCommandOptions {
        enabled: true,
        annotations: Some(read_only()),
        ..McpCommandOptions::default()
    })
    .done();
    def.options_fields = vec![task_option()];
    def.output_schema = Some(activation_output_schema());
    def
}

/// Activates one shipped archetype from its command.
struct ShippedArchetypeHandler {
    state: Arc<State>,
    name: String,
}

#[async_trait]
impl CommandHandler for ShippedArchetypeHandler {
    async fn run(&self, ctx: CommandContext) -> CommandResult {
        let Some(archetype) = self.state.archetypes.get(&self.name) else {
            return archetype_not_found(&self.name);
        };
        let task = string_arg(&ctx.options, "task");
        match self
            .state
            .activate(&Archetype::shipped(archetype), task)
            .await
        {
            Ok(data) => ok(data),
            Err(message) => error("WORKFLOW_HOST_ERROR", message),
        }
    }
}

fn archetype_not_found(name: &str) -> CommandResult {
    error(
        "ARCHETYPE_NOT_FOUND",
        format!("No archetype named '{name}'"),
    )
}

/// One subcommand of the `archetypes` group.
#[derive(Clone, Copy)]
enum ArchetypeAction {
    List,
    Show,
    Activate,
    Save,
    Delete,
}

struct ArchetypeGroupHandler {
    state: Arc<State>,
    action: ArchetypeAction,
}

#[async_trait]
impl CommandHandler for ArchetypeGroupHandler {
    async fn run(&self, ctx: CommandContext) -> CommandResult {
        match self.dispatch(&ctx).await {
            Ok(result) => result,
            Err(message) => error("WORKFLOW_HOST_ERROR", message),
        }
    }
}

impl ArchetypeGroupHandler {
    async fn dispatch(&self, ctx: &CommandContext) -> Result<CommandResult, String> {
        let state = &self.state;
        let name = string_arg(&ctx.args, "name").unwrap_or_default();
        Ok(match self.action {
            ArchetypeAction::List => ok(Value::Array(
                state
                    .catalog_archetypes()?
                    .iter()
                    .map(Archetype::summary_json)
                    .collect(),
            )),
            ArchetypeAction::Show => match state.resolve_archetype(name)? {
                Some(archetype) => ok(archetype.detail_json()),
                None => archetype_not_found(name),
            },
            ArchetypeAction::Activate => match state.resolve_archetype(name)? {
                Some(archetype) => ok(state
                    .activate(&archetype, string_arg(&ctx.options, "task"))
                    .await?),
                None => archetype_not_found(name),
            },
            ArchetypeAction::Save => {
                if state.archetypes.contains_key(name) {
                    return Ok(error(
                        "ARCHETYPE_SHIPPED",
                        format!("'{name}' is a shipped archetype and cannot be replaced"),
                    ));
                }
                if state.catalog.get(name).is_some() || state.shipped.contains_key(name) {
                    return Ok(error(
                        "INVALID_ARCHETYPE",
                        format!(
                            "'{name}' is already a command of '{}'",
                            state.catalog.name()
                        ),
                    ));
                }
                let scope = match parse_scope(ctx.options.get("tools")) {
                    Ok(scope) => scope,
                    Err(message) => return Ok(error("INVALID_ARCHETYPE", message)),
                };
                let archetype = Archetype {
                    name: name.to_string(),
                    summary: string_arg(&ctx.options, "summary")
                        .unwrap_or_default()
                        .to_string(),
                    instructions: string_arg(&ctx.options, "instructions")
                        .unwrap_or_default()
                        .to_string(),
                    scope,
                    origin: "saved",
                };
                if let Err(message) = check_definition(
                    &archetype.name,
                    &archetype.summary,
                    &archetype.instructions,
                    &archetype.scope,
                ) {
                    return Ok(error("INVALID_ARCHETYPE", message));
                }
                if let Err(message) = state.check_saved_scope(&archetype.scope).await {
                    return Ok(error("INVALID_ARCHETYPE", message));
                }
                state.archetype_store()?.save(&archetype, now_ms())?;
                ok(archetype.detail_json())
            }
            ArchetypeAction::Delete => {
                if state.archetypes.contains_key(name) {
                    return Ok(error(
                        "ARCHETYPE_SHIPPED",
                        format!("'{name}' is a shipped archetype and cannot be deleted"),
                    ));
                }
                if state.archetype_store()?.delete(name)? {
                    ok(json!({ "deleted": name }))
                } else {
                    archetype_not_found(name)
                }
            }
        })
    }
}

/// Builds the `archetypes` command group.
pub(crate) fn group(state: Arc<State>) -> Cli {
    let effectful = McpAnnotations {
        read_only_hint: Some(false),
        destructive_hint: Some(false),
        idempotent_hint: Some(true),
        open_world_hint: Some(false),
        title: None,
    };
    let destructive = McpAnnotations {
        destructive_hint: Some(true),
        ..effectful.clone()
    };
    let name_arg = || field("name", FieldType::String, true, Some("Archetype name"));
    let command = |name: &str,
                   action: ArchetypeAction,
                   description: &str,
                   annotations: McpAnnotations,
                   options: Vec<FieldMeta>| {
        let destructive = annotations.destructive_hint == Some(true);
        let mut def = CommandDef::build(
            name,
            ArchetypeGroupHandler {
                state: state.clone(),
                action,
            },
        )
        .description(description)
        .mcp(McpCommandOptions {
            enabled: true,
            annotations: Some(annotations),
            ..McpCommandOptions::default()
        })
        .destructive(destructive)
        .done();
        def.options_fields = options;
        def
    };
    let mut list = command(
        "list",
        ArchetypeAction::List,
        "List shipped and saved archetypes",
        read_only(),
        Vec::new(),
    );
    list.args_fields = Vec::new();
    let mut show = command(
        "show",
        ArchetypeAction::Show,
        "Show an archetype's summary, instructions, and scope",
        read_only(),
        Vec::new(),
    );
    show.args_fields = vec![name_arg()];
    let mut activate = command(
        "activate",
        ArchetypeAction::Activate,
        "Focus on a task: return an archetype's guidance and its scoped commands and workflows",
        read_only(),
        vec![task_option()],
    );
    activate.args_fields = vec![name_arg()];
    activate.output_schema = Some(activation_output_schema());
    let mut save = command(
        "save",
        ArchetypeAction::Save,
        "Save an archetype: a summary, instructions, and the commands and workflows it uses",
        effectful,
        vec![
            field(
                "summary",
                FieldType::String,
                true,
                Some("One line saying what the archetype is for"),
            ),
            field(
                "instructions",
                FieldType::String,
                true,
                Some("Guidance for an agent working on this kind of task"),
            ),
            field(
                "tools",
                FieldType::Array(Box::new(FieldType::String)),
                true,
                Some("Commands and workflows in scope, comma-separated"),
            ),
        ],
    );
    save.args_fields = vec![name_arg()];
    let mut delete = command(
        "delete",
        ArchetypeAction::Delete,
        "Delete a saved archetype",
        destructive,
        Vec::new(),
    );
    delete.args_fields = vec![name_arg()];

    let mut group = Cli::create(ARCHETYPES_GROUP_NAME).description(
        "Activate a task focus: guidance plus the commands and workflows that task uses",
    );
    for def in [list, show, activate, save, delete] {
        group = group.command(def.name.clone(), def);
    }
    group
}