punch-skills 1.2.0

Skill/move system for the Punch Agent Combat System
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
//! # Skill Marketplace
//!
//! A marketplace for sharing and discovering agent skills (special moves).
//! Fighters can browse the marketplace to find new tools, install them into
//! their loadout, and rate them after use.

use std::path::PathBuf;

use chrono::{DateTime, Utc};
use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use punch_types::error::{PunchError, PunchResult};
use punch_types::{ToolCategory, ToolDefinition};

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/// Where a skill comes from — its origin story.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SkillSource {
    /// Ships with Punch out of the box.
    Builtin,
    /// Loaded from a local path on disk.
    Local(PathBuf),
    /// Fetched from a remote URL.
    Remote(String),
    /// Provided by a plugin.
    Plugin(Uuid),
    /// Installed from the skills marketplace index.
    Marketplace {
        /// Pinned version.
        version: String,
        /// SHA-256 checksum of the installed tarball.
        checksum: String,
    },
}

/// A skill listing in the marketplace — like a fighter's move on the roster card.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillListing {
    /// Unique identifier.
    pub id: Uuid,
    /// Human-readable name of the skill.
    pub name: String,
    /// Description of what this skill does.
    pub description: String,
    /// Author or team that created the skill.
    pub author: String,
    /// Semantic version.
    pub version: String,
    /// Category (e.g. "filesystem", "web", "agent", "code").
    pub category: String,
    /// Searchable tags.
    pub tags: Vec<String>,
    /// The actual tool definitions this skill provides.
    pub tool_definitions: Vec<ToolDefinition>,
    /// Number of times this skill has been installed.
    pub install_count: u64,
    /// Average user rating (0.0–5.0).
    pub rating: f64,
    /// When the skill was published.
    pub published_at: DateTime<Utc>,
    /// Where the skill comes from.
    pub source: SkillSource,
}

/// A skill that has been installed into the fighter's loadout.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InstalledSkill {
    /// The ID of the skill listing this was installed from.
    pub skill_id: Uuid,
    /// When it was installed.
    pub installed_at: DateTime<Utc>,
    /// The tools this skill provides.
    pub tools: Vec<ToolDefinition>,
    /// Whether the skill is currently enabled.
    pub enabled: bool,
}

// ---------------------------------------------------------------------------
// Marketplace
// ---------------------------------------------------------------------------

/// The skill marketplace — a bazaar of special moves that fighters can equip.
pub struct SkillMarketplace {
    skills: DashMap<Uuid, SkillListing>,
    installed: DashMap<Uuid, InstalledSkill>,
}

impl SkillMarketplace {
    /// Create a new empty marketplace.
    pub fn new() -> Self {
        Self {
            skills: DashMap::new(),
            installed: DashMap::new(),
        }
    }

    /// Publish a skill listing to the marketplace. Returns the skill's ID.
    pub fn publish(&self, listing: SkillListing) -> Uuid {
        let id = listing.id;
        self.skills.insert(id, listing);
        id
    }

    /// Search for skills whose name, description, or tags contain the query.
    pub fn search(&self, query: &str) -> Vec<SkillListing> {
        let q = query.to_lowercase();
        self.skills
            .iter()
            .filter(|entry| {
                let s = entry.value();
                s.name.to_lowercase().contains(&q)
                    || s.description.to_lowercase().contains(&q)
                    || s.tags.iter().any(|t| t.to_lowercase().contains(&q))
            })
            .map(|entry| entry.value().clone())
            .collect()
    }

    /// Search for skills by category.
    pub fn search_by_category(&self, category: &str) -> Vec<SkillListing> {
        let cat = category.to_lowercase();
        self.skills
            .iter()
            .filter(|entry| entry.value().category.to_lowercase() == cat)
            .map(|entry| entry.value().clone())
            .collect()
    }

    /// Get a skill listing by ID.
    pub fn get(&self, id: &Uuid) -> Option<SkillListing> {
        self.skills.get(id).map(|entry| entry.value().clone())
    }

