Documentation > Architecture > System Layers
Module Architecture
The gsd-skill-creator codebase contains 50+ subsystems organized in src/. The codebase follows a strict dependency hierarchy where modules only depend on layers below them. This page documents every layer with real TypeScript interfaces from the source code.
Layer 1: Foundation
types/ — Type Definitions
Path: src/types/
Depends On: Nothing
Used By: Every other module
Defines all TypeScript interfaces, types, and constants. Key files: skill.ts, pattern.ts, scope.ts, application.ts, learning.ts, detection.ts, observation.ts, conflicts.ts, embeddings.ts, simulation.ts, testing.ts, activation.ts, agent.ts, team.ts, extensions.ts.
// src/types/skill.ts
export interface SkillMetadata {
name: string; // max 64 chars, lowercase + hyphens only
description: string; // max 1024 chars, used for auto-triggering
'disable-model-invocation'?: boolean; // Prevent Claude from auto-loading
'user-invocable'?: boolean; // Allow /skill-name invocation
'allowed-tools'?: string[] | string; // Restrict available tools
'argument-hint'?: string; // Hint for user invocation arguments
model?: string; // Model override (sonnet, opus, haiku, inherit)
context?: 'fork'; // Fork context for isolated execution
agent?: string; // Agent reference for skill
hooks?: Record<string, unknown>; // Lifecycle hooks configuration
license?: string; // SPDX license identifier
compatibility?: string; // Compatibility notes (max 500 chars)
metadata?: {
extensions?: {
'gsd-skill-creator'?: GsdSkillCreatorExtension;
[key: string]: unknown; // Preserve unknown extensions
};
};
}
export interface Skill {
metadata: SkillMetadata;
body: string; // Markdown content
path: string; // File path for reference
}
export interface SkillTrigger {
intents?: string[]; // Match user intent patterns
files?: string[]; // Match file patterns (glob)
contexts?: string[]; // Match context patterns
threshold?: number; // Minimum confidence (0-1)
}
export interface SkillLearning {
applicationCount?: number;
feedbackScores?: number[];
corrections?: SkillCorrection[];
lastRefined?: string;
}
export const OFFICIAL_NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
export function validateSkillName(name: string): boolean;
Also in this layer: identifiers/, portability/, events/, roles/, capabilities/.
Layer 2: Infrastructure
storage/ — CRUD Operations
Path: src/storage/
Depends On: types/, validation/
Key Exports: SkillStore, SkillIndex, PatternStore
// src/storage/skill-store.ts
export class SkillStore {
constructor(private skillsDir: string = '.claude/skills') {}
async create(skillName: string, metadata: SkillMetadata, body: string): Promise<Skill>
async createWithDisclosure(skillName: string, metadata: SkillMetadata, body: string): Promise<Skill>
async read(skillName: string): Promise<Skill>
async update(skillName: string, updates: Partial<SkillMetadata>, newBody?: string): Promise<Skill>
async delete(skillName: string): Promise<void>
async list(): Promise<string[]>
async exists(skillName: string): Promise<boolean>
async listWithFormat(): Promise<{ name: string; format: 'current' | 'legacy'; path: string }[]>
}
// src/storage/skill-index.ts
export interface SkillIndexEntry {
name: string;
description: string;
enabled: boolean;
triggers?: { intents?: string[]; files?: string[]; contexts?: string[] };
events?: { emits?: string[]; listens?: string[] };
path: string;
mtime: number;
}
export class SkillIndex {
async findByTrigger(intent?: string, file?: string, context?: string): Promise<SkillIndexEntry[]>
async rebuild(): Promise<void>
}
validation/ — 17 Validators
Path: src/validation/
Depends On: types/
Key Exports: SkillInputSchema, BudgetValidator, PathTraversalError
The validation layer contains 17 validator modules covering four categories:
| Category | Modules | Purpose |
|---|---|---|
| Safety | path-safety, yaml-safety, generation-safety, message-safety, jsonl-safety |
Prevent traversal, injection, dangerous commands |
| Budget | budget-validation, loading-projection, description-quality |
Enforce context window limits and quality |
| Schema | skill-validation, directory-validation, reserved-names, test-validation, backward-compat |
Validate structure, names, formats |
| Specialized | agent-validation, team-validation, openstack-validation, arguments-validation, context-fork-detection |
Domain-specific checks |
// src/validation/path-safety.ts
export class PathTraversalError extends Error {
override name = 'PathTraversalError' as const;
}
export function validateSafeName(name: string): SafeNameResult;
export function assertSafePath(resolvedPath: string, baseDir: string): void;
// src/validation/budget-validation.ts
export type BudgetSeverity = 'ok' | 'info' | 'warning' | 'error';
export class BudgetValidator {
static load(): BudgetValidator;
checkSingleSkill(charCount: number): BudgetCheckResult;
}
// src/validation/generation-safety.ts
export function scanForDangerousCommands(content: string): DangerousFinding[];
export function sanitizeGeneratedContent(body: string): { sanitized: string; findings: DangerousFinding[] };
export function inferAllowedTools(candidate: { type: string; pattern: string }): string[];
embeddings/ — Semantic Analysis
Path: src/embeddings/
Depends On: types/
Key Exports: EmbeddingService, EmbeddingCache, HeuristicEmbedder, cosineSimilarity()
Three-tier embedding strategy: cache lookup, HuggingFace BGE-small model, TF-IDF heuristic fallback.
testing/ — Test Infrastructure
Path: src/testing/
Depends On: types/, storage/
Key Exports: TestStore, ResultStore, TestRunner, ResultFormatter
safety/ — Security Subsystem
Path: src/safety/
Depends On: types/, validation/
Defense-in-depth security layer coordinating path safety, YAML safety, and generation safety.
disclosure/ — Progressive Disclosure
Path: src/disclosure/
Depends On: types/
Key Exports: ContentDecomposer, ReferenceLinker, CircularReferenceError
Decomposes large skills (>2000 words) into compact SKILL.md plus references/ and scripts/ subdirectories.
Layer 3: Analysis
observation/ — Session Observation
Path: src/observation/
Depends On: types/, storage/
Key Exports: SessionObserver, TranscriptParser, PatternSummarizer, PromotionEvaluator, ObservationSquasher
// src/observation/session-observer.ts
export interface SessionStartData {
sessionId: string;
transcriptPath: string;
cwd: string;
source: 'startup' | 'resume' | 'clear' | 'compact';
model: string;
startTime: number;
}
export interface SessionEndData {
sessionId: string;
transcriptPath: string;
cwd: string;
reason: 'clear' | 'logout' | 'prompt_input_exit' | 'bypass_permissions_disabled' | 'other';
activeSkills?: string[];
}
export class SessionObserver {
constructor(patternsDir?: string, retentionConfig?: Partial<RetentionConfig>, rateLimitConfig?: Partial<RateLimitConfig>);
async onSessionStart(data: SessionStartData): Promise<void>;
async onSessionEnd(data: SessionEndData): Promise<SessionObservation | null>;
}
Also includes: EphemeralStore, RetentionManager, ObservationRateLimiter, DeterminismAnalyzer, DriftMonitor, ExecutionCapture, FeedbackBridge, LineageTracker, PromotionDetector, PromotionGatekeeper, ScriptGenerator, JsonlCompactor.
detection/ — Pattern Detection
Path: src/detection/
Depends On: types/, storage/
Key Exports: PatternAnalyzer, SkillGenerator, SuggestionManager, SuggestionStore
// src/detection/pattern-analyzer.ts
export class PatternAnalyzer {
constructor(config?: Partial<DetectionConfig>);
async analyze(sessionsPath: string): Promise<SkillCandidate[]>;
analyzeFromSessions(sessions: SessionObservation[]): SkillCandidate[];
}
// src/detection/skill-generator.ts
export interface GeneratedSkill {
name: string;
metadata: SkillMetadata;
body: string;
references?: ReferenceFile[];
scripts?: ScriptFile[];
}
export class SkillGenerator {
constructor(private skillStore: SkillStore, private gsdInstalled?: boolean);
generateScaffold(candidate: SkillCandidate): GeneratedSkill;
async createFromCandidate(candidate: SkillCandidate): Promise<string>;
}
composition/ — Skill Inheritance
Path: src/composition/
Depends On: types/, storage/
Key Exports: SkillResolver, DependencyGraph, InheritanceValidator, GraphRenderer
// src/composition/skill-resolver.ts
export interface SkillResolution {
resolvedContent: string; // Merged body (parent + child)
resolvedMetadata: SkillMetadata; // Merged frontmatter
inheritanceChain: string[]; // [grandparent, parent, child]
}
export class SkillResolver {
constructor(private skillStore: SkillStore);
async resolve(skillName: string): Promise<SkillResolution>;
}
// src/composition/dependency-graph.ts
export interface DependencyResult {
hasCycle: boolean;
cycle?: string[];
topologicalOrder?: string[];
}
export class DependencyGraph {
addEdge(child: string, parent: string): void;
addNode(name: string): void;
static fromSkills(skills: Map<string, SkillMetadata>): DependencyGraph;
detectCycles(): DependencyResult; // Kahn's algorithm, O(n+m)
getInheritanceChain(skillName: string): string[];
getDependents(skillName: string): string[];
getAllDependents(skillName: string): string[];
getDepth(skillName: string): number;
}
agents/ — Agent Composition
Path: src/agents/
Depends On: types/, storage/, validation/
Key Exports: AgentGenerator, CoActivationTracker, ClusterDetector, AgentSuggestionManager
// src/agents/agent-generator.ts
export interface GeneratedAgent {
name: string;
description: string;
skills: string[];
filePath: string;
content: string;
warning?: string;
}
export class AgentGenerator {
constructor(skillStore: SkillStore, config?: Partial<AgentGeneratorConfig>);
async generateContent(cluster: SkillCluster): Promise<GeneratedAgent>;
async create(cluster: SkillCluster): Promise<GeneratedAgent>;
}
// src/agents/co-activation-tracker.ts
export interface SkillCoActivation {
skillPair: [string, string]; // Alphabetically sorted
coActivationCount: number;
sessions: string[];
firstSeen: number;
lastSeen: number;
}
export class CoActivationTracker {
constructor(config?: Partial<CoActivationConfig>);
analyze(sessions: SessionObservation[]): SkillCoActivation[];
getCoActivationScore(skillA: string, skillB: string, sessions: SessionObservation[]): number;
getRelatedSkills(skillName: string, sessions: SessionObservation[]): Array<{ skill: string; count: number }>;
}
teams/ — Multi-Agent Teams
Path: src/teams/
Depends On: types/, storage/, agents/, validation/
Key Exports: Template generators for 5 topologies, TeamStore, TeamValidator, TeamWizard, TeamAgentGenerator
Five supported team topologies:
| Topology | Generator | Pattern |
|---|---|---|
| Leader-Worker | generateLeaderWorkerTemplate() |
One coordinator delegates to workers |
| Pipeline | generatePipelineTemplate() |
Sequential stage-by-stage processing |
| Swarm | generateSwarmTemplate() |
Self-organizing parallel execution |
| Router | generateRouterTemplate() |
Intent-based routing to specialists |
| Map-Reduce | generateMapReduceTemplate() |
Parallel map then aggregate reduce |
Validation includes: schema validation, topology constraints, agent resolution, cycle detection, tool overlap detection, skill conflict detection, and role coherence checks.
Additional Analysis Modules
| Module | Path | Purpose |
|---|---|---|
activation/ |
src/activation/ |
Score activation likelihood, suggest improvements |
conflicts/ |
src/conflicts/ |
Detect semantic overlaps, suggest rewrites |
discovery/ |
src/discovery/ |
DBSCAN clustering with cosine distance, k-NN knee detection |
brainstorm/ |
src/brainstorm/ |
8-agent structured ideation system |
retrieval/ |
src/retrieval/ |
Adaptive routing between TF-IDF and embedding search |
evaluator/ |
src/evaluator/ |
Skill quality evaluation and scoring |
Layer 4: Core Processing
application/ — 6-Stage Pipeline
Path: src/application/
Depends On: types/, storage/, embeddings/, composition/
Key Exports: SkillPipeline, SkillApplicator, SkillSession, TokenCounter, BudgetProfiles
// src/application/skill-pipeline.ts
export interface PipelineContext {
readonly intent?: string;
readonly file?: string;
readonly context?: string;
matches: SkillIndexEntry[];
scoredSkills: ScoredSkill[];
resolvedSkills: ScoredSkill[];
conflicts: ConflictResult;
loaded: string[];
skipped: string[];
budgetSkipped: SkippedSkill[];
budgetWarnings: BudgetWarning[];
contentCache: Map<string, string>;
readonly modelProfile?: string; // 'quality' | 'balanced' | 'budget'
earlyExit: boolean;
getReport: () => SessionReport;
}
// Pipeline stages in src/application/stages/
// score-stage.ts → TF-IDF + embedding scoring with AdaptiveRouter
// resolve-stage.ts → Inheritance resolution via SkillResolver
// model-filter-stage.ts → Model-aware activation filtering
// cache-order-stage.ts → Cache hit optimization
// budget-stage.ts → Tiered budget enforcement (critical/standard/optional)
// load-stage.ts → Context injection
simulation/ — Activation Simulation
Path: src/simulation/
Depends On: types/, embeddings/, storage/
Predict which skill would activate for a given prompt without invoking Claude.
learning/ — Bounded Refinement
Path: src/learning/
Depends On: types/, storage/
Key Exports: RefinementEngine, FeedbackDetector, FeedbackStore, VersionManager, ContradictionDetector, DriftTracker
// src/learning/refinement-engine.ts
export class RefinementEngine {
constructor(
feedbackStore: FeedbackStore,
skillStore: SkillStore,
config?: Partial<BoundedLearningConfig>,
driftTracker?: DriftTracker
);
async checkEligibility(skillName: string): Promise<EligibilityResult>;
async generateSuggestion(skillName: string): Promise<RefinementSuggestion | null>;
validateChange(original: string, suggested: string): ValidationResult;
async applyRefinement(skillName: string, suggestion: RefinementSuggestion, userConfirmed: boolean): Promise<ApplyResult>;
}
// Bounded learning guardrails (non-negotiable):
// - Maximum 20% content change per refinement
// - Minimum 3 corrections before a refinement is proposed
// - 7-day cooldown between refinements
// - All refinements require user confirmation
// - Cumulative drift tracking prevents unbounded evolution
calibration/ — Threshold Optimization
Path: src/calibration/
Depends On: types/, storage/, embeddings/
Optimize activation thresholds based on real usage data. Requires minimum 75 events for reliable F1 calculation.
Layer 5: Orchestration
workflows/ & skill-workflows/
Path: src/workflows/, src/skill-workflows/
Depends On: All lower layers
Orchestrate multi-step operations combining storage, validation, user interaction, and the application pipeline.
orchestrator/
Path: src/orchestrator/
Depends On: workflows/, types/
Discovery, state management, intent classification, lifecycle coordination.
initialization/
Path: src/initialization/
Depends On: storage/, types/
Project and user environment initialization, migration, and bootstrap.
Layer 6: Entry Points
cli/ — Command-Line Interface
Path: src/cli/
Depends On: All lower layers
Thin layer exposing all functionality through CLI commands.
hooks/ — Session Lifecycle
Path: src/hooks/
Depends On: observation/, storage/
Integrate with Claude Code session lifecycle for passive data collection.
mcp/ — Model Context Protocol
Path: src/mcp/
Depends On: types/, storage/
Gateway and bridge for MCP integration.
Additional Entry Points
| Module | Path | Purpose |
|---|---|---|
launcher/ |
src/launcher/ |
System startup and process management |
terminal/ |
src/terminal/ |
Terminal UI rendering |
console/ |
src/console/ |
Console output formatting |
dashboard/ |
src/dashboard/ |
Web dashboard for skill management |
Dependency Matrix Summary
| Layer | Module Count | Can Depend On |
|---|---|---|
| L1: Foundation | 6 | Nothing |
| L2: Infrastructure | 6 | L1 |
| L3: Analysis | 12+ | L1, L2 |
| L4: Core Processing | 4 | L1, L2, L3 |
| L5: Orchestration | 4 | L1–L4 |
| L6: Entry Points | 6+ | All |

