API Reference

Documentation > Reference > API Reference

API Reference

gsd-skill-creator exports a comprehensive API for programmatic skill management. This reference documents all public exports from src/index.ts.

Quick Start

import { createStores, createApplicationContext } from 'gsd-skill-creator';

// Basic usage - create stores for skill management
const { skillStore, skillIndex, patternStore } = createStores();

// List all skills
const skills = await skillIndex.getAll();

// Full application context with skill applicator
const { skillStore, skillIndex, applicator } = createApplicationContext();
const result = await applicator.apply('commit my changes');

Public Exports

Quick reference of all exports organized by functional layer.

Storage

Export Type Description
SkillStore Class CRUD operations for skill files
PatternStore Class Pattern persistence for learning
SkillIndex Class In-memory skill index with search
createStores() Function Factory for all stores
createScopedStores() Function Scope-aware store factory
createApplicationContext() Function Full context with applicator
listAllScopes() Function List available skill scopes

Validation

Export Type Description
SkillInputSchema Zod Schema Complete skill input validation
SkillNameSchema Zod Schema Name validation rules
TriggerPatternsSchema Zod Schema Trigger pattern validation
SkillUpdateSchema Zod Schema Partial update validation
validateSkillInput() Function Validate skill input data
validateSkillUpdate() Function Validate skill updates
validateSkillName() Function Basic name validation
validateSkillMetadata() Function Metadata schema check

Application

Export Type Description
TokenCounter Class Count tokens in skill content
RelevanceScorer Class Score skill relevance to prompts
ConflictResolver Class Resolve overlapping skill activations
SkillSession Class Manage active skill session
SkillApplicator Class Apply skills to prompts

Learning

Export Type Description
FeedbackStore Class Store correction feedback
FeedbackDetector Class Detect corrections in output
RefinementEngine Class Generate bounded refinements
VersionManager Class Track skill versions

Calibration

Export Type Description
CalibrationStore Class Store calibration events
ThresholdOptimizer Class Find optimal threshold
ThresholdHistory Class Track threshold changes
BenchmarkReporter Class Generate benchmark reports
calculateMCC() Function Matthews Correlation Coefficient

Teams

Export Type Description
TeamStore Class CRUD operations for team config files
getTeamsBasePath() Function Get teams directory for scope
generateLeaderWorkerTemplate() Function Generate leader/worker team config
generatePipelineTemplate() Function Generate pipeline team config
generateSwarmTemplate() Function Generate swarm team config
writeTeamAgentFiles() Function Write agent .md files for team members
validateTeamFull() Function Run all validation checks on team config

Discovery

Export Type Description
parseSessionFile() Function Stream-parse a JSONL session file
CorpusScanner Class Incremental scanning with watermarks
PatternAggregator Class Aggregate patterns across sessions
rankCandidates() Function Rank and deduplicate candidates
generateSkillDraft() Function Generate draft SKILL.md content
dbscan() Function DBSCAN clustering algorithm
clusterPrompts() Function Full clustering pipeline

Factory Functions

createStores()

Create all stores with consistent paths.

import { createStores } from 'gsd-skill-creator';
const { skillStore, skillIndex, patternStore } = createStores();

// With scope
const stores = createStores({ scope: 'user' }); // Uses ~/.claude/skills

Parameters: patternsDir (string), skillsDir (string), scope (SkillScope)

Returns: { patternStore, skillStore, skillIndex }

createScopedStores()

Create stores configured for a specific scope (user or project).

const stores = createScopedStores('user');  // ~/.claude/skills
const stores = createScopedStores('project'); // .claude/skills

createApplicationContext()

Create full application context including the skill applicator.

const { skillStore, skillIndex, patternStore, applicator } = createApplicationContext();
const result = await applicator.apply('commit my changes');

Storage Layer

SkillStore

File-based storage for skills. Skills stored in subdirectory format: skill-name/SKILL.md.

Method Parameters Returns Description
create name, metadata, body Promise<Skill> Create new skill
read name Promise<Skill> Read skill by name
update name, metadata?, body? Promise<Skill> Update existing skill
delete name Promise<void> Delete skill
list Promise<string[]> List all skill names
exists name Promise<boolean> Check if skill exists

PatternStore

Append-only storage for usage patterns, stored as JSONL files organized by category.

Method Parameters Returns Description
append category, data Promise<void> Append pattern to category file
read category Promise<Pattern[]> Read all patterns from category

SkillIndex

In-memory index for fast skill lookups and search. Maintains .skill-index.json for persistence.

