/** * Core types for skill-tree * @packageDocumentation */ /** * Core skill representation combining OpenSkills format with versioning */ interface Skill { /** Unique identifier (kebab-case) */ id: string; /** Human-readable name */ name: string; /** Semantic version (e.g., "1.0.0") */ version: string; /** Short description optimized for semantic matching (1-2 sentences) */ description: string; /** Free-form markdown instructions (the SKILL.md body) */ instructions: string; /** Related skill IDs */ related?: string[]; author: string; tags: string[]; createdAt: Date; updatedAt: Date; /** Status in the skill lifecycle */ status: SkillStatus; /** Previous version this was derived from */ parentVersion?: string; /** Skills this was composed from */ derivedFrom?: string[]; /** Skills forked from this one (source → child tracking) */ forks?: string[]; /** Upstream tracking for skills imported with 'link' mode */ upstream?: SkillUpstream; source?: SkillSource$1; /** Taxonomy classification (from skill indexer) */ taxonomy?: SkillTaxonomy; /** External source information (for imported skills) */ externalSource?: ExternalSource; /** Relationships to other skills */ relationships?: SkillRelationship[]; /** Namespace and scope information for multi-tier skill trees */ namespace?: SkillNamespace; /** Serving-specific configuration for loadout/expansion behavior */ serving?: SkillServingMetadata; } /** * Serving-specific metadata for a skill */ interface SkillServingMetadata { /** Short summary for collapsed view (defaults to description) */ summary?: string; /** Estimated token count for context budgeting */ tokenEstimate?: number; /** Auto-expand triggers */ autoExpand?: ExpandTriggerConfig[]; /** Group ID for batch expansion */ expansionGroup?: string; } /** * Trigger conditions for auto-expanding a skill */ interface ExpandTriggerConfig { /** What event triggers expansion */ on: 'use' | 'mention' | 'error-match' | 'file-match' | 'explicit'; /** Optional conditions for the trigger */ conditions?: { /** Keywords that trigger expansion */ keywords?: string[]; /** Error patterns that trigger expansion */ errorPatterns?: string[]; /** File patterns that trigger expansion */ filePatterns?: string[]; }; } type SkillStatus = 'draft' | 'active' | 'deprecated' | 'experimental'; interface SkillSource$1 { /** Where the skill came from */ type: 'extracted' | 'manual' | 'imported' | 'composed'; /** Original source location (git URL, local path, etc.) */ location?: string; /** For extracted skills: the session it came from */ sessionId?: string; /** Timestamp of import/extraction */ importedAt: Date; /** Agent that created/extracted this skill */ agentId?: string; /** Human-readable agent name */ agentName?: string; } /** * Upstream tracking for skills imported from a remote with 'link' mode. * Enables checking for updates and pulling changes from the source. */ interface SkillUpstream { /** Name of the remote this skill was imported from */ remote: string; /** Original skill ID in the remote repository */ skillId: string; /** Version of the skill when last synced */ version: string; /** When the skill was last synced with upstream */ syncedAt: Date; } /** * Taxonomy classification for indexed skills */ interface SkillTaxonomy { /** Primary taxonomy path (e.g., ["Development", "Python", "Testing"]) */ primaryPath: string[]; /** Secondary taxonomy placements */ secondaryPaths?: string[][]; /** Classification confidence (0-1) */ confidence?: number; } /** * External source information for imported skills */ interface ExternalSource { /** Source URL */ url: string; /** Source repository */ repo: string; /** When the skill was scraped */ scrapedAt: Date; /** ETag for change detection */ etag?: string; } /** * Relationship between skills */ interface SkillRelationship { /** Target skill ID */ targetSkillId: string; /** Relationship type */ type: 'depends_on' | 'extends' | 'alternative' | 'related'; /** Confidence score (0-1) */ confidence: number; /** Reasoning for the relationship */ reasoning?: string; } /** * Scope level for a skill * - personal: Private to a single agent * - team: Shared within a team/organization * - global: Shared across all teams (public) */ type SkillScope = 'personal' | 'team' | 'global'; /** * Visibility level for skills * - private: Only owner can see * - team-only: Only team members can see * - public: Everyone can see */ type SkillVisibility = 'private' | 'team-only' | 'public'; /** * Namespace configuration for scoped skills */ interface SkillNamespace { /** Scope level (personal, team, global) */ scope: SkillScope; /** Owner identifier (agent ID for personal, team name for team) */ owner: string; /** Team name (for team-scoped skills) */ team?: string; /** Visibility setting */ visibility: SkillVisibility; /** Whether this skill can be promoted to a higher scope */ promotable?: boolean; /** If promoted from a personal skill, the original ID */ promotedFrom?: { originalId: string; originalOwner: string; promotedAt: Date; }; } /** * Access control for fine-grained permissions */ interface SkillAccessControl { /** Agent IDs that can read this skill */ canRead: string[]; /** Agent IDs that can modify this skill */ canWrite: string[]; /** Agent IDs that can delete this skill */ canDelete: string[]; } interface SkillVersion { /** Skill ID this version belongs to */ skillId: string; /** Version string (semver) */ version: string; /** Full skill snapshot at this version */ skill: Skill; /** What changed in this version */ changelog: string; /** When this version was created */ createdAt: Date; /** Hash of skill content for integrity checks */ contentHash: string; } interface SkillLineage { /** Root skill ID */ rootId: string; /** Version history in chronological order */ versions: SkillVersion[]; /** Branches/forks from this skill */ forks: SkillFork[]; } interface SkillFork { /** New skill ID that forked */ forkedSkillId: string; /** Version it forked from */ fromVersion: string; /** Reason for forking */ reason: string; /** When the fork happened */ forkedAt: Date; } interface StorageAdapter { /** Initialize the storage */ initialize(): Promise; saveSkill(skill: Skill): Promise; getSkill(id: string, version?: string): Promise; listSkills(filter?: SkillFilter): Promise; deleteSkill(id: string, version?: string): Promise; getVersionHistory(skillId: string): Promise; getLineage(skillId: string): Promise; searchSkills(query: string): Promise; /** Place a skill in the taxonomy tree */ placeInTaxonomy?(skillId: string, taxonomy: SkillTaxonomy): Promise; /** Get sync states for all remotes */ getSyncStates?(): Promise>; /** Save sync state for a remote */ saveSyncState?(state: { remote: string; syncedAt: Date; commitHash?: string; }): Promise; /** Record a fork relationship on the source skill's lineage */ recordFork?(sourceSkillId: string, fork: SkillFork): Promise; } interface SkillFilter { status?: SkillStatus[]; tags?: string[]; author?: string; createdAfter?: Date; createdBefore?: Date; /** Filter by scope */ scope?: SkillScope | SkillScope[]; /** Filter by owner (agent ID or team name) */ owner?: string; /** Filter by team */ team?: string; /** Filter by visibility */ visibility?: SkillVisibility | SkillVisibility[]; /** Filter to skills accessible by this agent ID */ accessibleBy?: string; /** The team of the agent specified in accessibleBy (for team-only visibility checks) */ accessibleByTeam?: string; } interface StorageConfig { /** Base path for skill storage */ basePath?: string; /** Whether to use OpenSkills-compatible format */ openSkillsCompatible?: boolean; } type SkillTreeEvent = { type: 'skill:created'; skill: Skill; } | { type: 'skill:updated'; skill: Skill; previousVersion: string; } | { type: 'skill:deprecated'; skillId: string; } | { type: 'skill:deleted'; skillId: string; }; type SkillTreeEventHandler = (event: SkillTreeEvent) => void | Promise; /** * Configuration for materializing skills to agent-discoverable locations */ interface MaterializationConfig { /** Enable automatic materialization on skill changes (default: false) */ enabled: boolean; /** Materialization mode: 'symlink' creates symlinks, 'copy' copies directories (default: 'symlink') */ mode?: 'symlink' | 'copy'; /** Additional directories to symlink/copy skill dirs into (e.g. ['.claude/skills', '.agent/skills']) */ symlinkPaths?: string[]; /** Path to write AGENTS.md (e.g. './AGENTS.md'). If set, auto-regenerates on changes */ agentsMdPath?: string; /** Format for AGENTS.md generation (default: 'xml') */ agentsMdFormat?: 'xml' | 'markdown' | 'json'; /** Debounce interval in ms for batch updates (default: 500) */ debounceMs?: number; } /** * Semantic versioning utilities */ /** * Parsed semantic version */ interface ParsedVersion { major: number; minor: number; patch: number; prerelease?: string; build?: string; } /** * Version bump type */ type BumpType = 'major' | 'minor' | 'patch' | 'prerelease'; /** * Parse a version string into components */ declare function parseVersion(version: string): ParsedVersion; /** * Format a parsed version back to string */ declare function formatVersion(parsed: ParsedVersion): string; /** * Check if a version string is valid semver */ declare function isValidVersion(version: string): boolean; /** * Compare two versions * Returns: -1 if a < b, 0 if a === b, 1 if a > b */ declare function compareVersions(a: string, b: string): -1 | 0 | 1; /** * Bump a version */ declare function bumpVersion(version: string, type: BumpType): string; /** * Check if version a satisfies version range b * Supports: exact, ^, ~, >=, >, <=, <, x ranges */ declare function satisfiesRange(version: string, range: string): boolean; /** * Get the latest version from a list */ declare function getLatestVersion(versions: string[]): string | null; /** * Sort versions in ascending order */ declare function sortVersions(versions: string[]): string[]; /** * Determine bump type based on changes */ declare function inferBumpType(changes: VersionChanges): BumpType; /** * Changes between versions */ interface VersionChanges { /** Breaking changes that require major bump */ breakingChanges?: string[]; /** New features that require minor bump */ newFeatures?: string[]; /** Bug fixes and patches */ bugFixes?: string[]; /** Other changes */ other?: string[]; } /** * Skill Merging System * Advanced merge capabilities with conflict detection, preview, and smart strategies */ /** * Strategy for handling merge conflicts */ type MergeStrategy = 'source' | 'target' | 'combine' | 'newest' | 'longest' | 'union' | 'intersection'; /** * Configuration for merging skills */ interface MergeConfig { /** Default strategy for text fields */ textStrategy?: MergeStrategy; /** Strategy for tags */ tagStrategy?: MergeStrategy; /** Fields to include in merge (defaults to all) */ includeFields?: (keyof Skill)[]; /** Fields to exclude from merge */ excludeFields?: (keyof Skill)[]; /** Version bump type (auto-inferred if not specified) */ bumpType?: BumpType; /** Changelog entry */ changelog?: string; } /** * A single merge conflict */ interface MergeConflict { /** Field with conflict */ field: keyof Skill; /** Value in target skill */ targetValue: unknown; /** Value in source skill */ sourceValue: unknown; /** Suggested resolution */ suggestion: 'source' | 'target' | 'combine'; /** Reason for suggestion */ reason: string; } /** * Resolution for a conflict */ interface ConflictResolution$1 { /** Field being resolved */ field: keyof Skill; /** Resolution strategy */ resolution: MergeStrategy | 'custom'; /** Custom value (when resolution is 'custom') */ customValue?: unknown; } /** * Preview of merge operation */ interface MergePreview { /** Target skill ID */ targetId: string; /** Source skill ID */ sourceId: string; /** Detected conflicts */ conflicts: MergeConflict[]; /** Fields that will be modified */ modifications: Array<{ field: keyof Skill; currentValue: unknown; newValue: unknown; strategy: MergeStrategy; }>; /** Resulting skill preview */ previewSkill: Partial; /** Suggested version */ suggestedVersion: string; /** Whether any conflicts need resolution */ hasConflicts: boolean; } /** * Result of merge operation */ interface MergeResult { /** Successfully merged skill */ skill: Skill; /** Conflicts that were resolved */ resolvedConflicts: MergeConflict[]; /** Strategy used for each field */ appliedStrategies: Map; /** Changelog generated */ changelog: string; } /** * Suggestion for merging similar skills */ interface MergeSuggestion { /** Source skill ID */ sourceId: string; /** Target skill ID */ targetId: string; /** Similarity score */ similarity: number; /** Reason for suggestion */ reason: string; /** Fields that could benefit from merge */ beneficialFields: (keyof Skill)[]; /** Potential conflicts */ potentialConflicts: string[]; } /** * Advanced skill merging with conflict detection and resolution */ declare class SkillMerger { private storage; private config; constructor(storage: StorageAdapter, config?: MergeConfig); /** * Preview a merge without applying it */ preview(targetId: string, sourceId: string, config?: MergeConfig): Promise; /** * Detect conflicts between two skills */ detectConflicts(target: Skill, source: Skill, config?: MergeConfig): MergeConflict[]; /** * Merge skills with optional conflict resolutions */ merge(targetId: string, sourceId: string, options?: { config?: MergeConfig; resolutions?: ConflictResolution$1[]; }): Promise; /** * Suggest skills that could benefit from merging */ suggestMerges(skills: Skill[], options?: { minSimilarity?: number; maxSuggestions?: number; }): Promise; /** * Update merge configuration */ setConfig(config: MergeConfig): void; private getFieldsToMerge; private valuesConflict; private suggestResolution; private buildModifications; private buildMergedSkill; private getStrategyForField; private mergeField; private mergeArrays; private mergeStrings; private calculateSimilarity; private buildMergeSuggestion; private calculateCompleteness; private generateChangelog; } /** * Create a skill merger instance */ declare function createSkillMerger(storage: StorageAdapter, config?: MergeConfig): SkillMerger; /** * Multi-Agent Sync Types * * Types for git-based skill synchronization across multiple agents */ /** * Configuration for multi-agent synchronization */ interface SyncConfig { /** Remote repository configuration */ remote: RemoteConfig; /** Agent identity */ agent: AgentConfig; /** Sync behavior settings */ sync: SyncBehaviorConfig; /** Conflict resolution settings */ conflicts: ConflictConfig; } /** * Remote repository configuration */ interface RemoteConfig { /** Remote type (git for now, http later) */ type: 'git'; /** Remote repository URL (e.g., git@github.com:org/skills.git) */ url: string; /** Branch to sync with (default: 'main') */ branch?: string; /** Path within repo where skills are stored (default: 'skills/') */ skillsPath?: string; } /** * Agent identity configuration */ interface AgentConfig { /** Unique agent identifier (slug format, e.g., 'claude-prod-1') */ id: string; /** Human-readable agent name */ name?: string; /** Environment this agent runs in */ environment?: string; } /** * Sync behavior configuration */ interface SyncBehaviorConfig { /** When to sync: manual, on-change, or periodic */ mode: 'manual' | 'on-change' | 'periodic'; /** Interval in milliseconds for periodic mode */ intervalMs?: number; /** How to handle push: immediate, batch, or manual */ pushStrategy: 'immediate' | 'batch' | 'manual'; /** How to handle pull: auto-merge, manual review, or preview first */ pullStrategy: 'auto-merge' | 'manual' | 'preview-first'; } /** * Conflict resolution configuration */ interface ConflictConfig { /** Default strategy for resolving conflicts */ defaultStrategy: ConflictStrategy; /** Field-specific strategies */ fieldStrategies?: Partial>; } /** * Strategies for resolving conflicts */ type ConflictStrategy = 'prefer-local' | 'prefer-remote' | 'prefer-newer' | 'union' | 'combine' | 'manual'; /** * Options for pull operation */ interface PullOptions { /** Only pull specific skills (default: all) */ skillIds?: string[]; /** Force overwrite local changes */ force?: boolean; /** Preview only, don't apply changes */ dryRun?: boolean; } /** * Options for push operation */ interface PushOptions { /** Only push specific skills (default: all modified) */ skillIds?: string[]; /** Custom commit message */ message?: string; /** Force push (dangerous, overwrites remote) */ force?: boolean; } /** * Result of a sync operation (pull or push) */ interface SyncResult$1 { /** Skills that were pulled from remote */ pulled: SkillChange[]; /** Skills that were pushed to remote */ pushed: SkillChange[]; /** Conflicts that need resolution */ conflicts: SkillConflict[]; /** Skills that were auto-merged successfully */ autoMerged: SkillMergeResult[]; /** Errors encountered during sync */ errors: SyncError[]; } /** * A single skill change */ interface SkillChange { /** Skill ID */ skillId: string; /** Type of change */ changeType: 'added' | 'modified' | 'deleted'; /** Previous version (for modifications) */ previousVersion?: string; /** New version */ newVersion?: string; /** The skill after the change */ skill?: Skill; } /** * Result of auto-merging a skill */ interface SkillMergeResult { /** Skill ID */ skillId: string; /** Merged skill */ mergedSkill: Skill; /** Fields that were auto-merged */ mergedFields: (keyof Skill)[]; /** Strategy used for each field */ strategies: Partial>; } /** * A sync error */ interface SyncError { /** Skill ID (if applicable) */ skillId?: string; /** Error message */ message: string; /** Error type */ type: 'network' | 'conflict' | 'permission' | 'parse' | 'unknown'; /** Original error */ cause?: Error; } /** * A skill conflict that needs resolution */ interface SkillConflict { /** Skill ID */ skillId: string; /** Local version of the skill */ localVersion: Skill; /** Remote version of the skill */ remoteVersion: Skill; /** Common ancestor version (for 3-way merge) */ baseVersion?: Skill; /** Fields with conflicts */ conflictingFields: (keyof Skill)[]; /** Detailed field-level conflicts (from SkillMerger) */ fieldConflicts: MergeConflict[]; /** Suggested merged result (if auto-merge partially succeeded) */ suggestedResolution?: Skill; /** Confidence in the suggested resolution (0-1) */ confidence: number; /** When the conflict was detected */ detectedAt: Date; } /** * Resolution for a conflict */ interface ConflictResolution { /** Resolution strategy */ strategy: 'accept-local' | 'accept-remote' | 'accept-merged' | 'custom'; /** Custom merged skill (for 'custom' strategy) */ customSkill?: Skill; /** Field-level overrides */ fieldOverrides?: Partial>; } /** * Current sync status */ interface SyncStatus { /** Whether sync is configured */ configured: boolean; /** Whether we're connected to remote */ connected: boolean; /** Last sync timestamp */ lastSync?: Date; /** Local commits ahead of remote */ localAhead: number; /** Remote commits ahead of local */ remoteBehind: number; /** Number of pending conflicts */ pendingConflicts: number; /** Skills modified locally since last sync */ modifiedSkills: string[]; /** Skills ready to push */ stagedSkills: string[]; /** Current branch */ branch: string; /** Remote URL */ remoteUrl: string; } /** * Result of fetch operation (preview of what would change) */ interface FetchResult { /** Local commits not on remote */ ahead: number; /** Remote commits not local */ behind: number; /** Skills changed on remote */ changedSkills: string[]; /** New skills on remote */ newSkills: string[]; /** Skills deleted on remote */ deletedSkills: string[]; } /** * Persisted sync state */ interface SyncState { /** Last synced commit hash */ lastSyncCommit: string; /** Last sync timestamp */ lastSyncTime: Date; /** Agent info at last sync */ agent: AgentConfig; /** Per-skill sync state */ skills: Record; } /** * Per-skill sync state */ interface SkillSyncState { /** Content hash at last sync */ localHash: string; /** When this skill was last synced */ syncedAt: Date; /** Version at last sync */ syncedVersion: string; } /** * Types for the hooks system * * Session lifecycle tracking belongs to sessionlog. * Skill runtime hooks (matched/applied/feedback) belong to cognitive-core. * skill-tree hooks cover storage and CRUD lifecycle only. */ /** * Events that can trigger hooks */ type HookEvent = 'storage:before-save' | 'storage:after-save' | 'storage:before-delete' | 'storage:after-delete' | 'skill:created' | 'skill:updated' | 'skill:deprecated' | 'skill:deleted'; /** * Priority levels for hook execution */ type HookPriority = 'high' | 'normal' | 'low'; /** * Base context shared by all hooks */ interface BaseHookContext { /** Unique ID for this hook invocation */ invocationId: string; /** Timestamp when the hook was triggered */ timestamp: Date; /** Additional metadata */ metadata?: Record; } /** * Context for storage hooks */ interface StorageHookContext extends BaseHookContext { event: 'storage:before-save' | 'storage:after-save' | 'storage:before-delete' | 'storage:after-delete'; skill: Skill; /** Operation type */ operation: 'save' | 'delete'; /** Whether the operation was successful */ success?: boolean; } /** * Context for skill CRUD hooks (create/update/deprecate/delete) */ interface SkillCrudHookContext extends BaseHookContext { event: 'skill:created' | 'skill:updated' | 'skill:deprecated' | 'skill:deleted'; skill: Skill; /** Previous version (on skill:updated) */ previousVersion?: string; /** Deprecation reason (on skill:deprecated) */ deprecationReason?: string; } /** * Union of all hook contexts */ type HookContext = StorageHookContext | SkillCrudHookContext; /** * Result from a hook handler */ interface HookResult { /** Whether to continue processing (false to abort) */ continue: boolean; /** Modified data (for before hooks that can transform data) */ modified?: unknown; /** Message explaining the result */ message?: string; /** Error if the hook failed */ error?: Error; } /** * Hook handler function */ type HookHandler = (context: T) => Promise | HookResult; /** * Registered hook definition */ interface RegisteredHook { /** Unique hook ID */ id: string; /** Hook name for display */ name: string; /** Events this hook listens to */ events: HookEvent[]; /** Handler function */ handler: HookHandler; /** Execution priority */ priority: HookPriority; /** Whether the hook is enabled */ enabled: boolean; /** Optional filter to control when hook runs */ filter?: (context: HookContext) => boolean; } /** * Hook Registry for managing and executing hooks */ /** * Options for registering a hook */ interface RegisterHookOptions { /** Hook name for display */ name: string; /** Events to listen for */ events: HookEvent | HookEvent[]; /** Handler function */ handler: HookHandler; /** Execution priority (default: 'normal') */ priority?: HookPriority; /** Whether the hook is enabled (default: true) */ enabled?: boolean; /** Optional filter function */ filter?: (context: HookContext) => boolean; } /** * Result of executing hooks for an event */ interface HookExecutionResult { /** Event that was triggered */ event: HookEvent; /** Number of hooks executed */ executedCount: number; /** Number of hooks that passed */ passedCount: number; /** Whether all hooks passed */ allPassed: boolean; /** Whether execution was aborted */ aborted: boolean; /** Results from each hook */ results: Array<{ hookId: string; hookName: string; result: HookResult; duration: number; }>; /** Total execution time (ms) */ totalDuration: number; } /** * Registry for managing hooks */ declare class HookRegistry { private hooks; private eventIndex; /** * Register a new hook */ register(options: RegisterHookOptions): string; /** * Unregister a hook */ unregister(hookId: string): boolean; /** * Enable a hook */ enable(hookId: string): boolean; /** * Disable a hook */ disable(hookId: string): boolean; /** * Get a hook by ID */ get(hookId: string): RegisteredHook | undefined; /** * List all registered hooks */ list(): RegisteredHook[]; /** * List hooks for a specific event */ listForEvent(event: HookEvent): RegisteredHook[]; /** * Execute hooks for an event */ execute(event: HookEvent, context: Omit): Promise; /** * Execute hooks and allow modification of data (for 'before' hooks) */ executeWithTransform(event: HookEvent, context: Omit, data: T): Promise<{ result: HookExecutionResult; data: T; }>; /** * Clear all hooks */ clear(): void; /** * Get statistics about registered hooks */ stats(): { totalHooks: number; enabledHooks: number; hooksByEvent: Record; hooksByPriority: Record; }; } /** * Global hook registry instance */ declare const hookRegistry: HookRegistry; /** * SyncManager - Orchestrates sync within SkillBank * * Bridges GitSyncAdapter with SkillBank's hook system to enable * automatic change tracking and configurable push/pull behavior. */ /** * Options for creating a SyncManager */ interface SyncManagerOptions { /** Path to the git repository (same as filesystem storage basePath) */ repoPath: string; /** Full sync configuration */ config: SyncConfig; /** Hook registry for listening to storage events */ hookRegistry: HookRegistry; } /** * Orchestrates git-based sync within SkillBank. * * Listens to storage hooks to track local changes and manages * push behavior based on the configured sync mode. */ declare class SyncManager { private adapter; private hookRegistry; private config; private periodicTimer?; private pendingChanges; private hookIds; private initialized; private pushDebounceTimer?; private readonly DEBOUNCE_MS; constructor(options: SyncManagerOptions); /** * Initialize the sync adapter and register hooks. */ initialize(): Promise; /** * Shutdown: clear timers and unregister hooks. */ shutdown(): Promise; /** * Fetch remote changes without applying them. */ fetch(): Promise; /** * Pull remote changes and merge into local storage. */ pull(options?: PullOptions): Promise; /** * Push local changes to the remote. */ push(options?: PushOptions): Promise; /** * Get current sync status. */ status(): Promise; /** * List pending merge conflicts. */ listConflicts(): Promise; /** * Resolve a merge conflict for a specific skill. */ resolveConflict(skillId: string, resolution: ConflictResolution): Promise; /** * Get the set of skill IDs modified since the last push. */ getPendingChanges(): ReadonlySet; private ensureInitialized; private registerHooks; private trackChange; private debouncedPush; private pushIfPending; } /** * Factory function for creating a SyncManager. */ declare function createSyncManager(options: SyncManagerOptions): SyncManager; /** * Types for the skill-tree serving layer * @packageDocumentation */ type ExpandTrigger = ExpandTriggerConfig; /** * Visibility/loading state of a skill in the loadout */ type SkillState = 'available' | 'expanded' | 'pending'; /** * Flexible criteria for selecting skills into a loadout */ interface LoadoutCriteria { /** * Always include these skill IDs in the result, regardless of other * filters (status, tags, author, relationships, etc.). Missing skills * are fetched from storage on demand. The list is treated as a SET + * order hint — included skills come first in the order they appear * here, then the rest of the filtered set. * * `exclude` wins over `include`: IDs listed in both are excluded. * * For "restrict to exactly these N skills" semantics, combine * `include: [...]` with `maxSkills: include.length`. */ include?: string[]; /** * Drop these skill IDs from the result. Wins over `include` — * an ID in both lists is excluded. */ exclude?: string[]; /** Match any of these tags */ tags?: string[]; /** Must have ALL these tags */ tagsAll?: string[]; /** Filter by status (default: ['active']) */ status?: SkillStatus[]; /** Filter by author */ author?: string; /** Semantic match to task description */ taskDescription?: string; /** Current problem being solved */ problemContext?: string; /** Error message to match */ errorContext?: string; /** Keyword triggers */ keywords?: string[]; /** Project type (e.g., "python", "typescript", "rust") */ projectType?: string; /** Glob patterns of files in scope */ filePatterns?: string[]; /** Detected frameworks */ frameworks?: string[]; /** Start with these skills, traverse relationships */ rootSkills?: string[]; /** Follow 'depends_on' edges */ includeDependencies?: boolean; /** Include 'related' skills */ includeRelated?: boolean; /** Max traversal depth (default: 2) */ depth?: number; /** Cap on loadout size */ maxSkills?: number; /** Context budget (estimated tokens) */ maxTokens?: number; /** * How to order results for selection. Currently only `'relevance'` is * recognized; it's a no-op until skill-tree gains semantic ranking. Live * usage-based ranking (formerly `'usage'` / `'successRate'` / `'recent'`) * is now the caller's responsibility — pre-rank and pass IDs via * `include: [...]`. See README "Metrics ownership" for the rationale. */ priorityOrder?: 'relevance'; /** How to apply to current state */ mode?: 'replace' | 'merge' | 'subtract'; } /** * How a loadout was created */ interface LoadoutSource { /** Source type */ type: 'criteria' | 'profile' | 'task' | 'project' | 'manual'; /** Criteria used (if type is 'criteria') */ criteria?: LoadoutCriteria; /** Profile name (if type is 'profile') */ profileName?: string; /** Task description (if type is 'task') */ taskDescription?: string; /** Project path (if type is 'project') */ projectPath?: string; } /** * Current state of what's loaded for an agent */ interface LoadoutState { /** Skills available to the agent (summaries visible) */ available: Map; /** Skills with full content expanded */ expanded: Set; /** Skills requested by agent, pending orchestrator approval */ pending: Set; /** How this loadout was created */ source: LoadoutSource; /** When the loadout was last modified */ updatedAt: Date; } /** * Summary of a skill for display in loadout views */ interface SkillSummary { /** Skill ID */ id: string; /** Human-readable name */ name: string; /** Short description */ description: string; /** Whether the skill is currently expanded */ expanded: boolean; /** Skill tags */ tags: string[]; } /** * View of the current loadout for agents */ interface LoadoutView { /** Available skills as summaries */ available: SkillSummary[]; /** Pending skill request IDs */ pending: string[]; /** Available profile names */ profiles: string[]; } /** * Detected project context for auto-configuration */ interface ProjectContext { /** Primary project type (e.g., "typescript", "python") */ type: string; /** Detected frameworks */ frameworks: string[]; /** File patterns found */ patterns: string[]; /** Package manager (e.g., "npm", "pip") */ packageManager?: string; } /** * Configuration for LoadoutCompiler */ interface LoadoutCompilerConfig { /** Default max skills when not specified (default: 15) */ defaultMaxSkills?: number; /** Default status filter (default: ['active']) */ defaultStatus?: SkillStatus[]; /** Minimum similarity threshold for semantic matching (default: 0.6) */ semanticThreshold?: number; } /** * Configuration for CatalogRenderer (browsable skill catalog) */ interface CatalogRendererConfig { /** Max categories to show at each level (default: 12) */ maxCategoriesPerLevel: number; /** Max skills to list at leaf nodes (default: 8) */ maxSkillsAtLeaf: number; /** Max summary length for leaf-level skill descriptions (default: 80) */ maxSummaryLength: number; } /** * Eviction strategy when maxExpanded is reached */ type EvictionStrategy = 'lru' | 'priority' | 'manual'; /** * Configuration for SkillGraphServer */ interface GraphServerConfig { /** Initial loadout criteria (optional) */ initialLoadout?: LoadoutCriteria; /** Whether agent can modify loadout (default: true) */ agentCanModify?: boolean; /** Whether agent can replace entire loadout (default: false) */ agentCanSetLoadout?: boolean; /** Whether agent can switch profiles (default: true) */ agentCanSwitchProfile?: boolean; /** Whether agent additions need approval (default: false) */ requireApproval?: boolean; /** Auto-expand skills on first use (default: true) */ autoExpandOnUse?: boolean; /** Auto-expand related skills when one expands (default: true) */ autoExpandRelated?: boolean; /** Max skills in expanded state (default: 5) */ maxExpanded?: number; /** Eviction strategy when maxExpanded reached */ evictionStrategy?: EvictionStrategy; /** Available loadout profiles */ profiles?: Record; /** Default profile to use */ defaultProfile?: string; /** Persist state across sessions (default: false) */ persistState?: boolean; /** Output format for system prompt (default: 'xml') */ outputFormat?: 'xml' | 'markdown'; /** Include token estimates in output (default: false) */ includeTokenEstimates?: boolean; /** Enable catalog browsing for large libraries (default: true) */ enableCatalog?: boolean; /** Catalog renderer config overrides */ catalogConfig?: Partial; } /** * Events emitted by the serving layer */ type ServingEvent = { type: 'loadout:changed'; state: LoadoutState; } | { type: 'skill:expanded'; skillId: string; } | { type: 'skill:collapsed'; skillId: string; } | { type: 'pending:added'; skillIds: string[]; } | { type: 'pending:approved'; skillIds: string[]; } | { type: 'pending:denied'; skillIds: string[]; } | { type: 'catalog:browsed'; path: string[]; } | { type: 'catalog:added'; skillId: string; }; /** * Handler for serving events */ type ServingEventHandler = (event: ServingEvent) => void; /** * SkillGraphServer - Main orchestrator for skill loadouts * * Provides dual control: external orchestrators can set/manage loadouts, * while agents can request modifications (subject to approval settings). * * @packageDocumentation */ /** * Main orchestrator for managing skill loadouts * * Supports: * - External orchestrator API for setting loadouts * - Agent API for requesting modifications (with optional approval) * - Expansion state management with eviction strategies * - Event emission for state changes */ declare class SkillGraphServer { private storage; private config; private compiler; private projectDetector; private viewRenderer; private catalogRenderer; private state; private handlers; private lruOrder; constructor(storage: StorageAdapter, config?: GraphServerConfig); /** * Initialize the server, applying initial loadout if configured */ initialize(): Promise; /** * Restore loadout state from persisted data */ restoreState(state: LoadoutState): void; /** * Set loadout from criteria (replaces current) */ setLoadout(criteria: LoadoutCriteria): Promise; /** * Set loadout based on task description (semantic matching) */ setLoadoutForTask(taskDescription: string): Promise; /** * Set loadout based on detected project context */ setLoadoutForProject(projectPath: string): Promise; /** * Set loadout from a named profile */ setLoadoutFromProfile(profileName: string): Promise; /** * Add skills to current loadout (merge mode) */ addSkills(skillIds: string[]): Promise; /** * Remove skills from current loadout */ removeSkills(skillIds: string[]): void; /** * Approve pending skill requests (adds to available) */ approvePending(skillIds: string[]): Promise; /** * Deny pending skill requests */ denyPending(skillIds: string[]): void; /** * Get current loadout state */ getState(): LoadoutState; /** * Get available profile names */ getProfiles(): string[]; /** * Add a profile at runtime */ addProfile(name: string, criteria: LoadoutCriteria): void; /** * Expand a skill (show full content) */ expandSkill(skillId: string): boolean; /** * Collapse a skill (hide full content) */ collapseSkill(skillId: string): boolean; /** * Agent requests to add skills * If requireApproval is true, adds to pending; otherwise directly adds */ agentRequestSkills(skillIds: string[]): Promise<{ added: string[]; pending: string[]; }>; /** * Agent requests to remove skills */ agentRemoveSkills(skillIds: string[]): { removed: string[]; }; /** * Agent requests to switch to a profile */ agentSwitchProfile(profileName: string): Promise; /** * Agent requests to set loadout (requires agentCanSetLoadout) */ agentSetLoadout(criteria: LoadoutCriteria): Promise; /** * Agent searches for skills (searches all skills, not just loadout) * Returns skill summaries for display */ agentSearchSkills(query: string, limit?: number): Promise; /** * Agent expands a skill (returns the full skill if in loadout) */ agentExpandSkill(skillId: string): Skill | null; /** * Agent collapses a skill */ agentCollapseSkill(skillId: string): boolean; /** * Agent lists current loadout (returns LoadoutView for display) */ agentListLoadout(): LoadoutView; /** * Agent browses the skill catalog at a given path. * Returns rendered category view (subcategories or skill summaries at leaf). * Pass no path for the top-level overview. */ agentBrowseCatalog(path?: string[]): Promise; /** * Agent adds a skill discovered via browsing directly to loadout and expands it. * Bridges browse → loadout: found it in catalog, now load it. */ agentAddFromCatalog(skillId: string): Promise<{ added: boolean; pending: boolean; expanded: boolean; }>; /** * Render current state as system prompt content. * Includes catalog overview when catalog is enabled. */ renderSystemPrompt(): Promise; /** * Estimate total tokens for current loadout */ estimateTokens(): number; /** * Subscribe to serving events */ on(handler: ServingEventHandler): () => void; /** * Emit an event to all handlers */ private emit; /** * Apply a new set of skills as the loadout */ private applyLoadout; /** * Evict a skill from expanded based on strategy */ private evictSkill; /** * Touch skill in LRU order (move to end) */ private touchLru; /** * Remove skill from LRU tracking */ private removeLru; /** * Get summary for a skill (short description) */ private getSummary; /** * Expand related skills (follows relationships) */ private expandRelated; } /** * Read-only view of skill storage for the serving layer * This interface provides only the methods needed for serving, * without exposing mutation operations. */ interface SkillStorageView { /** * Get a skill by ID (optionally a specific version) */ getSkill(id: string, version?: string): Promise; /** * List skills matching a filter */ listSkills(filter?: SkillFilter): Promise; /** * Search skills by query */ searchSkills(query: string): Promise; } /** * Events that flow from SkillBank to Serving Layer */ type SkillBankToServingEvent = { type: 'skill:created'; skill: Skill; } | { type: 'skill:updated'; skill: Skill; previousVersion: string; } | { type: 'skill:deleted'; skillId: string; } | { type: 'skill:deprecated'; skillId: string; }; /** * Events that flow from Serving Layer to SkillBank. * * `skill:used`, `skill:feedback`, and `skill:requested` were removed when * skill-tree dropped its `SkillMetrics` model — usage tracking is now * external (e.g., cognitive-core's `playbook.evolution.*`). See * docs/SKILL_TREE_METRICS_DEPRECATION.md. */ type ServingToSkillBankEvent = { type: 'loadout:changed'; state: LoadoutState; }; /** * Bidirectional event bridge between SkillBank and Serving Layer * * The serving layer registers to receive SkillBank events, * and the bridge forwards serving events back to SkillBank. */ interface ServingEventBridge { /** * Register handler for SkillBank → Serving events */ onSkillBankEvent(handler: (event: SkillBankToServingEvent) => void): () => void; /** * Emit event from Serving → SkillBank */ emitToSkillBank(event: ServingToSkillBankEvent): void; /** * Cleanup and disconnect */ disconnect(): void; } /** * Federation Types * * Types for managing federated skill repositories. * Federation enables connecting independent skill repositories for * cross-organization skill sharing and collaboration. */ /** * Configuration for a federated remote repository */ interface FederatedRemoteConfig { /** Git URL or local path to the remote repository */ url: string; /** Access level for this remote */ access: 'read-only' | 'read-write'; /** Local cache location (default: .remotes/{name}) */ localCache?: string; /** Branch to sync with (default: 'main') */ branch?: string; /** Path within repo where skills are stored (default: 'skills/') */ skillsPath?: string; /** Authentication method */ auth?: RemoteAuthConfig; } /** * Authentication configuration for private remotes */ interface RemoteAuthConfig { /** Auth type */ type: 'ssh' | 'https-token' | 'https-basic'; /** For https-token: the token */ token?: string; /** For https-basic: username */ username?: string; /** For https-basic: password */ password?: string; } /** * Runtime state of a remote */ interface RemoteState { /** Remote name */ name: string; /** Remote configuration */ config: FederatedRemoteConfig; /** When the remote was last fetched */ lastFetched?: Date; /** Current connection status */ status: 'connected' | 'disconnected' | 'error' | 'unknown'; /** Error message if status is 'error' */ error?: string; /** Number of skills available in this remote */ skillCount?: number; } /** * Mode for importing a skill from a remote */ type ImportMode = 'link' | 'fork'; /** * Options for importing a skill from a remote */ interface ImportOptions { /** * Import mode: * - 'link': Track upstream for updates (default) * - 'fork': Independent copy, no upstream tracking */ mode?: ImportMode; /** * Local ID for the imported skill. * Default: '@{remote}/{skillId}' for link, '{skillId}' for fork */ as?: string; /** * If true, overwrite existing skill with same ID. * Default: false (throws error on collision) */ overwrite?: boolean; } /** * Result of an import operation */ interface ImportResult { /** Whether the import succeeded */ success: boolean; /** The imported skill (if successful) */ skill?: Skill; /** Local ID of the imported skill */ localId: string; /** Import mode used */ mode: ImportMode; /** Error message (if failed) */ error?: string; } /** * Options for sharing a skill to a remote */ interface ShareOptions { /** * ID to use in the remote repository. * Default: strip '@' prefix from localId */ as?: string; /** Commit message for the share */ message?: string; /** If true, overwrite existing skill in remote */ overwrite?: boolean; } /** * Result of a share operation */ interface ShareResult { /** Whether the share succeeded */ success: boolean; /** ID of the skill in the remote */ remoteId: string; /** Git commit hash (if applicable) */ commitHash?: string; /** Error message (if failed) */ error?: string; } /** * Information about an available upstream update */ interface UpstreamUpdate { /** Local skill ID */ localId: string; /** Remote name */ remote: string; /** Skill ID in the remote */ remoteId: string; /** Current local version */ localVersion: string; /** Available remote version */ remoteVersion: string; /** Number of version bumps behind */ behind: number; /** Whether local changes exist that may conflict */ hasLocalChanges: boolean; } /** * Options for pulling upstream changes */ interface PullUpstreamOptions { /** * Strategy for handling conflicts: * - 'merge': Try to merge changes (default) * - 'overwrite': Replace local with remote */ strategy?: 'merge' | 'overwrite'; } /** * Result of pulling upstream changes */ interface PullUpstreamResult { /** Whether the pull succeeded */ success: boolean; /** The updated skill */ skill: Skill; /** Previous version before pull */ previousVersion: string; /** New version after pull */ newVersion: string; /** Whether conflicts were encountered */ hadConflicts: boolean; /** Unresolved conflicts (if any) */ conflicts?: UpstreamConflict[]; } /** * A conflict between local and upstream versions */ interface UpstreamConflict { /** Field that has a conflict */ field: keyof Skill; /** Local value */ local: unknown; /** Remote value */ remote: unknown; /** Base value (if available) */ base?: unknown; } /** * Events emitted by federation operations */ type FederationEvent = { type: 'remote:added'; name: string; config: FederatedRemoteConfig; } | { type: 'remote:removed'; name: string; } | { type: 'remote:refreshed'; name: string; skillCount: number; } | { type: 'skill:imported'; localId: string; remote: string; mode: ImportMode; } | { type: 'skill:shared'; localId: string; remote: string; remoteId: string; } | { type: 'upstream:updated'; localId: string; previousVersion: string; newVersion: string; } | { type: 'upstream:unlinked'; localId: string; }; type FederationEventHandler = (event: FederationEvent) => void | Promise; /** * Remote Store * * Persists remote configurations to disk in .skillbank/remotes.json. * Provides CRUD operations for managing federated remote repositories. */ /** * Options for creating a RemoteStore */ interface RemoteStoreOptions { /** Base path for the skill bank (where .skillbank/ will be created) */ basePath: string; } /** * RemoteStore manages persisted remote configurations. * * Storage location: {basePath}/.skillbank/remotes.json */ declare class RemoteStore { private basePath; private configDir; private configPath; private remotes; private initialized; constructor(options: RemoteStoreOptions); /** * Initialize the store, loading existing configuration */ initialize(): Promise; /** * Ensure store is initialized */ private ensureInitialized; /** * Load remotes from disk */ private load; /** * Save remotes to disk */ private save; /** * Add a remote */ addRemote(name: string, config: FederatedRemoteConfig): Promise; /** * Remove a remote */ removeRemote(name: string): Promise; /** * Get a remote configuration */ getRemote(name: string): FederatedRemoteConfig | undefined; /** * Check if a remote exists */ hasRemote(name: string): boolean; /** * List all remote names */ listRemotes(): string[]; /** * List all remotes with their configurations */ listRemotesWithConfig(): Array<{ name: string; config: FederatedRemoteConfig; }>; /** * Update a remote configuration */ updateRemote(name: string, updates: Partial): Promise; /** * Get the local cache path for a remote */ getCachePath(name: string): string; /** * Validate a remote name */ private isValidRemoteName; /** * Validate remote configuration */ private validateConfig; /** * Basic URL validation */ private isValidUrl; } /** * Remote Manager * * Handles git operations for remote repositories: * - Cloning remote repos to local cache * - Fetching updates * - Reading skills from cached repos * - Writing skills to writable remotes */ /** * Options for creating a RemoteManager */ interface RemoteManagerOptions { /** Base path for the skill bank */ basePath: string; /** Remote store instance */ remoteStore: RemoteStore; /** Timeout for git operations in ms (default: 60000) */ gitTimeout?: number; } /** * RemoteManager handles git operations for federated remotes. * * Directory structure: * {basePath}/ * .remotes/ * {remote-name}/ <- git clone of remote repo * skills/ <- skills directory in repo * skill-id/ * SKILL.md */ declare class RemoteManager { private basePath; private remotesDir; private remoteStore; private gitTimeout; private initialized; /** Cache of remote states */ private stateCache; /** Cache of skilltree configs per remote */ private configCache; /** Cache of discovered skill locations per remote */ private discoveryCache; constructor(options: RemoteManagerOptions); /** * Initialize the manager */ initialize(): Promise; /** * Ensure manager is initialized */ private ensureInitialized; /** * Refresh a remote (clone if not exists, fetch if exists) */ refreshRemote(name: string): Promise; /** * Get the state of a remote */ getRemoteState(name: string): Promise; /** * Delete the local cache for a remote */ deleteCache(name: string): Promise; /** * List skills from a remote */ listSkills(name: string, filter?: SkillFilter): Promise; /** * Get a single skill from a remote */ getSkill(remoteName: string, skillId: string): Promise; /** * Write a skill to a writable remote */ writeSkill(remoteName: string, skill: Skill): Promise; /** * Delete a skill from a writable remote */ deleteSkill(remoteName: string, skillId: string): Promise; /** * Commit and push changes to a remote */ commitAndPush(remoteName: string, message: string): Promise<{ commitHash: string; }>; /** * Clone a remote repository */ private gitClone; /** * Fetch latest from remote */ private gitFetch; /** * Check if a path is a git repository */ private isGitRepo; /** * Run a git command */ private runGit; /** * Get the cache path for a remote */ private getCachePath; /** * Load and cache the .skilltree config for a remote */ private getSkilltreeConfig; /** * Discover all skills in a remote repository's .skilltree directory */ private discoverSkills; /** * Get the path to write new skills to (.skilltree/skills/) */ private getWritePath; /** * Count skills in a remote's cache */ private countSkillsInCache; /** * Invalidate caches for a remote (call after fetch/clone) */ private invalidateCaches; /** * Parse skill content from SKILL.md format */ private parseSkillContent; /** * Parse YAML frontmatter (simple implementation) */ private parseYamlFrontmatter; /** * Parse tags from metadata */ private parseTags; /** * Serialize a skill to SKILL.md format */ private serializeSkill; /** * Apply filter to skills list */ private applyFilter; } /** * Federation Manager * * Main orchestrator for federated skill operations: * - Remote management (add, remove, refresh) * - Browse remote skills * - Import skills (link/fork modes) * - Share skills to remotes * - Upstream sync for linked skills */ /** * Options for creating a FederationManager */ interface FederationManagerOptions { /** Base path for skill storage */ basePath: string; /** Storage adapter for local skills */ storage: StorageAdapter; } /** * FederationManager orchestrates all federation operations. * * Usage: * ```typescript * const federation = new FederationManager({ basePath: './skills', storage }); * await federation.initialize(); * * // Add a remote * await federation.addRemote('team', { * url: 'git@github.com:org/skills.git', * access: 'read-write', * }); * * // Browse and import * const skills = await federation.browse('team'); * await federation.import('team', 'useful-pattern'); * * // Check for updates * const updates = await federation.checkUpstream(); * ``` */ declare class FederationManager { private basePath; private storage; private remoteStore; private remoteManager; private eventHandlers; private initialized; constructor(options: FederationManagerOptions); /** * Initialize the federation manager */ initialize(): Promise; /** * Ensure manager is initialized */ private ensureInitialized; /** * Add a remote repository */ addRemote(name: string, config: FederatedRemoteConfig): Promise; /** * Remove a remote repository */ removeRemote(name: string): Promise; /** * List configured remotes */ listRemotes(): string[]; /** * Check if a remote exists */ hasRemote(name: string): boolean; /** * Get the state of a remote */ getRemoteState(name: string): Promise; /** * Refresh a remote (fetch latest) */ refreshRemote(name: string): Promise; /** * Browse skills in a remote repository */ browse(remote: string, filter?: SkillFilter): Promise; /** * Get a specific skill from a remote */ browseSkill(remote: string, skillId: string): Promise; /** * Import a skill from a remote repository */ import(remote: string, skillId: string, options?: ImportOptions): Promise; /** * Get the default local ID for an imported skill */ private getDefaultLocalId; /** * Share a local skill to a remote repository */ share(localId: string, remote: string, options?: ShareOptions): Promise; /** * Strip @remote/ prefix from skill ID */ private stripPrefix; /** * Check for upstream updates to linked skills */ checkUpstream(): Promise; /** * Calculate how many versions behind */ private calculateVersionsBehind; /** * Pull upstream changes for a linked skill */ pullUpstream(localId: string, options?: PullUpstreamOptions): Promise; /** * Merge local and remote skills */ private mergeSkills; /** * Unlink a skill from its upstream (convert link to fork) */ unlink(localId: string): Promise; /** * Subscribe to federation events */ on(handler: FederationEventHandler): () => void; /** * Unsubscribe from events */ off(handler: FederationEventHandler): void; /** * Emit an event */ private emit; } /** * Create a FederationManager instance */ declare function createFederationManager(options: FederationManagerOptions): FederationManager; /** * Check if a directory has a .skilltree directory */ declare function hasSkilltreeDir(repoRoot: string): Promise; /** * Discovered skill location */ interface DiscoveredSkill { /** Skill ID (derived from path) */ id: string; /** Full path to the SKILL.md file */ filePath: string; /** Directory containing the skill */ directory: string; } /** * Discover all skills in a .skilltree directory */ declare function discoverSkills(repoRoot: string): Promise; /** * Skill lineage tracking * Tracks the evolution and relationships between skills */ /** * Options for creating a new version */ interface NewVersionOptions { /** Type of version bump (auto-inferred if not provided) */ bumpType?: BumpType; /** Changelog entry for this version */ changelog?: string; /** Changes for auto-inferring bump type */ changes?: VersionChanges; } /** * Options for rolling back a skill */ interface RollbackOptions { /** Why the rollback is being performed */ reason?: string; /** Custom changelog entry (auto-generated if not provided) */ changelog?: string; } /** * Options for forking a skill */ interface ForkOptions { /** New skill ID for the fork */ newId: string; /** New name for the forked skill */ newName?: string; /** Reason for forking */ reason: string; /** Version to fork from (defaults to latest) */ fromVersion?: string; } /** * Lineage tracker for managing skill versions and forks */ declare class LineageTracker { private storage; constructor(storage: StorageAdapter); /** * Create a new version of a skill */ createVersion(skillId: string, updates: Partial, options?: NewVersionOptions): Promise; /** * Fork a skill to create a new, related skill */ forkSkill(skillId: string, options: ForkOptions): Promise; /** * Merge changes from one skill into another */ mergeSkill(targetId: string, sourceId: string, options?: { /** Fields to merge */ fields?: (keyof Skill)[]; /** Strategy for conflicts */ conflictStrategy?: 'source' | 'target' | 'combine'; /** Changelog entry */ changelog?: string; }): Promise; /** * Get the full lineage tree for a skill */ getLineageTree(skillId: string): Promise; /** * Rollback a skill to a previous version. * Creates a new version (patch bump) with the content of the target version. * The rollback is recorded in the skill's notes for auditability. */ rollback(skillId: string, toVersion: string, options?: RollbackOptions): Promise; /** * Compare two versions of a skill */ compareVersions(skillId: string, versionA: string, versionB: string): Promise; /** * Get suggested next version based on changes */ suggestNextVersion(skillId: string, changes: VersionChanges): Promise; private mergeText; private diffSkills; } /** * Full lineage tree for a skill */ interface LineageTree { skillId: string; versions: SkillVersion[]; forks: Array<{ skill: Skill; fork: SkillFork; }>; ancestors: Skill[]; } /** * Diff between two versions */ interface VersionDiff { versionA: string; versionB: string; changes: SkillDiffChanges; } /** * Detailed changes between skills */ interface SkillDiffChanges { modified: Array<{ field: string; oldValue: string; newValue: string; }>; added: Array<{ type: string; value: string; }>; removed: Array<{ type: string; value: string; }>; } /** * Configuration for SkillBank */ interface SkillBankConfig { /** Storage configuration */ storage?: { type: 'memory'; } | { basePath: string; openSkillsCompatible?: boolean; }; /** Namespace configuration for multi-tier skill trees */ namespace?: { /** Current agent ID (used as owner for personal skills) */ agentId: string; /** Team the agent belongs to */ team?: string; /** Default scope for new skills */ defaultScope?: SkillScope; /** Default visibility for new skills */ defaultVisibility?: SkillVisibility; }; /** Hook registry for event-driven extensibility */ hookRegistry?: HookRegistry; /** Sync configuration for multi-agent collaboration */ sync?: { /** Sync configuration (remote, agent identity, behavior, conflicts) */ config: SyncConfig; /** Pull remote changes on initialize() (default: false) */ pullOnInit?: boolean; }; /** Materialization configuration for agent-discoverable skill output */ materialization?: MaterializationConfig; } /** * Main SkillBank class */ declare class SkillBank { private storage; private lineageTracker; private eventHandlers; private initialized; /** Namespace configuration for multi-tier skill trees */ private namespaceConfig?; /** Federation manager for remote repository connections */ private federationManager?; /** Base path for filesystem storage (needed for federation) */ private basePath?; /** Hook registry for event-driven extensibility */ private hookRegistry; /** Sync manager for multi-agent collaboration */ private syncManager?; /** Whether to pull on initialize */ private syncPullOnInit; /** Materializer for agent-discoverable output */ private materializer?; constructor(config?: SkillBankConfig); /** * Initialize the skill bank (required before use) */ initialize(): Promise; /** * Shutdown the skill bank cleanly */ shutdown(): Promise; /** * Ensure initialized before operations */ private ensureInitialized; /** * Get a skill by ID */ getSkill(id: string, version?: string): Promise; /** * List all skills with optional filtering */ listSkills(filter?: SkillFilter): Promise; /** * Search skills by query (uses SQLite FTS when available) */ searchSkills(query: string): Promise; /** * Save or update a skill * * Handles: * - Setting timestamps (createdAt on new skills, updatedAt always) * - Applying namespace if configured * - Placing in taxonomy if available * - Emitting skill:created or skill:updated events */ saveSkill(skill: Skill): Promise; /** * Ensure a skill has namespace information */ private ensureNamespace; /** * Delete a skill */ deleteSkill(id: string, version?: string): Promise; /** * Deprecate a skill */ deprecateSkill(id: string): Promise; /** * Create a new version of a skill */ createVersion(skillId: string, updates: Partial, options?: NewVersionOptions): Promise; /** * Fork a skill to create a new variant */ forkSkill(skillId: string, options: ForkOptions): Promise; /** * Get version history for a skill */ getVersionHistory(skillId: string): Promise; /** * Get full lineage for a skill */ getLineage(skillId: string): Promise; /** * Rollback a skill to a previous version */ rollbackSkill(skillId: string, toVersion: string, options?: RollbackOptions): Promise; /** * Compare two versions of a skill */ compareVersions(skillId: string, versionA: string, versionB: string): Promise; /** * Subscribe to skill bank events (skill:created, skill:updated, skill:deleted, skill:deprecated). * Returns an unsubscribe function. * * This is for simple, synchronous event listeners. For advanced use cases — async * handlers, priority ordering, filtering, or storage-level hooks (storage:after-save, * storage:after-delete) — use `getHookRegistry().register()` instead. */ on(handler: SkillTreeEventHandler): () => void; /** * Unsubscribe a handler from events */ off(handler: SkillTreeEventHandler): void; /** * Get current event handler count */ getEventHandlerCount(): number; /** * Emit an event to all handlers and execute corresponding hooks */ private emit; /** * Map SkillTreeEvent type to HookEvent type */ private mapEventToHook; /** * Build hook context from SkillTreeEvent */ private buildHookContext; /** * Get the underlying storage adapter (for advanced use cases) */ getStorage(): StorageAdapter; /** * Get the hook registry for registering custom hooks */ getHookRegistry(): HookRegistry; /** * Create a serving layer (SkillGraphServer) wired to this SkillBank * * @example * ```typescript * const { server, eventBridge, storageView } = await bank.createServingLayer({ * initialLoadout: { tags: ['typescript'] }, * maxExpanded: 5, * }); * * await server.setLoadoutForTask('Fix authentication bug'); * ``` */ createServingLayer(config?: GraphServerConfig): Promise<{ server: SkillGraphServer; eventBridge: ServingEventBridge; storageView: SkillStorageView; }>; /** * Map SkillBank events to serving layer events */ private mapToServingEvent; /** * Handle events from serving layer. * * The `loadout:changed` event is currently the only one we react to. * Earlier versions also handled `skill:used` / `skill:feedback` to mutate * `Skill.metrics`, but skill-tree no longer tracks per-skill usage — * cognitive-core owns that signal via `playbook.evolution.*`. See * docs/SKILL_TREE_METRICS_DEPRECATION.md. */ private handleServingEvent; /** * Get statistics about the skill bank */ getStats(): Promise; /** * Export all skills (for backup or migration) */ exportAll(): Promise; /** * Import skills (for restore or migration) */ importSkills(skills: Skill[]): Promise<{ imported: number; failed: number; }>; /** * Access the sync manager for multi-agent skill synchronization. * * @throws Error if sync is not configured */ get sync(): SyncManager; /** * Access the federation manager for remote repository operations. * * @throws Error if no basePath is configured (federation requires filesystem storage) */ get federation(): FederationManager; } /** * Statistics about the skill bank */ interface SkillBankStats { totalSkills: number; byStatus: Record; byTag: Record; byScope?: { personal: number; team: number; global: number; }; byVisibility?: { private: number; 'team-only': number; public: number; }; } /** * Create a SkillBank with common defaults */ declare function createSkillBank(config?: SkillBankConfig): SkillBank; /** * Base storage adapter interface and utilities */ /** * Abstract base class for storage adapters */ declare abstract class BaseStorageAdapter implements StorageAdapter { protected initialized: boolean; abstract initialize(): Promise; abstract saveSkill(skill: Skill): Promise; abstract getSkill(id: string, version?: string): Promise; abstract listSkills(filter?: SkillFilter): Promise; abstract deleteSkill(id: string, version?: string): Promise; abstract getVersionHistory(skillId: string): Promise; abstract getLineage(skillId: string): Promise; abstract searchSkills(query: string): Promise; /** * Ensure storage is initialized before operations */ protected ensureInitialized(): void; /** * Apply filters to a list of skills */ protected applyFilter(skills: Skill[], filter?: SkillFilter): Skill[]; /** * Apply namespace-related filters to a skill */ protected applyNamespaceFilter(skill: Skill, filter: SkillFilter): boolean; /** * Check if an agent can access a skill based on namespace rules */ protected canAgentAccessSkill(skill: Skill, agentId: string, agentTeam?: string): boolean; /** * Simple text search across skill fields */ protected textSearch(skills: Skill[], query: string): Skill[]; } /** * In-memory storage adapter (useful for testing) */ declare class MemoryStorageAdapter extends BaseStorageAdapter { private skills; private lineages; initialize(): Promise; saveSkill(skill: Skill): Promise; getSkill(id: string, version?: string): Promise; listSkills(filter?: SkillFilter): Promise; deleteSkill(id: string, version?: string): Promise; getVersionHistory(skillId: string): Promise; getLineage(skillId: string): Promise; searchSkills(query: string): Promise; private updateLineage; private compareVersions; private hashSkill; /** * Clear all stored skills (for testing) */ clear(): void; recordFork(sourceSkillId: string, fork: SkillFork): Promise; } /** * Cached Storage Adapter * * Composes FilesystemStorageAdapter (source of truth) with an optional * SQLiteStorageAdapter cache for fast FTS search and indexed queries. * * The SQLite cache is stored in .skilltree/.cache/index.db and is * gitignored. If better-sqlite3 is unavailable, it operates in * filesystem-only mode gracefully. * * Directory structure: * basePath/.skilltree/ * skills/ ← committed source of truth * .cache/ * index.db ← SQLite cache (gitignored) * manifest.json ← file mtime manifest for staleness detection */ interface CachedStorageConfig { /** Base directory for skill storage */ basePath: string; /** Use OpenSkills-compatible format (SKILL.md) — default: true */ openSkillsCompatible?: boolean; } /** * Cached storage adapter that uses filesystem as source of truth * with an optional SQLite cache for fast queries. */ declare class CachedStorageAdapter extends BaseStorageAdapter { private source; private cache; private basePath; private cacheDir; private dbPath; private manifestPath; constructor(config: CachedStorageConfig); initialize(): Promise; /** * Get the base path for this storage */ getBasePath(): string; /** * Whether the SQLite cache is active */ hasCacheEnabled(): boolean; saveSkill(skill: Skill): Promise; deleteSkill(id: string, version?: string): Promise; getSkill(id: string, version?: string): Promise; listSkills(filter?: SkillFilter): Promise; searchSkills(query: string): Promise; getVersionHistory(skillId: string): Promise; getLineage(skillId: string): Promise; recordFork(sourceSkillId: string, fork: SkillFork): Promise; /** * Force a full cache rebuild from filesystem */ rebuildCache(): Promise; /** * Check if cache is stale and rebuild if needed */ private rebuildIfStale; private readManifest; private writeManifest; private updateManifestEntry; private removeManifestEntry; /** * Close the cache database connection */ close(): void; } /** * Storage migration utility * * Migrates skill data between storage backends (memory, filesystem, SQLite). * Copies skills, version history, and lineage. */ /** * Options for storage migration */ interface MigrationOptions { /** Migrate skills */ skills?: boolean; /** Migrate version history and lineage */ lineage?: boolean; /** Called for each item migrated */ onProgress?: (item: MigrationProgressItem) => void; /** Whether to overwrite existing items in the target */ overwrite?: boolean; } /** * Progress item for migration callbacks */ interface MigrationProgressItem { type: 'skill' | 'lineage'; id: string; status: 'migrated' | 'skipped' | 'error'; error?: string; } /** * Result of a storage migration */ interface MigrationResult { /** Total items processed */ totalProcessed: number; /** Successfully migrated items */ migrated: number; /** Skipped items (already exist and overwrite=false) */ skipped: number; /** Failed items */ errors: number; /** Breakdown by type */ details: { skills: { migrated: number; skipped: number; errors: number; }; lineages: { migrated: number; skipped: number; errors: number; }; }; } /** * Migrate data from one storage backend to another. * * Both storage adapters must be initialized before calling this function. * * @example * ```typescript * const memory = new MemoryStorageAdapter(); * const fs = new FilesystemStorageAdapter({ basePath: './skills' }); * await memory.initialize(); * await fs.initialize(); * * const result = await migrateStorage(memory, fs, { * skills: true, * lineage: true, * onProgress: (item) => console.log(`${item.type}: ${item.id} - ${item.status}`), * }); * ``` */ declare function migrateStorage(source: StorageAdapter, target: StorageAdapter, options?: MigrationOptions): Promise; /** * AGENTS.md Integration Types */ /** * Format for skill descriptions in AGENTS.md */ type SkillFormat = 'xml' | 'markdown' | 'json'; /** * Configuration for AGENTS.md generation */ interface AgentsGeneratorConfig { /** Output format for skills (default: 'xml') */ format?: SkillFormat; /** Include skill IDs as data attributes (default: true) */ includeIds?: boolean; /** Include version information (default: true) */ includeVersions?: boolean; /** Group skills by tags (default: false) */ groupByTags?: boolean; /** Custom header content */ header?: string; /** Custom footer content */ footer?: string; /** Filter skills to include */ filter?: SkillSelector; } /** * Skill selector for filtering which skills to include */ interface SkillSelector { /** Include only these skill IDs */ ids?: string[]; /** Include skills with any of these tags */ tags?: string[]; /** Include skills matching this status */ status?: ('active' | 'experimental')[]; /** Maximum number of skills to include */ limit?: number; } /** * Parsed skill from AGENTS.md */ interface ParsedAgentSkill { /** Skill ID (if present) */ id?: string; /** Skill name */ name: string; /** Skill description */ description: string; /** Instructions content */ instructions?: string; /** Problem this skill solves (legacy, used during parsing) */ problem?: string; /** Solution steps (legacy, used during parsing) */ solution?: string; /** Verification steps (legacy, used during parsing) */ verification?: string; /** Additional notes (legacy, used during parsing) */ notes?: string; /** Tags extracted from content */ tags?: string[]; /** Version (if present) */ version?: string; /** Raw content block */ rawContent: string; } /** * Result of parsing AGENTS.md */ interface ParsedAgentsFile { /** Header content before skills */ header?: string; /** Parsed skills */ skills: ParsedAgentSkill[]; /** Footer content after skills */ footer?: string; /** Warnings during parsing */ warnings: string[]; } /** * Sync result */ interface SyncResult { /** Skills added to bank */ added: string[]; /** Skills updated in bank */ updated: string[]; /** Skills removed (in bank but not in AGENTS.md) */ removed: string[]; /** Skills unchanged */ unchanged: string[]; /** Warnings/issues */ warnings: string[]; } /** * Default configuration */ declare const DEFAULT_AGENTS_CONFIG: Required>; /** * AGENTS.md Generator * * Generates AGENTS.md content from skill bank for Claude Code integration. */ /** * Generate AGENTS.md content from skills */ declare class AgentsGenerator { private config; constructor(config?: AgentsGeneratorConfig); /** * Generate AGENTS.md content from a skill bank */ generate(storage: StorageAdapter): Promise; /** * Generate content for a single skill */ generateSkill(skill: Skill): string; /** * Generate skills list */ private generateSkillsList; /** * Generate skills grouped by tags */ private generateGroupedSkills; /** * Generate XML format skill (Claude Code native format) */ private generateXmlSkill; /** * Generate Markdown format skill */ private generateMarkdownSkill; /** * Generate JSON format skill */ private generateJsonSkill; /** * Filter skills based on selector */ private filterSkills; /** * Generate default header */ private generateDefaultHeader; /** * Format tag name for section header */ private formatTagName; /** * Escape XML special characters */ private escapeXml; /** * Indent content */ private indentContent; } /** * Create an AGENTS.md generator */ declare function createAgentsGenerator(config?: AgentsGeneratorConfig): AgentsGenerator; /** * AGENTS.md Parser * * Parses AGENTS.md files to import skills into skill bank. */ /** * Parse AGENTS.md content */ declare class AgentsParser { /** * Parse AGENTS.md content */ parse(content: string): ParsedAgentsFile; /** * Convert parsed skill to Skill type */ toSkill(parsed: ParsedAgentSkill, defaults?: Partial): Skill; /** * Parse XML format skills */ private parseXmlSkills; /** * Parse Markdown format skills */ private parseMarkdownSkills; /** * Extract content from XML tag */ private extractXmlTag; /** * Extract CDATA content */ private extractCData; /** * Unescape XML entities */ private unescapeXml; /** * Extract a markdown section by header */ private extractMarkdownSection; /** * Generate ID from skill name */ private generateId; /** * Extract header content */ private extractHeader; /** * Extract footer content */ private extractFooter; } /** * Create an AGENTS.md parser */ declare function createAgentsParser(): AgentsParser; /** * AGENTS.md Sync * * Synchronize skills between AGENTS.md and skill bank. */ /** * Sync options */ interface SyncOptions { /** Sync direction */ direction: 'import' | 'export' | 'bidirectional'; /** How to handle conflicts (when skill exists in both) */ conflictStrategy?: 'bank-wins' | 'agents-wins' | 'newer-wins' | 'skip'; /** Delete skills in bank that are not in AGENTS.md (only for import) */ removeOrphans?: boolean; /** Generator config for export */ generatorConfig?: AgentsGeneratorConfig; /** Dry run - don't make changes, just report */ dryRun?: boolean; } /** * Synchronize AGENTS.md with skill bank */ declare class AgentsSync { private generator; private parser; constructor(); /** * Sync AGENTS.md with skill bank */ sync(agentsPath: string, storage: StorageAdapter, options: SyncOptions): Promise; /** * Import skills from AGENTS.md to skill bank */ importFromAgents(agentsPath: string, storage: StorageAdapter, options: SyncOptions, result: SyncResult): Promise; /** * Export skills from skill bank to AGENTS.md */ exportToAgents(agentsPath: string, storage: StorageAdapter, options: SyncOptions, result: SyncResult): Promise; /** * Bidirectional sync */ bidirectionalSync(agentsPath: string, storage: StorageAdapter, options: SyncOptions, result: SyncResult): Promise; /** * Resolve conflict between existing and new skill */ private resolveConflict; /** * Merge skills, preserving important data from existing */ private mergeSkills; } /** * Create an AGENTS.md sync manager */ declare function createAgentsSync(): AgentsSync; /** * Convenience function to generate AGENTS.md */ declare function generateAgentsMd(storage: StorageAdapter, config?: AgentsGeneratorConfig): Promise; /** * Convenience function to write AGENTS.md to file */ declare function writeAgentsMd(storage: StorageAdapter, filePath: string, config?: AgentsGeneratorConfig): Promise; /** * Convenience function to import from AGENTS.md */ declare function importFromAgentsMd(filePath: string, storage: StorageAdapter, options?: { dryRun?: boolean; conflictStrategy?: SyncOptions['conflictStrategy']; }): Promise; /** * Built-in hooks for common use cases * * Runtime metrics hooks (matched/applied/feedback) have moved to cognitive-core * which handles skill usage tracking via sessionlog integration. */ /** * Creates a logging hook that logs all events */ declare function createLoggingHook(logger?: (message: string, context?: Record) => void): RegisterHookOptions; /** * Creates a hook that backs up skills before save */ declare function createBackupHook(backupFn: (skill: unknown) => Promise): RegisterHookOptions; /** * Creates a hook that validates skills before save */ declare function createSaveValidationHook(options: { requiredFields?: (keyof any)[]; maxDescriptionLength?: number; requireTriggers?: boolean; }): RegisterHookOptions; /** * Combines multiple hook handlers into one */ declare function combineHandlers(...handlers: HookHandler[]): HookHandler; /** * Creates a conditional hook that only runs when filter passes */ declare function conditionalHook(filter: (context: any) => boolean, handler: HookHandler): HookHandler; /** * LoadoutCompiler - Compiles skills from flexible criteria * * Supports multiple selection strategies: * - Explicit include/exclude * - Tag-based filtering * - Quality/status filtering * - Semantic matching * - Relationship traversal * * @packageDocumentation */ /** * Compiles skills from flexible criteria */ declare class LoadoutCompiler { private storage; private config; constructor(storage: StorageAdapter, config?: LoadoutCompilerConfig); /** * Main entry point - compile skills from criteria. * * Filter pipeline order: * 1. status (initial query) * 2. exclude (drop matching IDs) * 3. tags / tagsAll * 4. author * 5. semantic (currently no-op) * 6. relationships (rootSkills traversal) * 7. **include** — presence guarantee: ensures every ID in the * include list is in the result regardless of the filters above, * fetching missing ones from storage as needed. `exclude` still * wins (excluded IDs are removed from the include list before * this step). * 8. limits (maxSkills, maxTokens) * * For "restrict to exactly these skills" semantics, combine * `include: [...]` with `maxSkills: include.length`. */ compile(criteria: LoadoutCriteria): Promise; /** * Compile based on a task description (semantic matching) */ compileForTask(taskDescription: string): Promise; /** * Compile from a named profile */ compileFromProfile(profileName: string, profiles: Record): Promise; /** * Merge two loadouts based on mode */ mergeLoadouts(current: Skill[], additions: Skill[], mode?: 'replace' | 'merge' | 'subtract'): Skill[]; /** * Apply explicit exclude filter. Include is handled separately at the * compile level (see `ensureIncludedPresent`) so it can guarantee * presence regardless of the other filters in this method or below. */ applyExplicitFilters(skills: Skill[], criteria: LoadoutCriteria): Skill[]; /** * Apply tag-based filters */ applyTagFilters(skills: Skill[], criteria: LoadoutCriteria): Skill[]; /** * Apply quality/status filters */ applyQualityFilters(skills: Skill[], criteria: LoadoutCriteria): Skill[]; /** * Apply semantic filters (task description, problem context, etc.) * * Currently returns skills unchanged. Semantic matching was removed; * use SQLite FTS via storage.searchSkills() for keyword-based search. */ applySemanticFilters(skills: Skill[], _criteria: LoadoutCriteria): Promise; /** * Apply relationship-based filters (root skills, dependencies) */ applyRelationshipFilters(skills: Skill[], criteria: LoadoutCriteria): Promise; /** * Ensure every ID in `criteria.include` is present in the result, * regardless of which earlier filter would have dropped it. Missing * skills are fetched directly from storage. * * `criteria.exclude` still wins: an ID listed in both `include` and * `exclude` is treated as excluded (consistent with openteams' "deny * wins" inheritance rule on permissions). * * Included skills are placed at the front of the result, preserving * the order of `criteria.include`. Other skills retain their relative * order behind them. */ ensureIncludedPresent(current: Skill[], criteria: LoadoutCriteria): Promise; /** * Apply limits and sorting */ applyLimits(skills: Skill[], criteria: LoadoutCriteria): Skill[]; /** * Estimate token count for a skill (rough approximation) */ private estimateTokens; } /** * ViewRenderer - Renders loadout state for agent consumption * * Supports multiple output formats: * - XML (OpenSkills-compatible) * - Markdown (debugging/display) * - SKILL.md format * * @packageDocumentation */ /** * Configuration for ViewRenderer */ interface ViewRendererConfig { /** Include token estimates in output */ includeTokenEstimates?: boolean; /** Maximum summary length (characters) */ maxSummaryLength?: number; } /** * Renders loadout state for agent consumption */ declare class ViewRenderer { private config; constructor(config?: ViewRendererConfig); /** * Render loadout state as OpenSkills-compatible XML */ renderXml(state: LoadoutState): string; /** * Render loadout state as Markdown (for debugging) */ renderMarkdown(state: LoadoutState): string; /** * Render a skill in SKILL.md format */ renderSkillMd(skill: Skill): string; /** * Estimate total tokens for a loadout state */ estimateTokens(state: LoadoutState): number; /** * Convert loadout state to array of skill summaries */ toSummaries(state: LoadoutState): SkillSummary[]; /** * Get summary for a skill (short description). * Delegates to shared getSkillSummary utility. */ private getSummary; /** * Escape special XML characters. * Delegates to shared escapeXml utility. */ private escapeXml; /** * Estimate tokens for a full skill */ private estimateSkillTokens; /** * Estimate tokens for a skill summary */ private estimateSummaryTokens; } /** * ProjectDetector - Analyzes project directories to infer skill requirements * * Detects: * - Project type (Node.js, Python, Rust, Go, Java) * - Frameworks (React, Express, FastAPI, etc.) * - Patterns (CI/CD, Docker, etc.) * - Package manager * * @packageDocumentation */ /** * Detects project context from file system */ declare class ProjectDetector { /** Cache for project context */ private cache; /** Project type patterns */ private static PROJECT_TYPES; /** TypeScript detection */ private static TYPESCRIPT_FILES; /** Node.js framework patterns */ private static NODE_FRAMEWORKS; /** Python framework patterns (from pyproject.toml or requirements.txt) */ private static PYTHON_FRAMEWORKS; /** Directory patterns */ private static DIRECTORY_PATTERNS; /** * Detect project context from a directory */ detectProjectContext(projectPath: string): Promise; /** * Convert project context to loadout criteria */ contextToCriteria(context: ProjectContext): LoadoutCriteria; /** * Clear the detection cache */ clearCache(): void; /** * Detect project type from manifest files */ private detectProjectType; /** * Check for TypeScript */ private hasTypeScript; /** * Detect Node.js frameworks from package.json */ private detectNodeFrameworks; /** * Detect Python frameworks from dependencies */ private detectPythonFrameworks; /** * Detect patterns from directory structure */ private detectDirectoryPatterns; } /** * CatalogRenderer - Renders compressed, browsable skill catalog views * * Provides hierarchical discovery for large skill libraries by rendering * taxonomy trees or tag-based groupings at minimal token cost. Agents can * browse categories level by level instead of seeing a flat list. * * Two strategies: * 1. Taxonomy-based: Uses taxonomy_nodes from SQLite (preferred) * 2. Tag-based fallback: Groups skills by primary tag when no taxonomy exists * * @packageDocumentation */ /** * Renders compressed, browsable skill catalog views for agent consumption */ declare class CatalogRenderer { private storage; private config; private overviewCache; private static readonly CACHE_TTL_MS; constructor(storage: StorageAdapter, config?: Partial); /** * Render level-0 catalog overview for system prompt injection. * Shows top-level categories with counts. ~200 tokens. * Returns empty string if no skills exist. * Results are cached for 60 seconds to avoid repeated storage queries. */ renderOverview(): Promise; /** * Render a specific category path for browse drill-down. * Shows subcategories at intermediate nodes, or skill summaries at leaf nodes. */ renderCategory(path: string[]): Promise; /** * Invalidate the overview cache (e.g., after skill changes). */ invalidateCache(): void; /** * Render the overview XML shell with a list of categories. * Used by both taxonomy-based and tag-based paths. */ private renderOverviewXml; private renderOverviewFromNodes; private renderCategoryFromTaxonomy; private renderOverviewFromTags; private renderCategoryFromTags; private renderLeafSkills; private groupByPrimaryTag; /** * Pre-compute counts for a list of nodes, avoiding redundant recursive walks. */ private withCounts; private countNodeSkills; } /** * Built-in Loadout Profiles * * Pre-configured loadout criteria for common use cases. * These can be used directly or as templates for custom profiles. * * @packageDocumentation */ /** * Code Review Profile * * Optimized for reviewing code quality, security, and best practices. * Focuses on skills related to code analysis, security patterns, and quality gates. */ declare const codeReviewProfile: LoadoutCriteria; /** * Implementation Profile * * Optimized for writing new code and features. * Focuses on TDD, coding standards, and development patterns. */ declare const implementationProfile: LoadoutCriteria; /** * Debugging Profile * * Optimized for diagnosing and fixing bugs. * Focuses on error analysis, logging, and debugging techniques. */ declare const debuggingProfile: LoadoutCriteria; /** * Security Profile * * Optimized for security-focused work. * Focuses on vulnerability detection, secure coding, and security reviews. */ declare const securityProfile: LoadoutCriteria; /** * Testing Profile * * Optimized for writing and maintaining tests. * Focuses on test patterns, coverage, and test-driven development. */ declare const testingProfile: LoadoutCriteria; /** * Refactoring Profile * * Optimized for improving existing code. * Focuses on code quality, patterns, and safe refactoring techniques. */ declare const refactoringProfile: LoadoutCriteria; /** * Documentation Profile * * Optimized for writing and maintaining documentation. * Focuses on technical writing, API docs, and code comments. */ declare const documentationProfile: LoadoutCriteria; /** * DevOps Profile * * Optimized for infrastructure and deployment work. * Focuses on CI/CD, Docker, Kubernetes, and cloud patterns. */ declare const devopsProfile: LoadoutCriteria; /** * All built-in profiles keyed by name */ declare const builtInProfiles: Record; /** * Get a built-in profile by name */ declare function getBuiltInProfile(name: string): LoadoutCriteria | undefined; /** * List all built-in profile names */ declare function listBuiltInProfiles(): string[]; /** * Materializer - Keeps agent-discoverable filesystem representations * in sync with the skill bank. * * Supports two modes: * - 'symlink': Creates symlinks from discovery paths into .skilltree/skills/ * - 'copy': Copies skill directories to discovery paths * * Also auto-regenerates AGENTS.md on skill changes with marker-based sections. */ declare class Materializer { private storage; private basePath; private config; private debounceTimer; private pendingRegen; private regenerating; private watcher; private watchDebounceTimer; constructor(storage: StorageAdapter, basePath: string, config: MaterializationConfig); private get mode(); private get skillsSourceDir(); /** * Initial materialization: create all symlinks/copies + generate AGENTS.md */ initialize(): Promise; /** * Called when a skill is created or updated */ onSkillChanged(skillId: string): Promise; /** * Called when a skill is deleted */ onSkillDeleted(skillId: string): Promise; /** * Materialize a skill to all configured paths (symlink or copy) */ private ensureMaterialized; /** * Remove a materialized skill from all configured paths */ private removeMaterialized; /** * Create or verify a symlink */ private ensureSymlink; /** * Copy a skill directory, adding a marker file so we know we manage it */ private copyDir; /** * Schedule debounced AGENTS.md regeneration */ private scheduleAgentsMdRegen; /** * Regenerate AGENTS.md with marker-based section replacement */ regenerateAgentsMd(): Promise; private _doRegenerateAgentsMd; /** * Remove stale entries (symlinks or copies) that point to non-existent skills */ cleanup(): Promise; /** * Start watching .skilltree/skills/ for external changes. * Re-materializes when files are added/changed/removed outside the SkillBank API. */ watch(): void; /** * Stop watching for file changes */ unwatch(): void; /** * Flush any pending debounced operations (useful for testing) */ flush(): Promise; /** * Tear down: cancel pending timers and stop watcher */ shutdown(): void; /** * Resolve a path relative to basePath, handling ~ expansion */ private resolvePath; } /** * Git Sync Adapter * * Git-based skill synchronization for multi-agent collaboration. * Wraps FilesystemStorageAdapter with git operations. */ /** * Options for creating a GitSyncAdapter */ interface GitSyncAdapterOptions { /** Path to the git repository */ repoPath: string; /** Sync configuration */ config: SyncConfig; } declare class GitSyncAdapter { private repoPath; private config; private conflictStore; private git; private initialized; constructor(options: GitSyncAdapterOptions); /** * Initialize the adapter */ initialize(): Promise; /** * Ensure adapter is initialized */ private ensureInitialized; /** * Fetch remote changes without applying them */ fetch(): Promise; /** * Pull remote changes and merge into local */ pull(options?: PullOptions): Promise; /** * Push local changes to remote */ push(options?: PushOptions): Promise; /** * Get current sync status */ status(): Promise; /** * List all pending conflicts */ listConflicts(): Promise; /** * Resolve a conflict */ resolveConflict(skillId: string, resolution: ConflictResolution): Promise; private getSkillsPath; private getSkillFilePath; private extractSkillIdFromPath; private pullSkill; private isLocallyModified; private attemptAutoMerge; private applyStrategy; private getConflictingFields; private parseSkillContent; private writeSkill; private buildSkillContent; private buildCommitMessage; private updateSyncState; private hashSkill; } /** * Create a GitSyncAdapter instance */ declare function createGitSyncAdapter(options: GitSyncAdapterOptions): GitSyncAdapter; /** * Conflict Store * * Persists skill conflicts to .skillbank/conflicts/ for resolution workflow */ /** * Store for persisting sync conflicts and state */ declare class ConflictStore { private conflictsDir; private stateFile; constructor(basePath: string); /** * Initialize the store (create directories if needed) */ initialize(): Promise; /** * Save a conflict for later resolution */ saveConflict(conflict: SkillConflict): Promise; /** * Get a conflict by skill ID */ getConflict(skillId: string): Promise; /** * List all pending conflicts */ listConflicts(): Promise; /** * Remove a conflict (after resolution) */ removeConflict(skillId: string): Promise; /** * Check if a skill has a pending conflict */ hasConflict(skillId: string): Promise; /** * Get count of pending conflicts */ getConflictCount(): Promise; /** * Load sync state */ loadState(): Promise; /** * Save sync state */ saveState(state: SyncState): Promise; /** * Update state for a single skill */ updateSkillState(skillId: string, skillState: SkillSyncState): Promise; /** * Get state for a single skill */ getSkillState(skillId: string): Promise; /** * Remove skill from state (when deleted) */ removeSkillState(skillId: string): Promise; private getConflictFilename; private serializeConflict; private deserializeConflict; private serializeSkillDates; private deserializeSkillDates; } /** * Create a conflict store instance */ declare function createConflictStore(basePath: string): ConflictStore; declare function createDefaultSyncConfig(remoteUrl: string, agentId: string, options?: { branch?: string; agentName?: string; environment?: string; }): SyncConfig; /** * Indexer Service - Wraps the skill indexer functionality for use with SkillBank * * This service provides a bridge between the skill indexer (scraper/) and the * main skill-tree SkillBank. It can work in two modes: * * 1. Standalone mode: Direct database operations (default) * 2. Integrated mode: Uses SkillBank as the storage backend */ /** * Skill source for scraping */ interface SkillSource { type: "awesome-list" | "repository"; url: string; } /** * Indexer configuration (service-level) */ interface IndexerServiceConfig { /** GitHub API token */ githubToken?: string; /** Anthropic API key for classification */ anthropicApiKey?: string; /** Claude model to use */ claudeModel?: string; /** Database path for standalone mode */ databasePath?: string; /** Batch size for processing */ batchSize?: number; /** Concurrency limit */ concurrency?: number; /** Minimum confidence for classification */ minConfidence?: number; /** Cache directory */ cacheDir?: string; /** Cache TTL in seconds */ cacheTtlSeconds?: number; /** Pre-loaded scraper module. When provided, skips filesystem-based module discovery entirely. */ scraperModules?: any; } /** * Scrape result */ interface ScrapeResult { discovered: number; scraped: number; skipped: number; failed: number; unchanged: number; errors: string[]; } /** * Index result */ interface IndexResult { indexed: number; skipped: number; failed: number; errors: string[]; } /** * Relationship detection result */ interface RelationshipResult { detected: number; skipped: number; errors: string[]; } /** * Taxonomy node for tree display */ interface TaxonomyNode { id: string; name: string; path: string[]; skillCount: number; children: TaxonomyNode[]; } /** * Database statistics */ interface IndexerStats { totalSkills: number; indexedSkills: number; rawSkills: number; failedSkills: number; taxonomyNodes: number; relationships: number; sources: number; } /** * IndexerService - Manages skill discovery, classification, and relationship detection */ declare class IndexerService { private serviceConfig; private globalConfig; private skillBank?; private initialized; private scraperModule?; private indexerModule?; private databaseModule?; private db?; constructor(config?: IndexerServiceConfig, skillBank?: SkillBank); /** * Get effective configuration */ getConfig(): IndexerServiceConfig; /** * Initialize the service (lazy load scraper modules) */ initialize(): Promise; /** * Check if the indexer is available */ isAvailable(): boolean; /** * Check if running in degraded mode (no scraper modules) */ isDegradedMode(): boolean; /** * Scrape skills from GitHub sources */ scrape(sources: SkillSource[], options?: { force?: boolean; }): Promise; /** * Classify unindexed skills using AI */ classify(options?: { skillId?: string; all?: boolean; }): Promise; /** * Detect relationships between skills */ detectRelationships(options?: { skillId?: string; useAi?: boolean; }): Promise; /** * Detect relationships for a single skill */ private detectSkillRelationships; /** * Get taxonomy tree */ getTaxonomyTree(rootPath?: string[]): Promise; /** * Wrap tree nodes returned from SQLite storage into a root node */ private wrapTreeNodes; /** * Convert storage tree node to TaxonomyNode format */ private convertToTaxonomyNode; /** * Count total skills in a node tree */ private countNodeSkills; /** * Build taxonomy tree from flat nodes */ private buildTaxonomyTree; /** * Build taxonomy tree from skills */ private buildTaxonomyTreeFromSkills; /** * Get indexer statistics */ getStats(): Promise; /** * Count nodes in taxonomy tree */ private countTaxonomyNodes; /** * Scrape and index skills directly into SkillBank * This is the streamlined workflow for integrated mode */ scrapeAndIndex(sources: SkillSource[], options?: { force?: boolean; autoClassify?: boolean; detectRelationships?: boolean; /** Import all scraped skills into SkillBank regardless of classification status */ importAll?: boolean; }): Promise<{ scraped: ScrapeResult; indexed: IndexResult; relationships: RelationshipResult; skillsAdded: string[]; }>; /** * Import skills from indexer database into SkillBank */ importFromIndexerDb(options?: { status?: "raw" | "indexed" | "failed"; limit?: number; }): Promise<{ imported: number; failed: number; skills: Skill[]; }>; /** * Get default skill sources from config */ getDefaultSources(): SkillSource[]; /** * Close database connections */ close(): Promise; } /** * skill-tree - A library for managing agent skill versions and evolution * * This library provides: * - Versioned skill storage (OpenSkills-compatible) * - Lineage tracking and skill evolution * - Serving layer with dynamic loadouts * - Multi-agent sync and federation * * @packageDocumentation */ declare const VERSION = "0.2.0"; export { type AgentConfig, AgentsGenerator, type AgentsGeneratorConfig, AgentsParser, AgentsSync, type BaseHookContext, type BumpType, CachedStorageAdapter, type CachedStorageConfig, CatalogRenderer, type CatalogRendererConfig, type ConflictConfig, type ConflictResolution$1 as ConflictResolution, ConflictStore, type ConflictStrategy, DEFAULT_AGENTS_CONFIG, type DiscoveredSkill, type EvictionStrategy, type ExpandTrigger, type ExpandTriggerConfig, type FederatedRemoteConfig, type FederationEvent, type FederationEventHandler, FederationManager, type FederationManagerOptions, type FetchResult, type ForkOptions, GitSyncAdapter, type GitSyncAdapterOptions, type SyncResult$1 as GitSyncResult, type GraphServerConfig, type HookContext, type HookEvent, type HookExecutionResult, type HookHandler, type HookPriority, HookRegistry, type HookResult, type ImportMode, type ImportOptions, type ImportResult, type IndexResult, IndexerService, type IndexerServiceConfig, type SkillSource as IndexerSkillSource, type IndexerStats, LineageTracker, type LineageTree, LoadoutCompiler, type LoadoutCompilerConfig, type LoadoutCriteria, type LoadoutSource, type LoadoutState, type LoadoutView, type MaterializationConfig, Materializer, MemoryStorageAdapter, type MergeConfig, type MergeConflict, type MergePreview, type MergeResult, type MergeStrategy, type MergeSuggestion, type MigrationOptions, type MigrationProgressItem, type MigrationResult, type NewVersionOptions, type ParsedAgentSkill, type ParsedAgentsFile, type ParsedVersion, type ProjectContext, ProjectDetector, type PullOptions, type PullUpstreamOptions, type PullUpstreamResult, type PushOptions, type RegisterHookOptions, type RegisteredHook, type RelationshipResult, type RemoteConfig, RemoteManager, type RemoteState, RemoteStore, type RollbackOptions, type ScrapeResult, type ServingEvent, type ServingEventHandler, type ShareOptions, type ShareResult, type Skill, type SkillAccessControl, SkillBank, type SkillBankConfig, type SkillBankStats, type SkillChange, type SkillConflict, type SkillCrudHookContext, type SkillDiffChanges, type SkillFilter, type SkillFork, type SkillFormat, SkillGraphServer, type SkillLineage, type SkillMergeResult, SkillMerger, type SkillNamespace, type SkillScope, type SkillSelector, type SkillServingMetadata, type SkillSource$1 as SkillSource, type SkillState, type SkillStatus, type SkillSummary, type SkillSyncState, type SkillTreeEvent, type SkillTreeEventHandler, type SkillUpstream, type SkillVersion, type SkillVisibility, type StorageAdapter, type StorageConfig, type StorageHookContext, type SyncBehaviorConfig, type SyncConfig, type ConflictResolution as SyncConflictResolution, type SyncError, SyncManager, type SyncManagerOptions, type SyncOptions, type SyncResult, type SyncState, type SyncStatus, type TaxonomyNode, type UpstreamUpdate, VERSION, type VersionChanges, type VersionDiff, ViewRenderer, type ViewRendererConfig, builtInProfiles, bumpVersion, codeReviewProfile, combineHandlers, compareVersions, conditionalHook, createAgentsGenerator, createAgentsParser, createAgentsSync, createBackupHook, createConflictStore, createDefaultSyncConfig, createFederationManager, createGitSyncAdapter, createLoggingHook, createSaveValidationHook, createSkillBank, createSkillMerger, createSyncManager, debuggingProfile, devopsProfile, discoverSkills, documentationProfile, formatVersion, generateAgentsMd, getBuiltInProfile, getLatestVersion, hasSkilltreeDir, hookRegistry, implementationProfile, importFromAgentsMd, inferBumpType, isValidVersion, listBuiltInProfiles, migrateStorage, parseVersion, refactoringProfile, satisfiesRange, securityProfile, sortVersions, testingProfile, writeAgentsMd };