    /// Install a skill from the marketplace.
    pub fn install(&self, id: &Uuid) -> PunchResult<InstalledSkill> {
        let listing = self.skills.get(id).ok_or_else(|| {
            PunchError::ToolNotFound(format!("skill {id} not found in marketplace"))
        })?;

        let installed = InstalledSkill {
            skill_id: *id,
            installed_at: Utc::now(),
            tools: listing.tool_definitions.clone(),
            enabled: true,
        };

        // Bump install count
        drop(listing);
        if let Some(mut entry) = self.skills.get_mut(id) {
            entry.value_mut().install_count += 1;
        }

        self.installed.insert(*id, installed.clone());
        Ok(installed)
    }

    /// Uninstall a skill.
    pub fn uninstall(&self, id: &Uuid) -> PunchResult<()> {
        self.installed
            .remove(id)
            .ok_or_else(|| PunchError::ToolNotFound(format!("skill {id} is not installed")))?;
        Ok(())
    }

    /// List all installed skills.
    pub fn installed_skills(&self) -> Vec<InstalledSkill> {
        self.installed
            .iter()
            .map(|entry| entry.value().clone())
            .collect()
    }

    /// Check if a skill is currently installed.
    pub fn is_installed(&self, id: &Uuid) -> bool {
        self.installed.contains_key(id)
    }

    /// Update the rating for a skill.
    pub fn update_rating(&self, id: &Uuid, rating: f64) {
        if let Some(mut entry) = self.skills.get_mut(id) {
            entry.value_mut().rating = rating;
        }
    }

    /// Find a skill by exact name (case-insensitive).
    pub fn find_by_name(&self, name: &str) -> Option<SkillListing> {
        self.skills
            .iter()
            .find(|entry| entry.value().name.eq_ignore_ascii_case(name))
            .map(|entry| entry.value().clone())
    }

    /// List all available skill listings.
    pub fn list_all(&self) -> Vec<SkillListing> {
        self.skills
            .iter()
            .map(|entry| entry.value().clone())
            .collect()
    }
}