Method Parameters Returns Description
load Promise<void> Load index from disk
rebuild Promise<void> Rebuild index from skills
getAll Promise<SkillIndexEntry[]> Get all indexed skills
getEnabled Promise<SkillIndexEntry[]> Get enabled skills only
search query Promise<SkillIndexEntry[]> Search by name/description
findByTrigger intent?, file?, context? Promise<SkillIndexEntry[]> Find by trigger pattern

Validation

Zod schemas and validation functions for skill input validation.

Schemas

Schema Purpose
SkillInputSchema Full skill creation input validation
SkillUpdateSchema Partial skill update validation
OfficialSkillNameSchema Strict official name validation
TriggerPatternsSchema Trigger patterns array validation
SkillMetadataSchema Full metadata validation

Key Validation Functions

Function Description
validateSkillInput(input) Validate complete skill input for creation. Throws on failure.
validateSkillUpdate(input) Validate partial skill update data.
validateSkillNameStrict(name) Strict name validation with detailed errors and suggestions.
validateReservedName(name) Check if name conflicts with Claude Code built-in commands.
validateDescriptionQuality(desc) Check description quality for reliable activation.
hasActivationPattern(desc) Quick check for activation-friendly patterns.
suggestFixedName(input) Transform invalid name into valid suggestion.

Name Requirements: 1-64 characters, lowercase letters/numbers/hyphens only, must start and end with letter or number, no consecutive hyphens.


TypeScript Types

Core Types

Type Source Description
Skill types/skill.ts Complete skill structure
SkillMetadata types/skill.ts YAML frontmatter fields
SkillScope types/scope.ts 'user' | 'project'
Pattern types/pattern.ts Usage pattern structure
TeamConfig types/team.ts Top-level team configuration
TeamMember types/team.ts Team member definition
TeamTopology types/team.ts 'leader-worker' | 'pipeline' | 'swarm' | 'custom'
ApplicationConfig types/application.ts Application configuration
CalibrationEvent calibration/index.ts Recorded calibration event
TestCase testing/test-store.ts Complete test case

Embeddings

getEmbeddingService()

Get an initialized EmbeddingService singleton. Uses BGE-small-en-v1.5 for 384-dimensional embeddings with automatic TF-IDF fallback.

const service = await getEmbeddingService();
const result = await service.embed('commit my changes');
console.log(result.embedding.length); // 384

EmbeddingService Methods

Method Returns Description
embed(text, skillName?) Promise<EmbeddingResult> Generate embedding for single text
embedBatch(texts, skillNames?) Promise<EmbeddingResult[]> Batch embedding for efficiency
getStatus() ServiceStatus Check service status
isUsingFallback() boolean Check if using heuristic mode
reloadModel() Promise<boolean> Attempt to reload model after fallback

cosineSimilarity()

Calculate similarity between two embedding vectors. Returns -1 to 1 (higher = more similar).

import { cosineSimilarity, getEmbeddingService } from 'gsd-skill-creator';
const service = await getEmbeddingService();
const e1 = (await service.embed('commit changes')).embedding;
const e2 = (await service.embed('save changes')).embedding;
console.log(cosineSimilarity(e1, e2)); // ~0.85 (similar)

Conflict Detection

ConflictDetector

Detect skills with overlapping descriptions using embedding similarity.

const detector = new ConflictDetector({ threshold: 0.85 });
const result = await detector.detect(skills);
result.conflicts.forEach(c => {
  console.log(`${c.skillA} <-> ${c.skillB}: ${(c.similarity * 100).toFixed(1)}%`);
});

Severity Levels:

Severity Similarity Meaning
high > 90% Very likely conflict, activation confusion probable
medium 85-90% Possible conflict, worth reviewing

RewriteSuggester

Generate suggestions to differentiate conflicting skills. Uses Claude API when ANTHROPIC_API_KEY is available; otherwise heuristic suggestions.


Simulation

ActivationSimulator

Simulate which skill would activate for a given prompt.

const simulator = new ActivationSimulator({ threshold: 0.75 });
const result = await simulator.simulate('commit my changes', skills);
if (result.winner) {
  console.log(`Would activate: ${result.winner.skillName}`);
  console.log(`Confidence: ${result.winner.confidence.toFixed(1)}%`);
}

BatchSimulator

Run simulations across multiple prompts efficiently (5x+ speedup via batching).

const batch = new BatchSimulator({ concurrency: 20 });
const result = await batch.runTestSuite(prompts, skills);
console.log(`Activations: ${result.stats.activations}`);

Confidence Levels

Level Score Range Meaning
high >= 85% Strong match, reliable activation
medium 70-84% Reasonable match, likely correct
low 50-69% Weak match, may need review
none < 50% No meaningful match

