/** * @kjerneverk/riotplan-format * * SQLite-based storage format for RiotPlan with dual format support. * * This package provides a storage abstraction layer that supports both * directory-based and SQLite .plan formats for RiotPlan plans. * * @packageDocumentation */ /** * Options for batch migration */ export declare interface BatchMigrationOptions extends MigrationOptions { /** Glob pattern for source plans */ pattern?: string; /** Maximum concurrent migrations */ concurrency?: number; /** Continue on individual failures */ continueOnError?: boolean; /** Target format for all migrations */ targetFormat?: StorageFormat; } /** * Result of batch migration */ export declare interface BatchMigrationResult { /** Total number of plans found */ totalPlans: number; /** Number of successful migrations */ successful: number; /** Number of failed migrations */ failed: number; /** Number of skipped migrations */ skipped: number; /** Individual migration results */ results: MigrationResult[]; /** Total duration in milliseconds */ duration: number; } /** * Checkpoint for saving plan state */ export declare interface Checkpoint { /** Checkpoint name */ name: string; /** Checkpoint message/description */ message: string; /** Creation timestamp (ISO 8601) */ createdAt: string; /** Snapshot of plan state at checkpoint time */ snapshot: CheckpointSnapshot; } /** * Snapshot of plan state for checkpoints */ export declare interface CheckpointSnapshot { /** Plan metadata at checkpoint time */ metadata: PlanMetadata; /** Step statuses at checkpoint time */ steps: Pick[]; /** Files included in checkpoint */ files: Pick[]; } /** * Create a directory storage provider * * @param planPath - Path to the plan directory * @returns A directory storage provider instance * * @remarks * This creates a base provider that throws "not implemented" errors. * Use the implementation from the main riotplan package for actual functionality. */ export declare function createDirectoryProvider(planPath: string): DirectoryStorageProvider; /** * Create a plan migrator */ export declare function createMigrator(): PlanMigrator; /** * Create a storage provider for the given path using default configuration * * This is a convenience function for simple use cases. * * @param planPath - Path to the plan * @param options - Optional creation options * @returns A storage provider instance */ export declare function createProvider(planPath: string, options?: CreateProviderOptions & { config?: Partial; }): StorageProvider; /** * Options for creating a storage provider */ export declare interface CreateProviderOptions { /** Force a specific format instead of auto-detecting */ format?: StorageFormat; /** Create the plan if it doesn't exist */ create?: boolean; } /** * Create a new SQLite storage provider */ export declare function createSqliteProvider(planPath: string): SqliteStorageProvider; /** * Create a storage provider factory with the given configuration * * @param config - Optional format configuration * @returns A storage provider factory */ export declare function createStorageFactory(config?: Partial): DefaultStorageProviderFactory; /** * Create a migration validator */ export declare function createValidator(): MigrationValidator; /** * Default directory configuration */ export declare const DEFAULT_DIRECTORY_CONFIG: Required; /** * Default format configuration */ export declare const DEFAULT_FORMAT_CONFIG: ResolvedFormatConfig; /** * Default SQLite configuration */ export declare const DEFAULT_SQLITE_CONFIG: Required; /** * Default storage provider factory implementation * * Creates appropriate storage providers based on path characteristics * and configuration preferences. */ export declare class DefaultStorageProviderFactory implements StorageProviderFactory { private config; constructor(config?: Partial); /** * Create a storage provider for the given path * * @param planPath - Path to the plan * @param options - Optional creation options * @returns A storage provider instance */ createProvider(planPath: string, options?: CreateProviderOptions): StorageProvider; /** * Check if this factory supports the given path * * @param planPath - Path to check * @returns True if a provider can be created for this path */ supportsPath(planPath: string): boolean; /** * Determine the format to use for a path * * @param planPath - The plan path * @param forcedFormat - Optional format override * @returns The format to use */ private determineFormat; /** * Get the default format from configuration */ get defaultFormat(): StorageFormat; /** * Get the SQLite configuration */ get sqliteConfig(): Required; /** * Get the directory configuration */ get directoryConfig(): Required; } /** * Detect the format of a plan at the given path * * @param planPath - Path to check * @returns The detected format or 'unknown' if not a valid plan */ export declare function detectPlanFormat(planPath: string): StorageFormat | 'unknown'; /** * Configuration options for directory storage */ export declare interface DirectoryConfig { /** Create plan subdirectory by default (default: true) */ usePlanSubdir?: boolean; /** Default directory permissions (default: '0755') */ permissions?: string; } /** * Directory-based storage provider * * This provider stores plans as a directory structure with markdown files. * The directory structure follows the RiotPlan convention: * * ``` * my-plan/ * ├── SUMMARY.md * ├── STATUS.md * ├── IDEA.md (optional) * ├── SHAPING.md (optional) * ├── EXECUTION_PLAN.md (optional) * ├── plan.yaml (contains metadata including UUID) * ├── plan/ * │ ├── 01-step-one.md * │ ├── 02-step-two.md * │ └── ... * ├── evidence/ * │ └── *.md * ├── feedback/ * │ └── *.md * ├── reflections/ * │ └── *.md * └── .history/ * ├── timeline.json * └── checkpoints/ * └── *.json * ``` * * @remarks * This is a base implementation that throws "not implemented" errors. * The main riotplan package should extend this class and implement * the methods using its existing file loading logic. * * **UUID Handling**: When implementing this provider, ensure that: * - UUIDs are generated using `generatePlanUuid()` from utils.ts if not provided * - UUIDs are persisted in plan.yaml metadata file * - UUIDs are included in PlanMetadata returned by getMetadata() */ export declare class DirectoryStorageProvider implements StorageProvider { readonly format: StorageFormat; readonly path: string; constructor(planPath: string); exists(): Promise; initialize(_metadata: PlanMetadata): Promise>; close(): Promise; getMetadata(): Promise>; updateMetadata(_updates: Partial): Promise>; getSteps(): Promise>; getStep(_number: number): Promise>; addStep(_step: PlanStep): Promise>; updateStep(_number: number, _updates: Partial): Promise>; deleteStep(_number: number): Promise>; getFiles(): Promise>; getFile(_type: string, _filename: string): Promise>; saveFile(_file: PlanFile): Promise>; deleteFile(_type: string, _filename: string): Promise>; getTimelineEvents(): Promise>; addTimelineEvent(_event: TimelineEvent): Promise>; getEvidence(): Promise>; addEvidence(_evidence: EvidenceRecord): Promise>; getFeedback(): Promise>; addFeedback(_feedback: FeedbackRecord): Promise>; getCheckpoints(): Promise>; getCheckpoint(_name: string): Promise>; createCheckpoint(_checkpoint: Checkpoint): Promise>; restoreCheckpoint(_name: string): Promise>; search(_query: string): Promise>; createSnapshot(): Promise; } /** * Ensure a path has the correct extension for the format * * @param planPath - The plan path * @param format - The storage format * @param config - Optional format configuration * @returns The path with the correct extension */ export declare function ensureFormatExtension(planPath: string, format: StorageFormat, config?: FormatConfig): string; /** * Evidence record stored in the database */ export declare interface EvidenceRecord { /** Evidence ID */ id: string; /** Evidence description */ description: string; /** Source of the evidence */ source?: string; /** Source URL if applicable */ sourceUrl?: string; /** How the evidence was gathered */ gatheringMethod?: 'manual' | 'model-assisted'; /** Evidence content (for inline evidence) */ content?: string; /** Path to evidence file (for file-based evidence) */ filePath?: string; /** Relevance score (0-1) from model if model-assisted */ relevanceScore?: number; /** Original question or search query that prompted gathering this evidence */ originalQuery?: string; /** Model-generated summary of the evidence */ summary?: string; /** Creation timestamp (ISO 8601) */ createdAt: string; } /** * Feedback record stored in the database */ export declare interface FeedbackRecord { /** Feedback ID */ id: string; /** Feedback title */ title?: string; /** Platform where feedback was given */ platform?: string; /** Feedback content */ content: string; /** Participants in the feedback session */ participants?: string[]; /** Creation timestamp (ISO 8601) */ createdAt: string; } /** * Format-related configuration for RiotPlan */ export declare interface FormatConfig { /** Default plan storage format (default: 'directory') */ defaultFormat?: StorageFormat; /** SQLite-specific options */ sqlite?: SqliteConfig; /** Directory-specific options */ directory?: DirectoryConfig; } /** * Format a plan filename using UUID abbreviation and slug * * @param uuid - The plan UUID * @param slug - The plan slug (code) * @returns Formatted filename: {uuid-abbrev}-{slug}.plan */ export declare function formatPlanFilename(uuid: string, slug: string): string; /** * Generate a new plan UUID * * @returns A new UUID v4 string */ export declare function generatePlanUuid(): string; /** * Generate a target path based on source path and target format */ export declare function generateTargetPath(sourcePath: string, sourceFormat: StorageFormat, targetFormat: StorageFormat): string; /** * Get the appropriate file extension for a format * * @param format - The storage format * @param config - Optional format configuration * @returns The file extension (empty string for directory format) */ export declare function getFormatExtension(format: StorageFormat, config?: FormatConfig): string; /** * Get plan name from path * * @param planPath - The plan path * @param format - The storage format * @param config - Optional format configuration * @returns The plan name extracted from the path */ export declare function getPlanNameFromPath(planPath: string, format: StorageFormat, config?: FormatConfig): string; /** * Check if a file has a valid SQLite header * * @param filePath - Path to the file * @returns True if the file starts with SQLite magic bytes */ export declare function hasSqliteHeader(filePath: string): boolean; /** * Infer the format from a path based on extension and existence * * @param planPath - The plan path * @param config - Optional format configuration * @returns The inferred format */ export declare function inferFormatFromPath(planPath: string, config?: FormatConfig): StorageFormat; /** * Infer target format from source format (opposite format) */ export declare function inferTargetFormat(sourceFormat: StorageFormat): StorageFormat; /** * Check if a path looks like it should be a directory plan * * @param planPath - Path to check * @returns True if the path exists and is a directory, or doesn't have a file extension */ export declare function isDirectoryPath(planPath: string): boolean; /** * Check if a path looks like it should be a SQLite plan file * * @param planPath - Path to check * @param config - Optional format configuration * @returns True if the path has a SQLite plan extension */ export declare function isSqlitePath(planPath: string, config?: FormatConfig): boolean; /** * Options for markdown rendering */ export declare interface MarkdownRenderOptions { /** Include timeline events in output */ includeTimeline?: boolean; /** Include evidence records */ includeEvidence?: boolean; /** Include feedback records */ includeFeedback?: boolean; /** Include source format metadata */ includeSourceInfo?: boolean; } /** * Merge user config with defaults */ export declare function mergeFormatConfig(userConfig?: Partial): ResolvedFormatConfig; /** * Options for migration operations */ export declare interface MigrationOptions { /** Overwrite destination if it exists */ force?: boolean; /** Preserve source after migration */ keepSource?: boolean; /** Validate data integrity after migration */ validate?: boolean; /** Progress callback */ onProgress?: (progress: MigrationProgress) => void; } /** * Progress information during migration */ export declare interface MigrationProgress { /** Current phase */ phase: 'reading' | 'converting' | 'writing' | 'validating'; /** Progress percentage (0-100) */ percentage: number; /** Current item being processed */ currentItem?: string; /** Total items to process */ totalItems?: number; /** Items processed so far */ processedItems?: number; } /** * Result of a migration operation */ export declare interface MigrationResult { /** Whether the migration succeeded */ success: boolean; /** Source format */ sourceFormat: StorageFormat; /** Target format */ targetFormat: StorageFormat; /** Source path */ sourcePath: string; /** Target path */ targetPath: string; /** Error message if failed */ error?: string; /** Warning messages */ warnings: string[]; /** Migration statistics */ stats: MigrationStats; /** Duration in milliseconds */ duration: number; } /** * Statistics from a migration operation */ export declare interface MigrationStats { /** Number of steps converted */ stepsConverted: number; /** Number of files converted */ filesConverted: number; /** Number of timeline events converted */ timelineEventsConverted: number; /** Number of evidence records converted */ evidenceConverted: number; /** Number of feedback records converted */ feedbackConverted: number; /** Number of checkpoints converted */ checkpointsConverted: number; } /** * Validates migration fidelity between source and target */ export declare class MigrationValidator { /** * Validate that target contains all data from source */ validate(source: StorageProvider, target: StorageProvider): Promise; private validateMetadata; private validateSteps; private validateFiles; private validateTimeline; private validateEvidence; private validateFeedback; } /** * File extension for SQLite plan files */ export declare const PLAN_FILE_EXTENSION = ".plan"; /** * Plan file stored in the database */ export declare interface PlanFile { /** File type identifier */ type: PlanFileType; /** Original filename */ filename: string; /** File content (markdown/text) */ content: string; /** Creation timestamp (ISO 8601) */ createdAt: string; /** Last update timestamp (ISO 8601) */ updatedAt: string; } /** * Known plan file types */ export declare type PlanFileType = 'idea' | 'shaping' | 'summary' | 'execution_plan' | 'status' | 'provenance' | 'lifecycle' | 'evidence' | 'feedback' | 'prompt' | 'reflection' | 'other'; /** * Plan metadata stored in the database */ export declare interface PlanMetadata { /** Unique plan identifier (code) */ id: string; /** Globally unique identifier */ uuid: string; /** Human-readable plan name */ name: string; /** Plan description */ description?: string; /** Creation timestamp (ISO 8601) */ createdAt: string; /** Last update timestamp (ISO 8601) */ updatedAt: string; /** Current lifecycle stage */ stage: PlanStage; /** Schema version for migrations */ schemaVersion: number; } /** * Migrates plans between directory and SQLite formats */ export declare class PlanMigrator { private validator; constructor(); /** * Migrate a plan from source to target format * * @param sourcePath - Path to source plan * @param targetPath - Path for target plan * @param sourceProvider - Provider for reading source * @param targetProvider - Provider for writing target * @param options - Migration options */ migrate(sourcePath: string, targetPath: string, sourceProvider: StorageProvider, targetProvider: StorageProvider, options?: MigrationOptions): Promise; private migrateSteps; private migrateFiles; private migrateTimeline; private migrateEvidence; private migrateFeedback; private migrateCheckpoints; private deleteSource; private reportProgress; } /** * Plan lifecycle stages */ export declare type PlanStage = 'idea' | 'shaping' | 'built' | 'executing' | 'completed' | 'cancelled'; /** * Plan step stored in the database */ export declare interface PlanStep { /** Step number (1-based) */ number: number; /** Step code/identifier */ code: string; /** Step title */ title: string; /** Step description/objective */ description?: string; /** Step status */ status: StepStatus; /** When the step was started (ISO 8601) */ startedAt?: string; /** When the step was completed (ISO 8601) */ completedAt?: string; /** Full markdown content of the step file */ content: string; } /** * Rendered plan as markdown files */ export declare interface RenderedPlan { /** Main files (SUMMARY.md, STATUS.md, etc.) */ files: Map; /** Step files (plan/01-step.md, etc.) */ steps: Map; /** Evidence files (evidence/*.md) */ evidence: Map; /** Feedback files (feedback/*.md) */ feedback: Map; } /** * Render a plan to markdown format */ export declare function renderPlanToMarkdown(provider: StorageProvider, options?: MarkdownRenderOptions): Promise; /** * Resolved format configuration with all fields required */ export declare interface ResolvedFormatConfig { defaultFormat: StorageFormat; sqlite: Required; directory: Required; } /** * Current SQLite schema version */ export declare const SCHEMA_VERSION = 1; /** * Search result from content search */ export declare interface SearchResult { /** Type of content found */ type: 'step' | 'file' | 'evidence' | 'feedback' | 'timeline'; /** Identifier (step number, filename, etc.) */ id: string; /** Matching content snippet */ snippet: string; /** Relevance score (0-1) */ score: number; } /** * Configuration options for SQLite storage */ export declare interface SqliteConfig { /** Enable WAL mode for better concurrency (default: true) */ walMode?: boolean; /** SQLite pragma settings */ pragmas?: Record; /** File extension for SQLite plan files (default: '.plan') */ extension?: string; } /** * SQLite-based storage provider for .plan files */ export declare class SqliteStorageProvider implements StorageProvider { readonly format: "sqlite"; readonly path: string; private db; private planId; constructor(planPath: string); /** * Initialize the database with schema */ private initializeSchema; /** * Get the plan ID, loading it if necessary */ private getPlanId; exists(): Promise; initialize(metadata: PlanMetadata): Promise>; close(): Promise; getMetadata(): Promise>; updateMetadata(metadata: Partial): Promise>; getSteps(): Promise>; getStep(number: number): Promise>; addStep(step: PlanStep): Promise>; updateStep(number: number, updates: Partial): Promise>; deleteStep(number: number): Promise>; getFiles(): Promise>; getFile(type: string, filename: string): Promise>; saveFile(file: PlanFile): Promise>; deleteFile(type: string, filename: string): Promise>; getTimelineEvents(options?: { since?: string; type?: string; limit?: number; }): Promise>; addTimelineEvent(event: TimelineEvent): Promise>; getEvidence(): Promise>; addEvidence(evidence: EvidenceRecord): Promise>; getFeedback(): Promise>; addFeedback(feedback: FeedbackRecord): Promise>; getCheckpoints(): Promise>; getCheckpoint(name: string): Promise>; createCheckpoint(checkpoint: Checkpoint): Promise>; restoreCheckpoint(name: string): Promise>; search(query: string): Promise>; private extractSnippet; private calculateScore; /** * Create a snapshot of the current plan state for checkpoints */ createSnapshot(): Promise; } /** * Step status values */ export declare type StepStatus = 'pending' | 'in_progress' | 'completed' | 'skipped'; /** * Storage format types for RiotPlan * * This module defines the core types for the dual-format storage architecture * that supports both directory-based and SQLite .plan formats. */ /** * Supported storage formats */ export declare type StorageFormat = 'directory' | 'sqlite'; /** * Options for storage operations */ export declare interface StorageOptions { /** Storage format to use */ format?: StorageFormat; /** Create if not exists */ create?: boolean; /** Schema version to use (for migrations) */ schemaVersion?: number; } /** * Abstract storage provider interface * * Both DirectoryStorageProvider and SqliteStorageProvider implement this interface, * allowing the plan operations to work with either format transparently. */ export declare interface StorageProvider { /** * Get the storage format this provider uses */ readonly format: StorageFormat; /** * Get the path to the plan (directory path or .plan file path) */ readonly path: string; /** * Check if the plan exists */ exists(): Promise; /** * Initialize a new plan */ initialize(metadata: PlanMetadata): Promise>; /** * Close the storage (cleanup resources) */ close(): Promise; /** * Get plan metadata */ getMetadata(): Promise>; /** * Update plan metadata */ updateMetadata(metadata: Partial): Promise>; /** * Get all steps */ getSteps(): Promise>; /** * Get a specific step by number */ getStep(number: number): Promise>; /** * Add a new step */ addStep(step: PlanStep): Promise>; /** * Update an existing step */ updateStep(number: number, updates: Partial): Promise>; /** * Delete a step */ deleteStep(number: number): Promise>; /** * Get all files */ getFiles(): Promise>; /** * Get a specific file by type and filename */ getFile(type: string, filename: string): Promise>; /** * Save a file */ saveFile(file: PlanFile): Promise>; /** * Delete a file */ deleteFile(type: string, filename: string): Promise>; /** * Get timeline events */ getTimelineEvents(options?: { since?: string; type?: string; limit?: number; }): Promise>; /** * Add a timeline event */ addTimelineEvent(event: TimelineEvent): Promise>; /** * Get all evidence records */ getEvidence(): Promise>; /** * Add an evidence record */ addEvidence(evidence: EvidenceRecord): Promise>; /** * Get all feedback records */ getFeedback(): Promise>; /** * Add a feedback record */ addFeedback(feedback: FeedbackRecord): Promise>; /** * Get all checkpoints */ getCheckpoints(): Promise>; /** * Get a specific checkpoint by name */ getCheckpoint(name: string): Promise>; /** * Create a checkpoint */ createCheckpoint(checkpoint: Checkpoint): Promise>; /** * Restore from a checkpoint */ restoreCheckpoint(name: string): Promise>; /** * Search across all plan content */ search(query: string): Promise>; } /** * Interface for storage provider factories */ export declare interface StorageProviderFactory { /** * Create a storage provider for the given path */ createProvider(path: string, options?: unknown): StorageProvider; /** * Check if this factory supports the given path */ supportsPath(path: string): boolean; } /** * Factory function type for creating storage providers */ export declare type StorageProviderFactoryFn = (path: string) => Promise; /** * Result of a storage operation */ export declare interface StorageResult { /** Whether the operation succeeded */ success: boolean; /** Result data if successful */ data?: T; /** Error message if failed */ error?: string; } /** * Timeline event stored in the database */ export declare interface TimelineEvent { /** Event ID */ id: string; /** Event timestamp (ISO 8601) */ timestamp: string; /** Event type */ type: TimelineEventType; /** Event data (JSON) */ data: Record; } /** * Timeline event types */ export declare type TimelineEventType = 'plan_created' | 'stage_transition' | 'step_started' | 'step_completed' | 'note_added' | 'constraint_added' | 'question_added' | 'evidence_added' | 'approach_added' | 'approach_selected' | 'feedback_added' | 'checkpoint_created' | 'narrative_added' | 'reflection_added'; /** * Validate that a plan path is valid for the given format * * @param planPath - The plan path * @param format - The expected format * @param config - Optional format configuration * @returns An error message if invalid, or null if valid */ export declare function validatePlanPath(planPath: string, format: StorageFormat, config?: FormatConfig): string | null; /** * Validation error during migration */ export declare interface ValidationError { /** Type of validation error */ type: 'missing_step' | 'content_mismatch' | 'metadata_difference' | 'missing_file' | 'missing_event'; /** Path or identifier of the problematic item */ path: string; /** Expected value */ expected: unknown; /** Actual value */ actual: unknown; /** Human-readable error message */ message: string; } /** * Result of migration validation */ export declare interface ValidationResult { /** Whether validation passed */ valid: boolean; /** Validation errors */ errors: ValidationError[]; /** Warning messages */ warnings: string[]; /** Validation statistics */ stats: { stepsCompared: number; filesCompared: number; timelineEventsCompared: number; evidenceCompared: number; feedbackCompared: number; }; } /** * Package version */ export declare const VERSION = "1.0.0-dev.0"; export { }