diff --git a/tool/generator/bin/skills.dart b/tool/generator/bin/skills.dart index 6475eb21..3c11c0f5 100644 --- a/tool/generator/bin/skills.dart +++ b/tool/generator/bin/skills.dart @@ -2,6 +2,7 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. +import 'dart:async'; import 'dart:io'; import 'package:args/command_runner.dart'; @@ -14,11 +15,14 @@ import 'package:skills/src/commands/validate_skill_command.dart'; const String version = '0.1.0'; -void main(List arguments) async { +Future main(List arguments) async { final httpClient = http.Client(); final runner = - CommandRunner('skills', 'A sample command-line application.') + CommandRunner( + 'skills', + 'CLI tool for generating, updating, and validating Agent Skills.', + ) ..addCommand(GenerateSkillCommand(httpClient: httpClient)) ..addCommand(UpdateSkillCommand(httpClient: httpClient)) ..addCommand(ValidateSkillCommand(httpClient: httpClient)) @@ -36,6 +40,7 @@ void main(List arguments) async { help: 'Show additional command output.', ); + StreamSubscription? logSubscription; try { final results = runner.parse(arguments); if (results.flag('version')) { @@ -43,7 +48,7 @@ void main(List arguments) async { return; } - _configureLogging(results.flag('verbose')); + logSubscription = _configureLogging(results.flag('verbose')); if (results.flag('verbose')) { Logger.root.fine('All arguments: ${results.arguments}'); @@ -52,20 +57,22 @@ void main(List arguments) async { await runner.run(arguments); } on UsageException catch (e) { stderr.writeln(e); - exit(64); + exitCode = 64; } on Exception catch (e) { stderr.writeln('An error occurred: $e'); - exit(1); + exitCode = 1; } finally { + await logSubscription?.cancel(); httpClient.close(); } } -void _configureLogging(bool verbose) { +StreamSubscription _configureLogging(bool verbose) { Logger.root.level = verbose ? Level.ALL : Level.INFO; - Logger.root.onRecord.listen((record) { + return Logger.root.onRecord.listen((record) { if (record.level >= Level.SEVERE) { stderr.writeln(record.message); + exitCode = 1; } else { stdout.writeln(record.message); } diff --git a/tool/generator/lib/src/commands/base_skill_command.dart b/tool/generator/lib/src/commands/base_skill_command.dart index 9f37850e..5531f3cf 100644 --- a/tool/generator/lib/src/commands/base_skill_command.dart +++ b/tool/generator/lib/src/commands/base_skill_command.dart @@ -5,9 +5,11 @@ import 'dart:io'; import 'package:http/http.dart' as http; +import 'package:meta/meta.dart'; import '../models/skill_params.dart'; import '../services/gemini_service.dart'; +import '../utils/text_metrics.dart'; import 'base_yaml_command.dart'; /// Base command for skill operations requiring AI generation. @@ -53,29 +55,27 @@ abstract class BaseSkillCommand extends BaseYamlCommand { Directory outputDir, { Directory? configDir, }) async { + final dryRun = argResults?['dry-run'] as bool? ?? false; final apiKey = (environment ?? Platform.environment)['GEMINI_API_KEY']; - if (apiKey == null) { + if (!dryRun && (apiKey == null || apiKey.trim().isEmpty)) { logger.severe('GEMINI_API_KEY environment variable not set.'); return; } + final rawBudget = argResults!['thinking-budget'] as String; + final thinkingBudget = int.tryParse(rawBudget); + if (thinkingBudget == null || thinkingBudget < 0) { + logger.severe('Invalid thinking-budget: $rawBudget. Skipping.'); + return; + } + final model = argResults?['model'] as String?; final gemini = GeminiService( - apiKey: apiKey, + apiKey: (apiKey != null && apiKey.trim().isNotEmpty) ? apiKey : 'dry-run', httpClient: httpClient, model: model, ); - int thinkingBudget; - try { - thinkingBudget = int.parse(argResults!['thinking-budget'] as String); - } on FormatException { - logger.warning( - 'Invalid thinking-budget: ${argResults!['thinking-budget']}. Skipping.', - ); - return; - } - for (final skill in skills) { await runSkill( skill, @@ -87,6 +87,20 @@ abstract class BaseSkillCommand extends BaseYamlCommand { } } + /// Logs a warning when [content] exceeds [maxRecommendedSkillLines] lines per + /// the Agent Skills standard. + @protected + void warnIfExceedsLineLimit(String content, {required String prefix}) { + final lines = content.lineCount; + if (lines > maxRecommendedSkillLines) { + logger.warning( + ' $prefix has $lines lines. ' + 'The Agent Skills standard (https://agentskills.io) recommends keeping ' + 'SKILL.md under $maxRecommendedSkillLines lines.', + ); + } + } + /// Executes the command for a specific skill. Future runSkill( SkillParams skill, diff --git a/tool/generator/lib/src/commands/base_yaml_command.dart b/tool/generator/lib/src/commands/base_yaml_command.dart index 1b89d605..280a534a 100644 --- a/tool/generator/lib/src/commands/base_yaml_command.dart +++ b/tool/generator/lib/src/commands/base_yaml_command.dart @@ -2,11 +2,12 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'dart:convert'; import 'dart:io'; import 'package:args/command_runner.dart'; import 'package:logging/logging.dart'; +import 'package:meta/meta.dart'; +import 'package:path/path.dart' as p; import 'package:yaml/yaml.dart'; import '../models/skill_params.dart'; @@ -43,14 +44,38 @@ abstract class BaseYamlCommand extends Command { } final yamlContent = file.readAsStringSync(); - final yamlList = loadYaml(yamlContent) as YamlList; - final skills = yamlList - .map( - (e) => SkillParams.fromJson( - jsonDecode(jsonEncode(e)) as Map, - ), - ) - .toList(); + final YamlList yamlList; + try { + final decoded = loadYaml(yamlContent); + if (decoded is! YamlList) { + logger.severe('Invalid configuration: Root must be a YAML list.'); + return; + } + yamlList = decoded; + } on YamlException catch (e) { + logger.severe('Invalid YAML syntax in $inputFile: $e'); + return; + } + + if (!validateYamlList(yamlList, p.basename(file.path))) { + logger.severe('Configuration validation failed.'); + return; + } + + final skills = []; + for (var i = 0; i < yamlList.length; i++) { + final item = yamlList[i]; + if (item is! Map) { + logger.severe('Invalid configuration: Item $i is not a Map.'); + return; + } + try { + skills.add(SkillParams.fromYamlMap(item)); + } on FormatException catch (e) { + logger.severe('Invalid configuration at item $i: ${e.message}'); + return; + } + } final skillFilter = argResults?['skill'] as String?; final targetSkills = skillFilter != null @@ -74,6 +99,13 @@ abstract class BaseYamlCommand extends Command { await runWithSkills(targetSkills, outDir, configDir: file.parent); } + /// Validates the raw [yamlList] before converting entries to [SkillParams]. + /// + /// Subclasses such as `ValidateSkillCommand` can override this method to + /// perform schema checks without reading or parsing the YAML file twice. + @protected + bool validateYamlList(YamlList yamlList, String fileName) => true; + /// Executes the command with the parsed and filtered list of skills. Future runWithSkills( List skills, diff --git a/tool/generator/lib/src/commands/generate_skill_command.dart b/tool/generator/lib/src/commands/generate_skill_command.dart index 827600c3..927d25e4 100644 --- a/tool/generator/lib/src/commands/generate_skill_command.dart +++ b/tool/generator/lib/src/commands/generate_skill_command.dart @@ -2,7 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'dart:convert'; import 'dart:io'; import 'package:logging/logging.dart'; @@ -11,6 +10,7 @@ import 'package:path/path.dart' as p; import '../models/skill_params.dart'; import '../services/gemini_service.dart'; import '../services/resource_fetcher_service.dart'; +import '../utils/text_metrics.dart'; import 'base_skill_command.dart'; /// Command to generate skills from a configuration file. @@ -26,7 +26,7 @@ class GenerateSkillCommand extends BaseSkillCommand { String get name => 'generate-skill'; @override - String get description => 'Generates skills from using yaml configuration.'; + String get description => 'Generates skills from a YAML configuration file.'; @override Future runSkill( @@ -55,8 +55,8 @@ class GenerateSkillCommand extends BaseSkillCommand { final dryRun = argResults?['dry-run'] as bool? ?? false; if (dryRun) { - final words = RegExp(r'\S+').allMatches(combinedMarkdown).length; - final approxTokens = (words * 1.3).round(); + final words = combinedMarkdown.wordCount; + final approxTokens = combinedMarkdown.approximateTokenCount; logger ..info(' [DRY RUN] Would generate skill: ${skill.name}') ..info( @@ -86,13 +86,10 @@ class GenerateSkillCommand extends BaseSkillCommand { ' Generated ${p.join(outputDir.path, skill.name, 'SKILL.md')}', ); - final lineCount = const LineSplitter().convert(generatedContent).length; - if (lineCount > 500) { - logger.warning( - ' Warning: Generated SKILL.md has $lineCount lines. ' - 'The Agent Skills standard (https://agentskills.io) recommends keeping SKILL.md under 500 lines.', - ); - } + warnIfExceedsLineLimit( + generatedContent, + prefix: 'Warning: Generated SKILL.md', + ); } else { logger.severe(' Failed to generate content for ${skill.name}'); } diff --git a/tool/generator/lib/src/commands/update_readme_command.dart b/tool/generator/lib/src/commands/update_readme_command.dart index f5d36250..5991653e 100644 --- a/tool/generator/lib/src/commands/update_readme_command.dart +++ b/tool/generator/lib/src/commands/update_readme_command.dart @@ -21,6 +21,17 @@ class UpdateReadmeCommand extends BaseYamlCommand { ); } + static final RegExp _tableLineRegExp = RegExp( + r'^\| \[([^\]]+)\]\([^)]+\) \| [^|]+ \| ([^|]+) \|', + multiLine: true, + ); + static final RegExp _sectionHeaderRegExp = RegExp( + '^## (Available Skills|List of Skills|Skills List|Skill Index)', + caseSensitive: false, + multiLine: true, + ); + static final RegExp _nextSectionRegExp = RegExp(r'\n##\s'); + @override String get name => 'update-readme'; @@ -65,11 +76,7 @@ class UpdateReadmeCommand extends BaseYamlCommand { // Parse existing example prompts from the README if they exist final existingPrompts = {}; - final tableLineRegex = RegExp( - r'^\| \[([^\]]+)\]\([^)]+\) \| [^|]+ \| ([^|]+) \|', - multiLine: true, - ); - for (final match in tableLineRegex.allMatches(content)) { + for (final match in _tableLineRegExp.allMatches(content)) { final skillName = match.group(1)!; final prompt = match.group(2)!.trim(); if (prompt.isNotEmpty) { @@ -112,12 +119,7 @@ class UpdateReadmeCommand extends BaseYamlCommand { final newTable = buffer.toString(); // Find where to insert the table - final sectionRegex = RegExp( - '^## (Available Skills|List of Skills|Skills List|Skill Index)', - caseSensitive: false, - multiLine: true, - ); - final match = sectionRegex.firstMatch(content); + final match = _sectionHeaderRegExp.firstMatch(content); String updatedContent; if (match != null) { @@ -125,7 +127,7 @@ class UpdateReadmeCommand extends BaseYamlCommand { final headerEnd = content.indexOf('\n', match.start); // Find the next section header or end of file final nextSectionIndex = content.indexOf( - RegExp(r'\n##\s', multiLine: true), + _nextSectionRegExp, headerEnd + 1, ); diff --git a/tool/generator/lib/src/commands/update_skill_command.dart b/tool/generator/lib/src/commands/update_skill_command.dart index 23129cd3..0c88bc88 100644 --- a/tool/generator/lib/src/commands/update_skill_command.dart +++ b/tool/generator/lib/src/commands/update_skill_command.dart @@ -2,7 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'dart:convert'; import 'dart:io'; import 'package:logging/logging.dart'; @@ -11,6 +10,7 @@ import 'package:path/path.dart' as p; import '../models/skill_params.dart'; import '../services/gemini_service.dart'; import '../services/resource_fetcher_service.dart'; +import '../utils/text_metrics.dart'; import 'base_skill_command.dart'; /// Command to update skills from a configuration file, preserving existing content. @@ -42,7 +42,7 @@ class UpdateSkillCommand extends BaseSkillCommand { final skillFile = File(p.join(outputDir.path, skill.name, 'SKILL.md')); if (!skillFile.existsSync()) { logger.severe( - ' Skill file not found at ${skillFile.path}. Cannot update an non-existent skill.', + ' Skill file not found at ${skillFile.path}. Cannot update a non-existent skill.', ); return; } @@ -66,10 +66,10 @@ class UpdateSkillCommand extends BaseSkillCommand { final dryRun = argResults?['dry-run'] as bool? ?? false; if (dryRun) { - final origWords = RegExp(r'\S+').allMatches(existingContent).length; - final origTokens = (origWords * 1.3).round(); - final rawWords = RegExp(r'\S+').allMatches(combinedMarkdown).length; - final rawTokens = (rawWords * 1.3).round(); + final origWords = existingContent.wordCount; + final origTokens = existingContent.approximateTokenCount; + final rawWords = combinedMarkdown.wordCount; + final rawTokens = combinedMarkdown.approximateTokenCount; logger ..info(' [DRY RUN] Would update skill: ${skill.name}') ..info( @@ -93,13 +93,10 @@ class UpdateSkillCommand extends BaseSkillCommand { ' Updated ${p.join(outputDir.path, skill.name, 'SKILL.md')}', ); - final lineCount = const LineSplitter().convert(generatedContent).length; - if (lineCount > 500) { - logger.warning( - ' Warning: Updated SKILL.md has $lineCount lines. ' - 'The Agent Skills standard (https://agentskills.io) recommends keeping SKILL.md under 500 lines.', - ); - } + warnIfExceedsLineLimit( + generatedContent, + prefix: 'Warning: Updated SKILL.md', + ); } else { logger.severe(' Failed to update content for ${skill.name}'); } diff --git a/tool/generator/lib/src/commands/validate_skill_command.dart b/tool/generator/lib/src/commands/validate_skill_command.dart index 31885181..ce0aa179 100644 --- a/tool/generator/lib/src/commands/validate_skill_command.dart +++ b/tool/generator/lib/src/commands/validate_skill_command.dart @@ -2,7 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'dart:convert'; import 'dart:io'; import 'package:logging/logging.dart'; @@ -12,6 +11,7 @@ import 'package:yaml/yaml.dart'; import '../models/skill_params.dart'; import '../services/gemini_service.dart'; import '../services/resource_fetcher_service.dart'; +import '../utils/text_metrics.dart'; import 'base_skill_command.dart'; /// Command to validate skills by re-generating and comparing with existing skills. @@ -24,6 +24,11 @@ class ValidateSkillCommand extends BaseSkillCommand { this.validationDir, }) : super(logger: Logger('ValidateSkillCommand')); + static final RegExp _kebabCaseRegExp = RegExp(r'^[a-z0-9]+(-[a-z0-9]+)*$'); + static final RegExp _lastModifiedRegExp = RegExp('last_modified: (.*)'); + static final RegExp _modelRegExp = RegExp('model: (.*)'); + static final RegExp _gradeRegExp = RegExp(r'Grade:\s*(\d+)'); + /// The directory to output validation reports. final Directory? validationDir; @@ -32,51 +37,17 @@ class ValidateSkillCommand extends BaseSkillCommand { @override String get description => - 'Validates skills using existing skill files and yaml configuration.'; + 'Validates skills using existing skill files and YAML configuration.'; @override - Future run() async { - final inputFile = argResults!.rest.isNotEmpty - ? argResults!.rest.first - : 'resources/flutter_skills.yaml'; - - final file = File(inputFile); - if (!file.existsSync()) { - logger.severe('Configuration file not found: $inputFile'); - return; - } - - final yamlContent = file.readAsStringSync(); - YamlList yamlList; - try { - final decoded = loadYaml(yamlContent); - if (decoded is! YamlList) { - logger.severe('Invalid configuration: Root must be a YAML list.'); - return; - } - yamlList = decoded; - } on Object catch (e) { - logger.severe('Invalid YAML syntax in $inputFile: $e'); - return; - } - - final isValid = _validateYamlStructure(yamlList, p.basename(file.path)); - if (!isValid) { - logger.severe('Configuration validation failed.'); - return; - } - - await super.run(); - } - - bool _validateYamlStructure(YamlList yamlList, String fileName) { + bool validateYamlList(YamlList yamlList, String fileName) { if (yamlList.isEmpty) { logger.severe('Configuration list must not be empty.'); return false; } var isValid = true; - final kabobCase = RegExp(r'^[a-z0-9]+(-[a-z0-9]+)*$'); + final seenNames = {}; for (var i = 0; i < yamlList.length; i++) { final item = yamlList[i]; @@ -103,10 +74,10 @@ class ValidateSkillCommand extends BaseSkillCommand { } else if (rawDescription is! String) { logger.severe('Skill "$name" field "description" must be a string.'); isValid = false; - } else if (rawDescription.length > 1024) { + } else if (rawDescription.length > maxSkillDescriptionLength) { logger.warning( - 'Skill "$name" description exceeds 1024 characters (${rawDescription.length} chars). ' - 'The Agent Skills standard (https://agentskills.io) limits descriptions to 1024 characters.', + 'Skill "$name" description exceeds $maxSkillDescriptionLength characters (${rawDescription.length} chars). ' + 'The Agent Skills standard (https://agentskills.io) limits descriptions to $maxSkillDescriptionLength characters.', ); } @@ -120,8 +91,18 @@ class ValidateSkillCommand extends BaseSkillCommand { isValid = false; } + if (item['examplePrompt'] != null && item['examplePrompt'] is! String) { + logger.severe('Skill "$name" field "examplePrompt" must be a string.'); + isValid = false; + } + if (rawName is String) { - if (!kabobCase.hasMatch(name)) { + if (!seenNames.add(name)) { + logger.severe('Duplicate skill name "$name" in $fileName.'); + isValid = false; + } + + if (!_kebabCaseRegExp.hasMatch(name)) { logger.severe( 'Skill name "$name" must be kabob-case (e.g. abc-def).', ); @@ -228,37 +209,26 @@ class ValidateSkillCommand extends BaseSkillCommand { } // Check file length per agentskills.io recommendation (< 500 lines) - final lineCount = const LineSplitter() - .convert(existingSkillFileContent) - .length; - if (lineCount > 500) { - logger.warning( - ' Validation Warning: ${existingSkillFile.path} has $lineCount lines. ' - 'The Agent Skills standard (https://agentskills.io) recommends keeping SKILL.md under 500 lines.', - ); - } + warnIfExceedsLineLimit( + existingSkillFileContent, + prefix: 'Validation Warning: ${existingSkillFile.path}', + ); // Extract metadata from existing content final generationDate = - RegExp( - 'last_modified: (.*)', - ).firstMatch(existingSkillFileContent)?.group(1) ?? + _lastModifiedRegExp.firstMatch(existingSkillFileContent)?.group(1) ?? 'Unknown'; final modelName = - RegExp( - 'model: (.*)', - ).firstMatch(existingSkillFileContent)?.group(1) ?? + _modelRegExp.firstMatch(existingSkillFileContent)?.group(1) ?? 'Unknown'; // Compare final dryRun = argResults?['dry-run'] as bool? ?? false; if (dryRun) { - final existWords = RegExp( - r'\S+', - ).allMatches(existingSkillFileContent).length; - final existTokens = (existWords * 1.3).round(); - final rawWords = RegExp(r'\S+').allMatches(markdown).length; - final rawTokens = (rawWords * 1.3).round(); + final existWords = existingSkillFileContent.wordCount; + final existTokens = existingSkillFileContent.approximateTokenCount; + final rawWords = markdown.wordCount; + final rawTokens = markdown.approximateTokenCount; logger ..info(' [DRY RUN] Would validate skill: ${skill.name}') ..info( @@ -288,7 +258,7 @@ class ValidateSkillCommand extends BaseSkillCommand { File(p.join(valDir.path, 'validation.md')).writeAsStringSync(result); // Extract and log the grade - final gradeMatch = RegExp(r'Grade:\s*(\d+)').firstMatch(result); + final gradeMatch = _gradeRegExp.firstMatch(result); final grade = gradeMatch?.group(1); logger.info( diff --git a/tool/generator/lib/src/models/skill_params.dart b/tool/generator/lib/src/models/skill_params.dart index e2d833a2..64f165e0 100644 --- a/tool/generator/lib/src/models/skill_params.dart +++ b/tool/generator/lib/src/models/skill_params.dart @@ -14,13 +14,56 @@ class SkillParams { }); /// Creates a [SkillParams] instance from a JSON map. - factory SkillParams.fromJson(Map json) { + factory SkillParams.fromJson(Map json) => + SkillParams.fromYamlMap(json); + + /// Creates a [SkillParams] instance from a decoded YAML or JSON map. + /// + /// Throws a [FormatException] if required fields are missing or have invalid + /// types. + factory SkillParams.fromYamlMap(Map map) { + final name = map['name']; + if (name is! String || name.trim().isEmpty) { + throw const FormatException('Skill "name" must be a non-empty string.'); + } + final description = map['description']; + if (description is! String) { + throw FormatException( + 'Skill "$name" field "description" must be a string.', + ); + } + final rawResources = map['resources']; + if (rawResources is! List) { + throw FormatException('Skill "$name" field "resources" must be a list.'); + } + final resources = []; + for (final resource in rawResources) { + if (resource is! String) { + throw FormatException( + 'Skill "$name" resource entries must be strings.', + ); + } + resources.add(resource); + } + final instructions = map['instructions']; + if (instructions != null && instructions is! String) { + throw FormatException( + 'Skill "$name" field "instructions" must be a string.', + ); + } + final examplePrompt = map['examplePrompt']; + if (examplePrompt != null && examplePrompt is! String) { + throw FormatException( + 'Skill "$name" field "examplePrompt" must be a string.', + ); + } + return SkillParams( - name: json['name'] as String, - description: json['description'] as String, - resources: (json['resources'] as List).cast(), - instructions: json['instructions'] as String?, - examplePrompt: json['examplePrompt'] as String?, + name: name, + description: description, + resources: List.unmodifiable(resources), + instructions: instructions as String?, + examplePrompt: examplePrompt as String?, ); } diff --git a/tool/generator/lib/src/utils/text_metrics.dart b/tool/generator/lib/src/utils/text_metrics.dart new file mode 100644 index 00000000..ea0b5935 --- /dev/null +++ b/tool/generator/lib/src/utils/text_metrics.dart @@ -0,0 +1,68 @@ +// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +/// Recommended maximum line count for a `SKILL.md` file per the Agent Skills +/// standard (https://agentskills.io). +const int maxRecommendedSkillLines = 500; + +/// Maximum `description` length in characters per the Agent Skills standard +/// (https://agentskills.io). +const int maxSkillDescriptionLength = 1024; + +/// Approximate ratio of LLM tokens per whitespace-delimited word. +/// +/// Subword tokenizers used by Gemini (SentencePiece/BPE) average roughly +/// 4 characters per token, or 100 tokens per 60–80 English words (~0.75 words +/// per token, whose reciprocal is ~1.33 tokens per word). We use `1.3` as a +/// fast offline dry-run heuristic without making network calls to `countTokens`. +/// +/// See: https://ai.google.dev/gemini-api/docs/tokens +const double tokensPerWordEstimate = 1.3; + +final RegExp _nonWhitespaceWordRegExp = RegExp(r'\S+'); + +/// Extension methods on [RegExp] for match counting without allocating +/// intermediate substring lists. +extension RegExpMatchCount on RegExp { + /// Returns the number of non-overlapping matches of this pattern in [input] + /// without allocating intermediate substring lists. + int countMatches(String input) => allMatches(input).length; +} + +/// Extension methods on [String] for document size and token estimation. +extension StringMetrics on String { + /// Number of whitespace-delimited words in this string. + int get wordCount => _nonWhitespaceWordRegExp.countMatches(this); + + /// Approximate LLM token count using [tokensPerWordEstimate] (~1.3 tokens + /// per whitespace-delimited word). + int get approximateTokenCount => (wordCount * tokensPerWordEstimate).round(); + + /// Number of lines in this string without allocating intermediate substrings. + /// + /// Matches `LineSplitter` semantics for `\n`, `\r`, and `\r\n`, ignoring a + /// single trailing line terminator at the end of the string. + int get lineCount { + if (isEmpty) return 0; + var lines = 0; + for (var i = 0; i < length; i++) { + final unit = codeUnitAt(i); + if (unit == 0x0D) { + lines++; + if (i + 1 < length && codeUnitAt(i + 1) == 0x0A) { + i++; + } + if (i == length - 1) { + return lines; + } + } else if (unit == 0x0A) { + lines++; + if (i == length - 1) { + return lines; + } + } + } + return lines + 1; + } +} diff --git a/tool/generator/test/commands/base_skill_command_test.dart b/tool/generator/test/commands/base_skill_command_test.dart index 48edfbf4..c84cf4d1 100644 --- a/tool/generator/test/commands/base_skill_command_test.dart +++ b/tool/generator/test/commands/base_skill_command_test.dart @@ -18,6 +18,8 @@ class _TestSkillCommand extends BaseSkillCommand { _TestSkillCommand({required super.httpClient, super.environment}) : super(logger: Logger('_TestSkillCommand')); + int runSkillCalls = 0; + @override String get name => 'test-command'; @@ -31,7 +33,9 @@ class _TestSkillCommand extends BaseSkillCommand { Directory outputDir, int thinkingBudget, { Directory? configDir, - }) async {} + }) async { + runSkillCalls++; + } } void main() { @@ -40,6 +44,7 @@ void main() { late Directory tempDir; late MockClient mockClient; final logs = []; + final records = []; setUp(() async { tempDir = await Directory.systemTemp.createTemp( @@ -50,13 +55,19 @@ void main() { ..addCommand(_TestSkillCommand(httpClient: mockClient)); Logger.root.level = Level.INFO; - Logger.root.onRecord.listen((record) => logs.add(record.message)); + final sub = Logger.root.onRecord.listen((record) { + logs.add(record.message); + records.add(record); + }); + addTearDown(sub.cancel); logs.clear(); + records.clear(); }); tearDown(() async { await tempDir.delete(recursive: true); logs.clear(); + records.clear(); }); test('logs severe error when configuration file not found', () async { @@ -68,6 +79,38 @@ void main() { expect(logs, contains('Configuration file not found: $path')); }); + test( + 'logs severe error when YAML syntax or item schema is invalid', + () async { + final invalidYamlFile = File(p.join(tempDir.path, 'invalid.yaml')); + await invalidYamlFile.writeAsString(': invalid: [yaml'); + await runner.run(['test-command', invalidYamlFile.path]); + expect(logs, contains(contains('Invalid YAML syntax in'))); + + logs.clear(); + final nonMapItemFile = File(p.join(tempDir.path, 'non_map.yaml')); + await nonMapItemFile.writeAsString(jsonEncode([123])); + await runner.run(['test-command', nonMapItemFile.path]); + expect(logs, contains('Invalid configuration: Item 0 is not a Map.')); + + logs.clear(); + final badMapItemFile = File(p.join(tempDir.path, 'bad_map.yaml')); + await badMapItemFile.writeAsString( + jsonEncode([ + {'name': 'foo', 'description': 123, 'resources': []}, + ]), + ); + await runner.run(['test-command', badMapItemFile.path]); + expect( + logs, + contains( + 'Invalid configuration at item 0: ' + 'Skill "foo" field "description" must be a string.', + ), + ); + }, + ); + test('logs warning when no skills match the --skill filter', () async { final configFile = File(p.join(tempDir.path, 'config.yaml')); await configFile.writeAsString( @@ -103,7 +146,52 @@ void main() { expect(logs, contains('No skills found in configuration file.')); }); - test('logs severe error when GEMINI_API_KEY is not set', () async { + test( + 'logs severe error when GEMINI_API_KEY is missing or blank unless --dry-run', + () async { + final configFile = File(p.join(tempDir.path, 'config.yaml')); + await configFile.writeAsString( + jsonEncode(>[ + { + 'name': 'existent-skill', + 'description': 'desc', + 'resources': [], + }, + ]), + ); + + final missingKeyCommand = _TestSkillCommand( + httpClient: mockClient, + environment: {}, + ); + runner = CommandRunner('skills', 'Test runner') + ..addCommand(missingKeyCommand); + await runner.run(['test-command', configFile.path]); + expect(logs, contains('GEMINI_API_KEY environment variable not set.')); + expect(missingKeyCommand.runSkillCalls, 0); + + logs.clear(); + await runner.run(['test-command', '--dry-run', configFile.path]); + expect( + logs, + isNot(contains('GEMINI_API_KEY environment variable not set.')), + ); + expect(missingKeyCommand.runSkillCalls, 1); + + logs.clear(); + final blankKeyCommand = _TestSkillCommand( + httpClient: mockClient, + environment: {'GEMINI_API_KEY': ' '}, + ); + runner = CommandRunner('skills', 'Test runner') + ..addCommand(blankKeyCommand); + await runner.run(['test-command', configFile.path]); + expect(logs, contains('GEMINI_API_KEY environment variable not set.')); + expect(blankKeyCommand.runSkillCalls, 0); + }, + ); + + test('logs severe error when --thinking-budget is invalid', () async { final configFile = File(p.join(tempDir.path, 'config.yaml')); await configFile.writeAsString( jsonEncode(>[ @@ -115,17 +203,28 @@ void main() { ]), ); - // Override environment parameter to simulate missing api key - runner = CommandRunner( - 'skills', - 'Test runner', - )..addCommand(_TestSkillCommand(httpClient: mockClient, environment: {})); - - await IOOverrides.runZoned(() async { - await runner.run(['test-command', configFile.path]); - }, getCurrentDirectory: () => tempDir); - - expect(logs, contains('GEMINI_API_KEY environment variable not set.')); + runner = CommandRunner('skills', 'Test runner') + ..addCommand( + _TestSkillCommand( + httpClient: mockClient, + environment: {'GEMINI_API_KEY': 'test-key'}, + ), + ); + + await runner.run([ + 'test-command', + configFile.path, + '--thinking-budget', + '-1', + ]); + expect( + records.any( + (r) => + r.level == Level.SEVERE && + r.message.contains('Invalid thinking-budget: -1. Skipping.'), + ), + isTrue, + ); }); test('defines model option defaulting to GeminiService.defaultModel', () { diff --git a/tool/generator/test/commands/validate_skills_input_test.dart b/tool/generator/test/commands/validate_skills_input_test.dart index b287e6bd..ff9b0605 100644 --- a/tool/generator/test/commands/validate_skills_input_test.dart +++ b/tool/generator/test/commands/validate_skills_input_test.dart @@ -27,9 +27,10 @@ void main() { mockClient = MockClient((request) async => http.Response('', 200)); Logger.root.level = Level.INFO; - Logger.root.onRecord.listen((record) { + final sub = Logger.root.onRecord.listen((record) { logs.add(record.message); }); + addTearDown(sub.cancel); logs.clear(); }); @@ -225,6 +226,7 @@ void main() { await runValidation('flutter_skills.yaml', content1); expect(logs, contains('Item 0 field "name" must be a string.')); + expect(logs, contains('Configuration validation failed.')); logs.clear(); final content2 = jsonEncode([ @@ -240,6 +242,7 @@ void main() { logs, contains('Skill "flutter-skill" field "description" must be a string.'), ); + expect(logs, contains('Configuration validation failed.')); logs.clear(); final content3 = jsonEncode([ @@ -258,6 +261,50 @@ void main() { 'Skill "flutter-skill" field "instructions" must be a string.', ), ); + expect(logs, contains('Configuration validation failed.')); + + logs.clear(); + final content4 = jsonEncode([ + { + 'name': 'flutter-skill', + 'description': 'A Flutter skill description', + 'resources': ['https://example.com'], + 'examplePrompt': 123, // int, should be string + }, + ]); + + await runValidation('flutter_skills.yaml', content4); + expect( + logs, + contains( + 'Skill "flutter-skill" field "examplePrompt" must be a string.', + ), + ); + expect(logs, contains('Configuration validation failed.')); + }); + + test('fails when configuration contains duplicate skill names', () async { + final content = jsonEncode([ + { + 'name': 'flutter-duplicate-skill', + 'description': 'First skill description', + 'resources': ['https://example.com/first'], + }, + { + 'name': 'flutter-duplicate-skill', + 'description': 'Second skill description', + 'resources': ['https://example.com/second'], + }, + ]); + + await runValidation('flutter_skills.yaml', content); + expect( + logs, + contains( + 'Duplicate skill name "flutter-duplicate-skill" in flutter_skills.yaml.', + ), + ); + expect(logs, contains('Configuration validation failed.')); }); }); } diff --git a/tool/generator/test/models/skill_params_test.dart b/tool/generator/test/models/skill_params_test.dart index b0293775..40cb9253 100644 --- a/tool/generator/test/models/skill_params_test.dart +++ b/tool/generator/test/models/skill_params_test.dart @@ -33,5 +33,61 @@ void main() { expect(skill.resources, ['http://example.com']); expect(skill.instructions, 'Do not hallucinate.'); }); + + test('fromYamlMap parses untyped YAML maps including examplePrompt', () { + final yamlMap = { + 'name': 'yaml-skill', + 'description': 'YAML Description', + 'resources': ['https://example.com/doc'], + 'instructions': 'Keep under 500 lines.', + 'examplePrompt': 'Build a responsive layout.', + }; + final skill = SkillParams.fromYamlMap(yamlMap); + expect(skill.name, 'yaml-skill'); + expect(skill.description, 'YAML Description'); + expect(skill.resources, ['https://example.com/doc']); + expect(skill.instructions, 'Keep under 500 lines.'); + expect(skill.examplePrompt, 'Build a responsive layout.'); + }); + + test('fromYamlMap throws FormatException on invalid field types', () { + expect( + () => SkillParams.fromYamlMap({}), + throwsFormatException, + ); + expect( + () => SkillParams.fromYamlMap({ + 'name': 'foo', + 'description': 123, + 'resources': ['https://example.com'], + }), + throwsFormatException, + ); + expect( + () => SkillParams.fromYamlMap({ + 'name': 'foo', + 'description': 'desc', + 'resources': [123], + }), + throwsFormatException, + ); + expect( + () => SkillParams.fromYamlMap({ + 'name': ' ', + 'description': 'desc', + 'resources': ['https://example.com'], + }), + throwsFormatException, + ); + expect( + () => SkillParams.fromYamlMap({ + 'name': 'foo', + 'description': 'desc', + 'resources': ['https://example.com'], + 'examplePrompt': 456, + }), + throwsFormatException, + ); + }); }); } diff --git a/tool/generator/test/skills_cli_test.dart b/tool/generator/test/skills_cli_test.dart new file mode 100644 index 00000000..6fb5e47e --- /dev/null +++ b/tool/generator/test/skills_cli_test.dart @@ -0,0 +1,47 @@ +// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; + +import '../bin/skills.dart' as cli; + +void main() { + group('skills CLI entrypoint', () { + late Directory tempDir; + + setUp(() async { + exitCode = 0; + tempDir = await Directory.systemTemp.createTemp('skills_cli_test'); + }); + + tearDown(() async { + exitCode = 0; + await tempDir.delete(recursive: true); + }); + + test('exits 0 for --version and warning-only runs', () async { + await cli.main(['--version']); + expect(exitCode, 0); + + final emptyConfig = File(p.join(tempDir.path, 'empty.yaml')) + ..writeAsStringSync('[]'); + await cli.main(['generate-skill', emptyConfig.path]); + expect(exitCode, 0); + }); + + test('sets exitCode = 64 on UsageException', () async { + await cli.main(['--unknown-flag']); + expect(exitCode, 64); + }); + + test('sets exitCode = 1 when a SEVERE error is logged', () async { + final missingPath = p.join(tempDir.path, 'does_not_exist.yaml'); + await cli.main(['generate-skill', missingPath]); + expect(exitCode, 1); + }); + }); +} diff --git a/tool/generator/test/update_skills_test.dart b/tool/generator/test/update_skills_test.dart index 4c9680e4..5ab2080f 100644 --- a/tool/generator/test/update_skills_test.dart +++ b/tool/generator/test/update_skills_test.dart @@ -131,7 +131,7 @@ void main() { await runner.run(['update-skill', inputYamlFile.path]); expect(logs, contains(contains('Skill file not found at'))); - expect(logs, contains(contains('Cannot update an non-existent skill.'))); + expect(logs, contains(contains('Cannot update a non-existent skill.'))); }); test( diff --git a/tool/generator/test/utils/text_metrics_test.dart b/tool/generator/test/utils/text_metrics_test.dart new file mode 100644 index 00000000..0094c5b8 --- /dev/null +++ b/tool/generator/test/utils/text_metrics_test.dart @@ -0,0 +1,116 @@ +// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import 'dart:convert'; + +import 'package:skills/src/utils/text_metrics.dart'; +import 'package:test/test.dart'; + +void main() { + group('Agent Skills standard constants', () { + test('exposes expected Agent Skills limits and token ratio', () { + expect(maxRecommendedSkillLines, 500); + expect(maxSkillDescriptionLength, 1024); + expect(tokensPerWordEstimate, 1.3); + }); + }); + + group('RegExpMatchCount', () { + test('returns 0 when input is empty or has no matches', () { + final digits = RegExp(r'\d+'); + expect(digits.countMatches(''), 0); + expect(digits.countMatches('no numbers here'), 0); + }); + + test('counts non-overlapping matches across single and multiple lines', () { + final digits = RegExp(r'\d+'); + expect(digits.countMatches('1 22 333\n4444'), 4); + + final headings = RegExp(r'^#+\s+', multiLine: true); + expect(headings.countMatches('# Title\nBody\n## Section 1\n### Sub'), 3); + }); + }); + + group('StringMetrics', () { + group('wordCount', () { + test('returns 0 for empty and whitespace-only strings', () { + expect(''.wordCount, 0); + expect(' '.wordCount, 0); + expect('\t\n\r\n '.wordCount, 0); + }); + + test('counts single and multiple whitespace-delimited words', () { + expect('hello'.wordCount, 1); + expect(' hello world '.wordCount, 2); + expect('one\ttwo\nthree\r\nfour'.wordCount, 4); + }); + + test('counts markdown tokens and punctuation-attached words', () { + const markdown = '# Heading\n\n- `code_symbol`: value (v1.2.3)'; + // Tokens: #, Heading, -, `code_symbol`:, value, (v1.2.3) + expect(markdown.wordCount, 6); + }); + }); + + group('approximateTokenCount', () { + test('returns 0 for empty and whitespace-only strings', () { + expect(''.approximateTokenCount, 0); + expect(' \n\t '.approximateTokenCount, 0); + }); + + test('multiplies wordCount by 1.3 and rounds to nearest integer', () { + // 1 * 1.3 = 1.3 -> 1 + expect('one'.approximateTokenCount, 1); + // 2 * 1.3 = 2.6 -> 3 + expect('one two'.approximateTokenCount, 3); + // 4 * 1.3 = 5.2 -> 5 + expect('one two three four'.approximateTokenCount, 5); + // 7 * 1.3 = 9.1 -> 9 + expect('a b c d e f g'.approximateTokenCount, 9); + // 8 * 1.3 = 10.4 -> 10 + expect('a b c d e f g h'.approximateTokenCount, 10); + // 10 * 1.3 = 13.0 -> 13 + expect('a b c d e f g h i j'.approximateTokenCount, 13); + }); + }); + + group('lineCount', () { + test('returns 0 for empty string', () { + expect(''.lineCount, 0); + }); + + test('counts single and multi-line LF, CR, and CRLF strings', () { + expect('single line'.lineCount, 1); + expect('line 1\nline 2\nline 3'.lineCount, 3); + expect('line 1\rline 2\rline 3'.lineCount, 3); + expect('line 1\r\nline 2\r\nline 3'.lineCount, 3); + }); + + test('matches LineSplitter across trailing newline edge cases', () { + const samples = [ + '', + '\n', + '\r', + '\r\n', + '\n\n', + '\r\n\r\n', + 'a', + 'a\n', + 'a\r', + 'a\r\n', + 'line 1\nline 2\n', + 'line 1\nline 2\n\n', + 'line 1\rline 2\r\nline 3\n', + ]; + for (final sample in samples) { + expect( + sample.lineCount, + const LineSplitter().convert(sample).length, + reason: 'Mismatch for ${jsonEncode(sample)}', + ); + } + }); + }); + }); +}