impl Default for SkillMarketplace {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Built-in skills
// ---------------------------------------------------------------------------

/// Helper to build a tool definition with a proper input schema.
fn tool(
    name: &str,
    description: &str,
    category: ToolCategory,
    schema: serde_json::Value,
) -> ToolDefinition {
    ToolDefinition {
        name: name.to_string(),
        description: description.to_string(),
        input_schema: schema,
        category,
    }
}

/// Returns listings for all built-in skills that ship with Punch.
pub fn builtin_skills() -> Vec<SkillListing> {
    let now = Utc::now();

    vec![
        SkillListing {
            id: Uuid::new_v4(),
            name: "Filesystem Tools".to_string(),
            description: "Read, write, and list files on the local filesystem.".to_string(),
            author: "Punch Team".to_string(),
            version: "0.1.0".to_string(),
            category: "filesystem".to_string(),
            tags: vec!["io".to_string(), "files".to_string(), "builtin".to_string()],
            tool_definitions: vec![
                tool(
                    "file_read",
                    "Read the contents of a file at the given path. Returns the file content as a string.",
                    ToolCategory::FileSystem,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "path": {
                                "type": "string",
                                "description": "Path to the file to read (absolute or relative to working directory)"
                            }
                        },
                        "required": ["path"]
                    }),
                ),
                tool(
                    "file_write",
                    "Write string content to a file at the given path. Creates parent directories if needed.",
                    ToolCategory::FileSystem,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "path": {
                                "type": "string",
                                "description": "Path to the file to write (absolute or relative to working directory)"
                            },
                            "content": {
                                "type": "string",
                                "description": "The content to write to the file"
                            }
                        },
                        "required": ["path", "content"]
                    }),
                ),
                tool(
                    "file_list",
                    "List files and directories at the given path. Returns name and type for each entry.",
                    ToolCategory::FileSystem,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "path": {
                                "type": "string",
                                "description": "Directory path to list (defaults to current working directory)"
                            }
                        }
                    }),
                ),
            ],
            install_count: 0,
            rating: 0.0,
            published_at: now,
            source: SkillSource::Builtin,
        },
        SkillListing {
            id: Uuid::new_v4(),
            name: "Shell Tools".to_string(),
            description: "Execute shell commands.".to_string(),
            author: "Punch Team".to_string(),
            version: "0.1.0".to_string(),
            category: "shell".to_string(),
            tags: vec![
                "exec".to_string(),
                "command".to_string(),
                "builtin".to_string(),
            ],
            tool_definitions: vec![tool(
                "shell_exec",
                "Execute a shell command and return stdout, stderr, and exit code. Commands run via sh -c.",
                ToolCategory::Shell,
                serde_json::json!({
                    "type": "object",
                    "properties": {
                        "command": {
                            "type": "string",
                            "description": "The shell command to execute"
                        }
                    },
                    "required": ["command"]
                }),
            )],
            install_count: 0,
            rating: 0.0,
            published_at: now,
            source: SkillSource::Builtin,
        },
        SkillListing {
            id: Uuid::new_v4(),
            name: "Web Tools".to_string(),
            description: "Search the web and fetch URLs.".to_string(),
            author: "Punch Team".to_string(),
            version: "0.1.0".to_string(),
            category: "web".to_string(),
            tags: vec![
                "http".to_string(),
                "search".to_string(),
                "builtin".to_string(),
            ],
            tool_definitions: vec![
                tool(
                    "web_search",
                    "Search the web using DuckDuckGo and return a list of results with titles, URLs, and snippets.",
                    ToolCategory::Web,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "query": {
                                "type": "string",
                                "description": "The search query"
                            },
                            "max_results": {
                                "type": "integer",
                                "description": "Maximum number of results to return (default: 10)"
                            }
                        },
                        "required": ["query"]
                    }),
                ),
                tool(
                    "web_fetch",
                    "Fetch the content of a web page at the given URL. Returns the page text content.",
                    ToolCategory::Web,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "url": {
                                "type": "string",
                                "description": "The URL to fetch"
                            },
                            "max_length": {
                                "type": "integer",
                                "description": "Maximum content length in characters (default: 50000)"
                            }
                        },
                        "required": ["url"]
                    }),
                ),
            ],
            install_count: 0,
            rating: 0.0,
            published_at: now,
            source: SkillSource::Builtin,
        },
        SkillListing {
            id: Uuid::new_v4(),
            name: "Memory Tools".to_string(),
            description: "Store and recall information from memory.".to_string(),
            author: "Punch Team".to_string(),
            version: "0.1.0".to_string(),
            category: "memory".to_string(),
            tags: vec![
                "recall".to_string(),
                "store".to_string(),
                "builtin".to_string(),
            ],
            tool_definitions: vec![
                tool(
                    "memory_store",
                    "Store a key-value pair in the agent's persistent memory for later recall.",
                    ToolCategory::Memory,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "key": {
                                "type": "string",
                                "description": "The key to store the value under"
                            },
                            "value": {
                                "type": "string",
                                "description": "The value to store"
                            },
                            "tags": {
                                "type": "array",
                                "items": {"type": "string"},
                                "description": "Optional tags for categorizing the memory"
                            }
                        },
                        "required": ["key", "value"]
                    }),
                ),
                tool(
                    "memory_recall",
                    "Recall stored values from the agent's persistent memory by key or semantic search.",
                    ToolCategory::Memory,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "query": {
                                "type": "string",
                                "description": "Search query or exact key to recall"
                            },
                            "max_results": {
                                "type": "integer",
                                "description": "Maximum number of results to return (default: 5)"
                            }
                        },
                        "required": ["query"]
                    }),
                ),
            ],
            install_count: 0,
            rating: 0.0,
            published_at: now,
            source: SkillSource::Builtin,
        },
        SkillListing {
            id: Uuid::new_v4(),
            name: "Knowledge Graph".to_string(),
            description: "Build and query a knowledge graph of entities and relations.".to_string(),
            author: "Punch Team".to_string(),
            version: "0.1.0".to_string(),
            category: "knowledge".to_string(),
            tags: vec![
                "graph".to_string(),
                "entities".to_string(),
                "builtin".to_string(),
            ],
            tool_definitions: vec![
                tool(
                    "knowledge_add_entity",
                    "Add an entity with a name, type, and optional description to the knowledge graph.",
                    ToolCategory::Knowledge,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "name": {
                                "type": "string",
                                "description": "Name of the entity"
                            },
                            "entity_type": {
                                "type": "string",
                                "description": "Type/category of the entity (e.g. 'person', 'concept', 'tool')"
                            },
                            "description": {
                                "type": "string",
                                "description": "Optional description of the entity"
                            }
                        },
                        "required": ["name", "entity_type"]
                    }),
                ),
                tool(
                    "knowledge_add_relation",
                    "Add a directed relation between two entities in the knowledge graph.",
                    ToolCategory::Knowledge,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "from": {
                                "type": "string",
                                "description": "Name of the source entity"
                            },
                            "relation": {
                                "type": "string",
                                "description": "The relation type (e.g. 'depends_on', 'uses', 'created_by')"
                            },
                            "to": {
                                "type": "string",
                                "description": "Name of the target entity"
                            }
                        },
                        "required": ["from", "relation", "to"]
                    }),
                ),
                tool(
                    "knowledge_query",
                    "Query the knowledge graph for entities and their relations.",
                    ToolCategory::Knowledge,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "query": {
                                "type": "string",
                                "description": "Search query for entities or relations"
                            },
                            "entity_type": {
                                "type": "string",
                                "description": "Optional filter by entity type"
                            },
                            "max_results": {
                                "type": "integer",
                                "description": "Maximum number of results (default: 10)"
                            }
                        },
                        "required": ["query"]
                    }),
                ),
            ],
            install_count: 0,
            rating: 0.0,
            published_at: now,
            source: SkillSource::Builtin,
        },
        SkillListing {
            id: Uuid::new_v4(),
            name: "Agent Coordination".to_string(),
            description: "Spawn, message, and list other agents in the ring.".to_string(),
            author: "Punch Team".to_string(),
            version: "0.1.0".to_string(),
            category: "agent".to_string(),
            tags: vec![
                "multi-agent".to_string(),
                "coordination".to_string(),
                "builtin".to_string(),
            ],
            tool_definitions: vec![
                tool(
                    "agent_spawn",
                    "Spawn a new agent with the given name and system prompt. Returns the new agent's ID.",
                    ToolCategory::Agent,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "name": {
                                "type": "string",
                                "description": "Name for the new agent"
                            },
                            "system_prompt": {
                                "type": "string",
                                "description": "System prompt defining the agent's role and behavior"
                            }
                        },
                        "required": ["name", "system_prompt"]
                    }),
                ),
                tool(
                    "agent_message",
                    "Send a message to another agent and receive its response.",
                    ToolCategory::Agent,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "fighter_id": {
                                "type": "string",
                                "description": "ID of the target agent (UUID)"
                            },
                            "name": {
                                "type": "string",
                                "description": "Name of the target agent (alternative to fighter_id)"
                            },
                            "message": {
                                "type": "string",
                                "description": "The message to send"
                            }
                        },
                        "required": ["message"]
                    }),
                ),
                tool(
                    "agent_list",
                    "List all active agents in the ring with their IDs, names, and statuses.",
                    ToolCategory::Agent,
                    serde_json::json!({
                        "type": "object",
                        "properties": {}
                    }),
                ),
            ],
            install_count: 0,
            rating: 0.0,
            published_at: now,
            source: SkillSource::Builtin,
        },
        SkillListing {
            id: Uuid::new_v4(),
            name: "Browser Tools".to_string(),
            description: "Navigate and interact with web pages in a browser.".to_string(),
            author: "Punch Team".to_string(),
            version: "0.1.0".to_string(),
            category: "browser".to_string(),
            tags: vec![
                "web".to_string(),
                "scrape".to_string(),
                "builtin".to_string(),
            ],
            tool_definitions: vec![tool(
                "browser_navigate",
                "Navigate to a URL in the browser. Opens the page and waits for it to load.",
                ToolCategory::Browser,
                serde_json::json!({
                    "type": "object",
                    "properties": {
                        "url": {
                            "type": "string",
                            "description": "The URL to navigate to"
                        }
                    },
                    "required": ["url"]
                }),
            )],
            install_count: 0,
            rating: 0.0,
            published_at: now,
            source: SkillSource::Builtin,
        },
        SkillListing {
            id: Uuid::new_v4(),
            name: "Desktop Vision".to_string(),
            description: "Capture screenshots and extract text from app windows via OCR."
                .to_string(),
            author: "Punch Team".to_string(),
            version: "0.1.0".to_string(),
            category: "automation".to_string(),
            tags: vec![
                "screenshot".to_string(),
                "ocr".to_string(),
                "vision".to_string(),
                "builtin".to_string(),
            ],
            tool_definitions: vec![
                tool(
                    "sys_screenshot",
                    "Capture a screenshot of the full screen or a specific window. Returns a base64-encoded PNG image that the vision model can interpret.",
                    ToolCategory::SystemAutomation,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "window": {
                                "type": "string",
                                "description": "Name of the window to capture (omit for full screen)"
                            }
                        }
                    }),
                ),
                tool(
                    "app_ocr",
                    "Extract text from an application window using local OCR (macOS Vision / tesseract). Returns plain text without requiring a vision model.",
                    ToolCategory::AppIntegration,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "app": {
                                "type": "string",
                                "description": "Name of the application to extract text from"
                            }
                        },
                        "required": ["app"]
                    }),
                ),
            ],
            install_count: 0,
            rating: 0.0,
            published_at: now,
            source: SkillSource::Builtin,
        },
        SkillListing {
            id: Uuid::new_v4(),
            name: "UI Automation".to_string(),
            description:
                "Find, click, and type in application UI elements via the accessibility API."
                    .to_string(),
            author: "Punch Team".to_string(),
            version: "0.1.0".to_string(),
            category: "automation".to_string(),
            tags: vec![
                "accessibility".to_string(),
                "click".to_string(),
                "type".to_string(),
                "ui".to_string(),
                "builtin".to_string(),
            ],
            tool_definitions: vec![
                tool(
                    "ui_find_elements",
                    "Query the accessibility tree of an application to find buttons, text fields, rows, and other UI elements.",
                    ToolCategory::UiAutomation,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "app": { "type": "string", "description": "Application name" },
                            "role": { "type": "string", "description": "Accessibility role filter (e.g. button, text field, row)" }
                        },
                        "required": ["app"]
                    }),
                ),
                tool(
                    "ui_click",
                    "Click a UI element identified by its element ID (e.g. 'Messages:3').",
                    ToolCategory::UiAutomation,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "element_id": { "type": "string", "description": "Element ID in 'AppName:index' format" }
                        },
                        "required": ["element_id"]
                    }),
                ),
                tool(
                    "ui_type_text",
                    "Type text into a focused UI element or a specific element by ID.",
                    ToolCategory::UiAutomation,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "text": { "type": "string", "description": "Text to type" },
                            "element_id": { "type": "string", "description": "Optional element ID to focus first" }
                        },
                        "required": ["text"]
                    }),
                ),
            ],
            install_count: 0,
            rating: 0.0,
            published_at: now,
            source: SkillSource::Builtin,
        },
        SkillListing {
            id: Uuid::new_v4(),
            name: "Window Management".to_string(),
            description: "List open windows and read UI element attributes for desktop inspection."
                .to_string(),
            author: "Punch Team".to_string(),
            version: "0.1.0".to_string(),
            category: "automation".to_string(),
            tags: vec![
                "windows".to_string(),
                "inspect".to_string(),
                "desktop".to_string(),
                "builtin".to_string(),
            ],
            tool_definitions: vec![
                tool(
                    "ui_list_windows",
                    "List all open windows with their titles, application names, and IDs.",
                    ToolCategory::UiAutomation,
                    serde_json::json!({
                        "type": "object",
                        "properties": {}
                    }),
                ),
                tool(
                    "ui_read_attribute",
                    "Read a specific accessibility attribute from a UI element.",
                    ToolCategory::UiAutomation,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "element_id": { "type": "string", "description": "Element ID in 'AppName:index' format" },
                            "attribute": { "type": "string", "description": "Attribute to read (e.g. value, title, description)" }
                        },
                        "required": ["element_id", "attribute"]
                    }),
                ),
                tool(
                    "ui_screenshot",
                    "Capture a screenshot of a specific UI region or element for targeted visual inspection.",
                    ToolCategory::UiAutomation,
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "app": { "type": "string", "description": "Application name" },
                            "bounds": { "type": "string", "description": "Region as 'x,y,width,height'" }
                        },
                        "required": ["app"]
                    }),
                ),
            ],
            install_count: 0,
            rating: 0.0,
            published_at: now,
            source: SkillSource::Builtin,
        },
        SkillListing {
            id: Uuid::new_v4(),
            name: "Patch Tools".to_string(),
            description: "Apply unified diffs and patches to files.".to_string(),
            author: "Punch Team".to_string(),
            version: "0.1.0".to_string(),
            category: "code".to_string(),
            tags: vec![
                "diff".to_string(),
                "patch".to_string(),
                "builtin".to_string(),
            ],
            tool_definitions: vec![tool(
                "patch_apply",
                "Apply a unified diff patch to a file. Supports fuzzy matching for slight offset mismatches.",
                ToolCategory::FileSystem,
                serde_json::json!({
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "Path to the file to patch"
                        },
                        "diff": {
                            "type": "string",
                            "description": "The unified diff text to apply"
                        }
                    },
                    "required": ["path", "diff"]
                }),
            )],
            install_count: 0,
            rating: 0.0,
            published_at: now,
            source: SkillSource::Builtin,
        },
    ]
}

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

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

    fn sample_listing(name: &str, category: &str) -> SkillListing {
        SkillListing {
            id: Uuid::new_v4(),
            name: name.to_string(),
            description: format!("A skill for {name}"),
            author: "tester".to_string(),
            version: "1.0.0".to_string(),
            category: category.to_string(),
            tags: vec!["test".to_string(), category.to_string()],
            tool_definitions: vec![tool(
                "test_tool",
                "a test tool",
                ToolCategory::Shell,
                serde_json::json!({"type": "object", "properties": {}}),
            )],
            install_count: 0,
            rating: 0.0,
            published_at: Utc::now(),
            source: SkillSource::Builtin,
        }
    }

    #[test]
    fn test_publish_skill() {
        let mp = SkillMarketplace::new();
        let listing = sample_listing("puncher", "agent");
        let id = listing.id;
        let returned = mp.publish(listing);
        assert_eq!(returned, id);
        assert!(mp.get(&id).is_some());
    }

    #[test]
    fn test_search_by_name() {
        let mp = SkillMarketplace::new();
        mp.publish(sample_listing("Filesystem Tools", "filesystem"));
        mp.publish(sample_listing("Web Tools", "web"));

        let results = mp.search("filesystem");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "Filesystem Tools");
    }

    #[test]
    fn test_search_by_category() {
        let mp = SkillMarketplace::new();
        mp.publish(sample_listing("Tool A", "web"));
        mp.publish(sample_listing("Tool B", "web"));
        mp.publish(sample_listing("Tool C", "agent"));

        let results = mp.search_by_category("web");
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_search_by_tag() {
        let mp = SkillMarketplace::new();
        let mut listing = sample_listing("Tagged", "misc");
        listing.tags.push("special_move".to_string());
        mp.publish(listing);

        let results = mp.search("special_move");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "Tagged");
    }

    #[test]
    fn test_install_skill() {
        let mp = SkillMarketplace::new();
        let listing = sample_listing("installable", "agent");
        let id = listing.id;
        mp.publish(listing);

        let installed = mp.install(&id).expect("install should succeed");
        assert_eq!(installed.skill_id, id);
        assert!(installed.enabled);
        assert!(!installed.tools.is_empty());

        // Install count should be bumped
        let updated = mp.get(&id).expect("should exist");
        assert_eq!(updated.install_count, 1);
    }

    #[test]
    fn test_uninstall_skill() {
        let mp = SkillMarketplace::new();
        let listing = sample_listing("removable", "agent");
        let id = listing.id;
        mp.publish(listing);
        mp.install(&id).expect("install");

        assert!(mp.is_installed(&id));
        mp.uninstall(&id).expect("uninstall");
        assert!(!mp.is_installed(&id));
    }

    #[test]
    fn test_is_installed_check() {
        let mp = SkillMarketplace::new();
        let listing = sample_listing("checker", "agent");
        let id = listing.id;
        mp.publish(listing);

        assert!(!mp.is_installed(&id));
        mp.install(&id).expect("install");
        assert!(mp.is_installed(&id));
    }

    #[test]
    fn test_update_rating() {
        let mp = SkillMarketplace::new();
        let listing = sample_listing("rated", "agent");
        let id = listing.id;
        mp.publish(listing);

        mp.update_rating(&id, 4.5);
        let updated = mp.get(&id).expect("should exist");
        assert!((updated.rating - 4.5).abs() < f64::EPSILON);
    }

    #[test]
    fn test_builtin_skills_populated() {
        let skills = builtin_skills();
        assert!(
            skills.len() >= 11,
            "expected at least 11 builtin skills, got {}",
            skills.len()
        );

        let names: Vec<&str> = skills.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"Filesystem Tools"));
        assert!(names.contains(&"Shell Tools"));
        assert!(names.contains(&"Web Tools"));
        assert!(names.contains(&"Memory Tools"));
        assert!(names.contains(&"Knowledge Graph"));
        assert!(names.contains(&"Agent Coordination"));
        assert!(names.contains(&"Browser Tools"));
        assert!(names.contains(&"Patch Tools"));
        assert!(names.contains(&"Desktop Vision"));
        assert!(names.contains(&"UI Automation"));
        assert!(names.contains(&"Window Management"));
    }

    #[test]
    fn test_marketplace_default() {
        let mp = SkillMarketplace::default();
        assert!(mp.installed_skills().is_empty());
    }

    #[test]
    fn test_install_nonexistent() {
        let mp = SkillMarketplace::new();
        let id = Uuid::new_v4();
        let result = mp.install(&id);
        assert!(result.is_err());
    }

    #[test]
    fn test_uninstall_nonexistent() {
        let mp = SkillMarketplace::new();
        let id = Uuid::new_v4();
        let result = mp.uninstall(&id);
        assert!(result.is_err());
    }

    #[test]
    fn test_search_case_insensitive() {
        let mp = SkillMarketplace::new();
        mp.publish(sample_listing("MyTool", "code"));

        let results = mp.search("mytool");
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_search_no_match() {
        let mp = SkillMarketplace::new();
        mp.publish(sample_listing("alpha", "code"));

        let results = mp.search("zzzzz");
        assert!(results.is_empty());
    }

    #[test]
    fn test_search_by_description() {
        let mp = SkillMarketplace::new();
        let listing = sample_listing("tool", "web");
        mp.publish(listing);

        let results = mp.search("skill for tool");
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_installed_skills_list() {
        let mp = SkillMarketplace::new();
        let l1 = sample_listing("a", "code");
        let l2 = sample_listing("b", "web");
        let id1 = l1.id;
        let id2 = l2.id;
        mp.publish(l1);
        mp.publish(l2);

        mp.install(&id1).unwrap();
        mp.install(&id2).unwrap();

        let installed = mp.installed_skills();
        assert_eq!(installed.len(), 2);
    }

    #[test]
    fn test_install_count_increments() {
        let mp = SkillMarketplace::new();
        let listing = sample_listing("counter", "misc");
        let id = listing.id;
        mp.publish(listing);

        mp.install(&id).unwrap();
        let updated = mp.get(&id).unwrap();
        assert_eq!(updated.install_count, 1);
    }

    #[test]
    fn test_update_rating_nonexistent() {
        let mp = SkillMarketplace::new();
        // Should not panic
        mp.update_rating(&Uuid::new_v4(), 3.0);
    }

    #[test]
    fn test_skill_source_serde() {
        let sources = vec![
            SkillSource::Builtin,
            SkillSource::Local(std::path::PathBuf::from("/tmp/skill")),
            SkillSource::Remote("https://example.com/skill.wasm".to_string()),
            SkillSource::Plugin(Uuid::new_v4()),
            SkillSource::Marketplace {
                version: "1.0.0".to_string(),
                checksum: "abc123def456".to_string(),
            },
        ];
        for source in &sources {
            let json = serde_json::to_string(source).unwrap();
            let restored: SkillSource = serde_json::from_str(&json).unwrap();
            // Just verify roundtrip doesn't panic
            let _ = format!("{restored:?}");
        }
    }

    #[test]
    fn test_builtin_skills_have_tools() {
        let skills = builtin_skills();
        for skill in &skills {
            assert!(
                !skill.tool_definitions.is_empty(),
                "builtin skill '{}' should have at least one tool",
                skill.name
            );
        }
    }

    #[test]
    fn test_builtin_skills_all_builtin_source() {
        let skills = builtin_skills();
        for skill in &skills {
            assert!(
                matches!(skill.source, SkillSource::Builtin),
                "builtin skill '{}' should have Builtin source",
                skill.name
            );
        }
    }

    #[test]
    fn test_get_by_id() {
        let mp = SkillMarketplace::new();
        let listing = sample_listing("findme", "code");
        let id = listing.id;
        mp.publish(listing);

        let found = mp.get(&id);
        assert!(found.is_some());
        assert_eq!(found.as_ref().map(|s| s.name.as_str()), Some("findme"));

        let missing = mp.get(&Uuid::new_v4());
        assert!(missing.is_none());
    }

    #[test]
    fn test_find_by_name() {
        let mp = SkillMarketplace::new();
        mp.publish(sample_listing("Alpha Tool", "code"));
        mp.publish(sample_listing("Beta Tool", "web"));

        let found = mp.find_by_name("alpha tool");
        assert!(found.is_some());
        assert_eq!(found.unwrap().name, "Alpha Tool");

        let found_exact = mp.find_by_name("Alpha Tool");
        assert!(found_exact.is_some());

        let not_found = mp.find_by_name("nonexistent");
        assert!(not_found.is_none());
    }

    #[test]
    fn test_list_all() {
        let mp = SkillMarketplace::new();
        mp.publish(sample_listing("tool-a", "code"));
        mp.publish(sample_listing("tool-b", "web"));
        mp.publish(sample_listing("tool-c", "agent"));

        let all = mp.list_all();
        assert_eq!(all.len(), 3);
    }

    #[test]
    fn test_list_all_empty() {
        let mp = SkillMarketplace::new();
        let all = mp.list_all();
        assert!(all.is_empty());
    }
}