Learning Module

FeedbackStore

Store and retrieve correction feedback for skills.

Method Description
record(event) Record a feedback event
getAll() Get all feedback events
getBySkill(name) Get feedback for specific skill

RefinementEngine

Generate bounded refinements from accumulated feedback. Requires 3+ corrections, limited to 20% content change, 7-day cooldown.

Method Description
suggest(skillName) Generate refinement suggestion
checkEligibility(skillName) Check if skill is eligible
apply(skillName, suggestion) Apply approved refinement

VersionManager

Track skill versions and enable rollback via git history.


Calibration

CalibrationStore

Persist calibration events (JSONL format at ~/.gsd-skill/calibration/events.jsonl).

Method Returns Description
record(input) Promise<CalibrationEvent> Record new calibration event
getKnownOutcomes() Promise<CalibrationEvent[]> Get events with known outcomes
count(knownOnly?) Promise<number> Count events

ThresholdOptimizer

Find optimal activation thresholds using F1 score optimization via grid search.

const optimizer = new ThresholdOptimizer();
const result = optimizer.findOptimalThreshold(events, currentThreshold);
console.log(`Optimal: ${result.optimalThreshold} (F1: ${(result.optimalF1 * 100).toFixed(1)}%)`);

ThresholdHistory

Track threshold changes over time for auditing and rollback.

BenchmarkReporter

Generate benchmark reports for accuracy analysis.

MCC Utilities

import { calculateMCC, mccToPercentage } from 'gsd-skill-creator';
const mcc = calculateMCC(80, 15, 3, 2); // TP, TN, FP, FN
console.log(`Correlation: ${mccToPercentage(mcc)}%`); // ~87%

Testing

TestStore

Persist test cases per skill at <skillsDir>/<skillName>/tests.json.

Method Returns Description
add(skillName, input) Promise<TestCase> Add new test case
get(skillName, testId) Promise<TestCase | null> Get test case by ID
update(skillName, testId, updates) Promise<TestCase | null> Update test case
delete(skillName, testId) Promise<boolean> Delete test case
list(skillName) Promise<TestCase[]> List all test cases

TestRunner

Execute test cases and collect results. Connects TestStore with BatchSimulator.

const runner = new TestRunner(testStore, skillStore, resultStore, 'user');
const result = await runner.runForSkill('git-commit', { threshold: 0.75 });
console.log(`Accuracy: ${result.metrics.accuracy}%`);

Teams Module

Template Generators

Function Description
generateLeaderWorkerTemplate(opts) 1 coordinator + N workers
generatePipelineTemplate(opts) 1 orchestrator + N sequential stages
generateSwarmTemplate(opts) 1 coordinator + N self-claiming workers
generateGsdResearchTeam(opts?) 1 synthesizer + 4 dimension researchers
generateGsdDebuggingTeam(opts?) 1 coordinator + 3 adversarial debuggers

TeamStore

File-based persistence for team configurations at {teamsDir}/{teamName}/config.json.

Method Returns Description
save(config) Promise<string> Validate and save config
read(teamName) Promise<TeamConfig> Read config by team name
list() Promise<string[]> List all team names
delete(teamName) Promise<void> Delete team config

Team Validation

validateTeamFull(config, options?) runs all 7 validation checks: schema validation, topology rules, member resolution, task cycles, tool overlap, skill conflicts, role coherence.


Discovery Module

Session Parsing

import { parseSessionFile, enumerateSessions } from 'gsd-skill-creator';
for await (const entry of parseSessionFile('/path/to/session.jsonl')) {
  if (entry.kind === 'tool-uses') console.log('Tools:', entry.tools.map(t => t.name));
}

Incremental Scanning

const scanner = new CorpusScanner({ stateStore, excludeProjects: ['private'] });
const result = await scanner.scan(async (file, meta) => { /* process */ });
console.log(`Scanned ${result.newSessions} new sessions`);

Pattern Extraction

const bigrams = extractNgrams(['Read', 'Edit', 'Bash'], 2); // ['Read->Edit', 'Edit->Bash']
const category = classifyBashCommand('git commit -m "fix"'); // 'git'

Ranking and Drafting

const ranked = rankCandidates(patterns, { totalSessions: 100, existingSkills });
const selected = await selectCandidates(ranked);
for (const c of selected) console.log(generateSkillDraft(c));

Semantic Clustering

const clusters = await clusterPrompts(prompts, { embeddingCache });
const candidates = rankClusterCandidates(clusters, { totalSessions: 100 });

See Also

API Reference for gsd-skill-creator