speckeeper 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types/common.ts","../src/types/meta-model.ts","../src/core/relation.ts","../src/core/model.ts","../src/core/model-registry.ts","../src/core/config-api.ts","../src/utils/config-loader.ts","../src/utils/file-writer.ts"],"names":["z","parseYaml","existsSync","dirname","readFileSync","join"],"mappings":";;;;;;;;AAMO,IAAM,WAAA,GAAc,CAAA,CAAE,IAAA,CAAK,CAAC,KAAA,EAAO,OAAO,KAAA,EAAO,MAAA,EAAQ,KAAA,EAAO,IAAI,CAAC;AAGrE,IAAM,cAAA,GAAiB,EAAE,IAAA,CAAK,CAAC,QAAQ,QAAA,EAAU,OAAA,EAAS,MAAM,CAAC;AAiCjE,IAAM,mBAAA,GAAsB,CAAC,EAAA,KAA8B;AAC3D,IAAM,iBAAA,GAAoB,CAAC,EAAA,KAA4B;AACvD,IAAM,gBAAA,GAAmB,CAAC,EAAA,KAA2B;AACrD,IAAM,aAAA,GAAgB,CAAC,EAAA,KAAwB;AAC/C,IAAM,cAAA,GAAiB,CAAC,EAAA,KAAyB;AACjD,IAAM,gBAAA,GAAmB,CAAC,EAAA,KAA2B;AACrD,IAAM,YAAA,GAAe,CAAC,EAAA,KAAuB;AAC7C,IAAM,cAAA,GAAiB,CAAC,EAAA,KAAyB;AACjD,IAAM,kBAAA,GAAqB,CAAC,EAAA,KAA6B;AACzD,IAAM,YAAA,GAAe,CAAC,EAAA,KAAuB;AAC7C,IAAM,mBAAA,GAAsB,CAAC,EAAA,KAA8B;AAC3D,IAAM,mBAAA,GAAsB,CAAC,EAAA,KAA8B;AAC3D,IAAM,eAAA,GAAkB,CAAC,EAAA,KAA0B;AACnD,IAAM,aAAA,GAAgB,CAAC,EAAA,KAAwB;AAC/C,IAAM,sBAAA,GAAyB,CAAC,EAAA,KAAiC;AACj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M,QAAQ,CAAC,WAAA,EAAa,aAAa,CAAA,EAAG,CAAA;AAC/E;AAMO,SAAS,gBAAA,CACd,OAAA,EACA,QAAA,EACA,QAAA,EACQ;AACR,EAAA,OAAOA,IAAAA,CAAK,OAAA,EAAS,QAAA,EAAU,QAAQ,CAAA;AACzC;AAEO,SAAS,iBAAA,CACd,OAAA,EACA,QAAA,EACA,QAAA,EACQ;AACR,EAAA,OAAOA,IAAAA,CAAK,OAAA,EAAS,QAAA,EAAU,QAAQ,CAAA;AACzC","file":"index.js","sourcesContent":["import { z } from 'zod';\n\n// ============================================================================\n// Phase definitions\n// ============================================================================\n\nexport const PhaseSchema = z.enum(['REQ', 'HLD', 'LLD', 'IMPL', 'OPS', 'CI']);\nexport type Phase = z.infer<typeof PhaseSchema>;\n\nexport const PrioritySchema = z.enum(['must', 'should', 'could', 'wont']);\nexport type Priority = z.infer<typeof PrioritySchema>;\n\n// ============================================================================\n// ID types (using simple string types for now)\n// ============================================================================\n\n// ID types - all are strings with semantic meaning\nexport type RequirementId = string;\nexport type ComponentId = string;\nexport type BoundaryId = string;\nexport type LayerId = string;\nexport type EntityId = string;\nexport type RelationId = string;\nexport type RuleId = string;\nexport type ScreenId = string;\nexport type TransitionId = string;\nexport type FormId = string;\nexport type UIComponentId = string;\nexport type ProcessFlowId = string;\nexport type UseCaseId = string;\nexport type ActorId = string;\nexport type DTORequirementId = string;\nexport type EventRequirementId = string;\nexport type APIRefId = string;\nexport type TableRefId = string;\nexport type IaCRefId = string;\nexport type BatchRefId = string;\nexport type ErrorCaseId = string;\nexport type TermId = string;\nexport type StateId = string;\n\n// ID creation helpers (no-op for now, but preserves API for future branding)\nexport const createRequirementId = (id: string): RequirementId => id;\nexport const createComponentId = (id: string): ComponentId => id;\nexport const createBoundaryId = (id: string): BoundaryId => id;\nexport const createLayerId = (id: string): LayerId => id;\nexport const createEntityId = (id: string): EntityId => id;\nexport const createRelationId = (id: string): RelationId => id;\nexport const createRuleId = (id: string): RuleId => id;\nexport const createScreenId = (id: string): ScreenId => id;\nexport const createTransitionId = (id: string): TransitionId => id;\nexport const createFormId = (id: string): FormId => id;\nexport const createUIComponentId = (id: string): UIComponentId => id;\nexport const createProcessFlowId = (id: string): ProcessFlowId => id;\nexport const createUseCaseId = (id: string): UseCaseId => id;\nexport const createActorId = (id: string): ActorId => id;\nexport const createDTORequirementId = (id: string): DTORequirementId => id;\nexport const createEventRequirementId = (id: string): EventRequirementId => id;\nexport const createAPIRefId = (id: string): APIRefId => id;\nexport const createTableRefId = (id: string): TableRefId => id;\nexport const createIaCRefId = (id: string): IaCRefId => id;\nexport const createBatchRefId = (id: string): BatchRefId => id;\nexport const createErrorCaseId = (id: string): ErrorCaseId => id;\nexport const createTermId = (id: string): TermId => id;\nexport const createStateId = (id: string): StateId => id;\n\n// ============================================================================\n// ID Pattern definitions\n// ============================================================================\n\nexport const ID_PATTERNS = {\n requirement: /^REQ-[A-Z]+-\\d{6}-[A-Z0-9]{4}$/,\n component: /^COMP-[A-Z]+-[A-Z0-9-]+$/,\n boundary: /^BND-[A-Z]+-[A-Z0-9-]+$/,\n layer: /^LAYER-[A-Z]+$/,\n entity: /^ENT-[A-Z]+-?[A-Z0-9-]*$/,\n relation: /^REL-[A-Z]+-[A-Z0-9-]+$/,\n rule: /^RULE-[A-Z0-9-]+$/,\n screen: /^SCR-[A-Z]+-?[A-Z0-9-]*$/,\n transition: /^TRANS-[A-Z0-9-]+$/,\n form: /^FORM-[A-Z0-9-]+$/,\n uiComponent: /^UI-[A-Z0-9-]+$/,\n processFlow: /^FLOW-[A-Z]+-[A-Z0-9-]+$/,\n useCase: /^UC-[A-Z]+-\\d{3}$/,\n actor: /^ACTOR-[A-Z]+$/,\n dtoRequirement: /^DTO-REQ-[A-Z0-9-]+$/,\n eventRequirement: /^EVT-REQ-[A-Z0-9-]+$/,\n apiRef: /^API-[A-Z0-9-]+$/,\n tableRef: /^TBL-[A-Z0-9-]+$/,\n iacRef: /^IAC-[A-Z0-9-]+$/,\n batchRef: /^BATCH-[A-Z0-9-]+$/,\n errorCase: /^ERR-[A-Z]+-\\d{3}$/,\n term: /^TERM-[A-Z0-9-]+$/,\n} as const;\n\n// ============================================================================\n// Concretization Slot (TBD management)\n// ============================================================================\n\nexport const ConcretizationSlotSchema = z.object({\n field: z.string(),\n mustDecideBy: PhaseSchema,\n value: z.union([z.string(), z.null()]).optional(),\n description: z.string().optional(),\n});\n\nexport type ConcretizationSlot = z.infer<typeof ConcretizationSlotSchema>;\n\n// ============================================================================\n// Link types\n// ============================================================================\n\nexport interface Link {\n type: 'requirement' | 'component' | 'entity' | 'screen' | 'usecase' | 'external';\n id: string;\n label?: string;\n}\n\nexport const LinkSchema = z.object({\n type: z.enum(['requirement', 'component', 'entity', 'screen', 'usecase', 'external']),\n id: z.string(),\n label: z.string().optional(),\n});\n\n// ============================================================================\n// Validation result types\n// ============================================================================\n\nexport type Severity = 'error' | 'warning' | 'info';\n\nexport interface ValidationError {\n severity: Severity;\n code: string;\n message: string;\n path?: string;\n id?: string;\n suggestions?: string[];\n}\n\nexport interface ValidationResult {\n valid: boolean;\n errors: ValidationError[];\n warnings: ValidationError[];\n}\n\n// ============================================================================\n// Generic model registry (Type definition)\n// Note: Implementation is in utils/model-loader.ts\n// ============================================================================\n\nexport interface ModelRegistrySchema {\n requirements: Map<RequirementId, unknown>;\n components: Map<ComponentId, unknown>;\n boundaries: Map<BoundaryId, unknown>;\n layers: Map<LayerId, unknown>;\n entities: Map<EntityId, unknown>;\n relations: Map<RelationId, unknown>;\n rules: Map<RuleId, unknown>;\n screens: Map<ScreenId, unknown>;\n transitions: Map<TransitionId, unknown>;\n forms: Map<FormId, unknown>;\n uiComponents: Map<UIComponentId, unknown>;\n processFlows: Map<ProcessFlowId, unknown>;\n useCases: Map<UseCaseId, unknown>;\n actors: Map<ActorId, unknown>;\n dtoRequirements: Map<DTORequirementId, unknown>;\n eventRequirements: Map<EventRequirementId, unknown>;\n apiRefs: Map<APIRefId, unknown>;\n tableRefs: Map<TableRefId, unknown>;\n iacRefs: Map<IaCRefId, unknown>;\n batchRefs: Map<BatchRefId, unknown>;\n errorCases: Map<ErrorCaseId, unknown>;\n terms: Map<TermId, unknown>;\n}\n","import { z } from 'zod';\n\n// ============================================================================\n// Meta Model Types - Types for defining models\n// ============================================================================\n\n/**\n * Export Context\n * Context information passed to exporter functions\n */\nexport interface ExportContext {\n /** Access to all models (MetaModelRegistry type, using unknown to avoid circular references) */\n registry: unknown;\n /** Configuration (SpeckeeperConfig type, using unknown to avoid circular references) */\n config: unknown;\n /** Output base directory */\n outputDir: string;\n /** Current date/time */\n generatedAt: Date;\n}\n\n/**\n * Lint Context\n * Context information passed to lint functions\n */\nexport interface LintContext {\n /** Access to all models (MetaModelRegistry type) */\n registry: unknown;\n /** Current phase */\n phase?: 'REQ' | 'HLD' | 'LLD' | 'OPS';\n /** Strict mode */\n strict?: boolean;\n}\n\n/**\n * Check Context\n * Context information passed to external SSOT check functions\n */\nexport interface CheckContext {\n /** Access to all models (MetaModelRegistry type) */\n registry: unknown;\n /** External SSOT file path */\n sourcePath: string;\n /** Configuration (SpeckeeperConfig type) */\n config: unknown;\n}\n\n/**\n * Lint Issue\n */\nexport interface LintIssue {\n /** Issue message */\n message: string;\n /** Problematic field (optional) */\n field?: string;\n /** Fix suggestion (optional) */\n suggestion?: string;\n}\n\n/**\n * Check Result\n */\nexport interface CheckResult {\n /** Whether successful */\n success: boolean;\n /** List of error messages */\n errors: CheckError[];\n /** List of warning messages */\n warnings: CheckWarning[];\n}\n\nexport interface CheckError {\n /** Error message */\n message: string;\n /** Target model ID */\n modelId: string;\n /** External SSOT reference */\n externalRef?: string;\n}\n\nexport interface CheckWarning {\n /** Warning message */\n message: string;\n /** Target model ID */\n modelId: string;\n}\n\n// ============================================================================\n// Exporter Interfaces\n// ============================================================================\n\n/**\n * Markdown Exporter\n */\nexport interface MarkdownExporter<T> {\n /** Single document generation */\n single: (model: T, context: ExportContext) => string;\n /** Index page generation (optional) */\n index?: (models: T[], context: ExportContext) => string;\n /** Output directory (relative path from docs/) */\n outputDir: string;\n /** Filename generation (default is model.id) */\n filename?: (model: T) => string;\n}\n\n/**\n * Mermaid Diagram Exporter\n */\nexport interface MermaidExporter<T> {\n /** Diagram type */\n diagramType: 'flowchart' | 'sequenceDiagram' | 'erDiagram' | 'stateDiagram' | 'C4Context' | 'C4Container' | 'C4Component' | 'custom';\n /** Diagram generation function */\n generate: (models: T[], context: ExportContext) => string;\n /** Output file path (relative path from docs/) */\n outputPath: string;\n /** Diagram title */\n title?: string;\n}\n\n/**\n * JSON Schema Exporter Settings\n */\nexport interface JsonSchemaExporter {\n /** Enabled */\n enabled: boolean;\n /** Output directory (relative path from specs/) */\n outputDir: string;\n}\n\n// ============================================================================\n// Lint Rule Interface\n// ============================================================================\n\n/**\n * Lint Rule\n */\nexport interface LintRule<T> {\n /** Rule ID */\n id: string;\n /** Rule description */\n description: string;\n /** Severity */\n severity: 'error' | 'warning' | 'info';\n /** Check function */\n check: (model: T, context: LintContext) => LintIssue | null;\n}\n\n// ============================================================================\n// External Checker Interface\n// ============================================================================\n\n/**\n * External SSOT Checker\n */\nexport interface ExternalChecker<T> {\n /** External SSOT type to check */\n targetType: 'openapi' | 'ddl' | 'iac' | 'custom';\n /** Execute check */\n check: (model: T, externalSource: unknown, context: CheckContext) => CheckResult;\n /** Get external SSOT file path (from model) */\n getSourcePath?: (model: T) => string | undefined;\n}\n\n// ============================================================================\n// Reference Definition\n// ============================================================================\n\n/**\n * Inter-model Reference Definition (for traceability)\n */\nexport interface ReferenceDefinition {\n /** Field name with reference */\n field: string;\n /** Referenced model ID */\n targetModel: string;\n /** Whether reference is required */\n required?: boolean;\n /** Whether reference is array */\n isArray?: boolean;\n}\n\n// ============================================================================\n// Model Definition Interface\n// ============================================================================\n\n/**\n * Model Definition\n * Interface for users to define new entities\n */\nexport interface ModelDefinition<T extends z.ZodTypeAny = z.ZodTypeAny> {\n /** Model unique identifier (kebab-case recommended) */\n id: string;\n /** Model name (PascalCase recommended) */\n name: string;\n /** Model description */\n description: string;\n \n /** Zod Schema */\n schema: T;\n \n /** ID prefix for generation */\n idPrefix: string;\n \n /** Exporter settings */\n exporters?: {\n /** Markdown exporter */\n markdown?: MarkdownExporter<z.infer<T>>;\n /** Mermaid diagram exporter (multiple allowed) */\n mermaid?: MermaidExporter<z.infer<T>> | MermaidExporter<z.infer<T>>[];\n /** JSON Schema exporter */\n jsonSchema?: JsonSchemaExporter;\n };\n \n /** Lint rules */\n lintRules?: LintRule<z.infer<T>>[];\n \n /** External SSOT checker */\n externalChecker?: ExternalChecker<z.infer<T>>;\n \n /** Reference definitions (for traceability) */\n references?: ReferenceDefinition[];\n \n /** DSL function name (the Xxx part of defineXxx) */\n dslName?: string;\n \n /** Phase (the phase where this model is primarily used) */\n phase?: 'REQ' | 'HLD' | 'LLD' | 'OPS';\n}\n\n// ============================================================================\n// Model Registry Interface\n// ============================================================================\n\n/**\n * Meta Model Registry\n * Manages registered model definitions and model instances\n */\nexport interface MetaModelRegistry {\n /** Registered model definitions */\n definitions: Map<string, ModelDefinition>;\n /** Model instances (Map<instanceId, instance> for each model ID) */\n instances: Map<string, Map<string, unknown>>;\n}\n\n// ============================================================================\n// Meta Config Interface (extends base config)\n// ============================================================================\n\n/**\n * Additional settings for meta model\n */\nexport interface MetaModelConfig {\n /** Custom model definitions */\n models?: ModelDefinition[];\n /** External SSOT settings */\n externalSsot?: {\n openapi?: {\n enabled: boolean;\n paths: string[];\n };\n ddl?: {\n enabled: boolean;\n type: 'ddl' | 'prisma' | 'typeorm' | 'drizzle';\n path: string;\n };\n iac?: {\n enabled: boolean;\n type: 'cloudformation' | 'cdk' | 'terraform';\n path: string;\n };\n };\n}\n\n// ============================================================================\n// Helper Types\n// ============================================================================\n\n/**\n * Base type for model instances\n * All model instances have an id\n */\nexport interface BaseModelInstance {\n id: string;\n}\n\n/**\n * Helper type for creating type-safe model definitions\n */\nexport type InferModelType<T extends ModelDefinition> = z.infer<T['schema']>;\n\n// ============================================================================\n// Zod Schemas for Meta Types\n// ============================================================================\n\nexport const ReferenceDefinitionSchema = z.object({\n field: z.string(),\n targetModel: z.string(),\n required: z.boolean().optional(),\n isArray: z.boolean().optional(),\n});\n\nexport const LintIssueSchema = z.object({\n message: z.string(),\n field: z.string().optional(),\n suggestion: z.string().optional(),\n});\n\nexport const CheckErrorSchema = z.object({\n message: z.string(),\n modelId: z.string(),\n externalRef: z.string().optional(),\n});\n\nexport const CheckWarningSchema = z.object({\n message: z.string(),\n modelId: z.string(),\n});\n\nexport const CheckResultSchema = z.object({\n success: z.boolean(),\n errors: z.array(CheckErrorSchema),\n warnings: z.array(CheckWarningSchema),\n});\n","/**\n * Definition and validation of model relations\n */\nimport { z } from 'zod';\n\n// ============================================================================\n// Model Levels\n// ============================================================================\n\n/**\n * Model abstraction level\n * \n * - L0: Business + Domain Analysis (Why / Problem space)\n * Desired outcomes/value, business flows, actors, terminology, business rules\n * - L1: Requirements (What)\n * Functional/non-functional requirements, constraints, acceptance criteria\n * - L2: Design (How / Direction)\n * Architecture, component breakdown, domain model, key sequences\n * - L3: Detailed Design/Implementation (How to build / Concrete artifacts)\n * Screen/API/DB definitions, external SSOT references\n */\nexport type ModelLevel = 'L0' | 'L1' | 'L2' | 'L3';\n\n/**\n * Get numeric index of level\n */\nexport function getLevelIndex(level: ModelLevel): number {\n return ['L0', 'L1', 'L2', 'L3'].indexOf(level);\n}\n\n// ============================================================================\n// Relation Types\n// ============================================================================\n\n/**\n * Relation types\n */\nexport const RELATION_TYPES = [\n 'dependsOn',\n 'uses',\n 'includes',\n 'implements',\n 'refines',\n 'verifies',\n 'satisfies',\n 'traces',\n 'relatedTo',\n] as const;\n\nexport type RelationType = typeof RELATION_TYPES[number];\n\n/**\n * Relation schema\n */\nexport const RelationSchema = z.object({\n /** Relation type */\n type: z.enum(RELATION_TYPES),\n /** Target ID */\n target: z.string(),\n /** Description (optional) */\n description: z.string().optional(),\n});\n\n/**\n * Relation field to add to model schemas\n * Usage: schema.extend({ relations: RelationsFieldSchema })\n */\nexport const RelationsFieldSchema = z.array(RelationSchema).optional();\n\nexport type Relation = z.infer<typeof RelationSchema>;\n\n// ============================================================================\n// Relation Constraints\n// ============================================================================\n\n/**\n * Definition of relation constraints\n */\nexport interface RelationConstraint {\n /** Allowed target levels (all levels allowed if not specified) */\n allowedTargetLevels?: ModelLevel[];\n /** Level constraint rule */\n levelRule: 'source>target' | 'source>=target' | 'same' | 'any';\n /** Direction of impact propagation */\n propagation: 'forward' | 'backward' | 'both';\n}\n\n/**\n * Constraint definitions per relation type\n * \n * Level hierarchy:\n * L0 (Business) → L1 (Requirements) → L2 (Design) → L3 (Implementation)\n * Abstract ───────────────────────────→ Concrete\n */\nexport const RELATION_CONSTRAINTS: Record<RelationType, RelationConstraint> = {\n // Concrete→Abstract (implementation/design fulfills requirements)\n 'implements': {\n allowedTargetLevels: ['L1'], // Implements requirements\n levelRule: 'source>target',\n propagation: 'forward', // A changes → B needs review\n },\n // Concrete→Abstract (design/implementation satisfies business/requirements)\n 'satisfies': {\n allowedTargetLevels: ['L0', 'L1'], // Satisfies business/requirements\n levelRule: 'source>=target',\n propagation: 'backward', // B changes → A needs update\n },\n // Concrete→Abstract (refinement: requirements refine business, design refines requirements)\n 'refines': {\n allowedTargetLevels: ['L0', 'L1'], // Refines business/requirements\n levelRule: 'source>target',\n propagation: 'backward', // B changes → A needs update\n },\n // Test→Requirements/Business (verification relationship)\n 'verifies': {\n allowedTargetLevels: ['L0', 'L1'], // Verifies business/requirements\n levelRule: 'any',\n propagation: 'backward', // B changes → A needs update\n },\n // Dependencies (same level or concrete→abstract)\n 'dependsOn': {\n levelRule: 'source>=target',\n propagation: 'backward', // B changes → A affected\n },\n // Usage relationship (no level constraint)\n 'uses': {\n levelRule: 'any',\n propagation: 'backward', // B changes → A affected\n },\n // Inclusion relationship (same level only)\n 'includes': {\n levelRule: 'same',\n propagation: 'backward', // B changes → A affected\n },\n // Bidirectional tracing\n 'traces': {\n levelRule: 'any',\n propagation: 'both',\n },\n // General relation\n 'relatedTo': {\n levelRule: 'any',\n propagation: 'both',\n },\n};\n\n// ============================================================================\n// Relation Validation\n// ============================================================================\n\n/**\n * Relation validation result\n */\nexport interface RelationValidationResult {\n valid: boolean;\n errors: RelationValidationError[];\n}\n\n/**\n * Relation validation error\n */\nexport interface RelationValidationError {\n type: 'level_violation' | 'target_level_violation' | 'self_reference' | 'cycle_detected';\n message: string;\n relation: Relation;\n sourceId: string;\n}\n\n/**\n * Validate level constraint for single relation\n * \n * @param sourceLevel - Source model level (set in _models/)\n * @param sourceSpecId - Source spec ID\n * @param relation - Relation\n * @param targetLevel - Target model level\n */\nexport function validateRelationLevel(\n sourceLevel: ModelLevel | undefined,\n sourceSpecId: string,\n relation: Relation,\n targetLevel: ModelLevel | undefined,\n): RelationValidationError | null {\n // Self-reference check\n if (sourceSpecId === relation.target) {\n return {\n type: 'self_reference',\n message: `Self-reference is not allowed: ${sourceSpecId} → ${relation.target}`,\n relation,\n sourceId: sourceSpecId,\n };\n }\n\n // Skip if level is undefined\n if (!sourceLevel || !targetLevel) {\n return null;\n }\n \n const constraint = RELATION_CONSTRAINTS[relation.type];\n \n // Target level constraint check\n if (constraint.allowedTargetLevels && \n !constraint.allowedTargetLevels.includes(targetLevel)) {\n return {\n type: 'target_level_violation',\n message: `'${relation.type}' relation target must be ${constraint.allowedTargetLevels.join(' or ')}, but target is ${targetLevel}`,\n relation,\n sourceId: sourceSpecId,\n };\n }\n \n // Level direction constraint check\n const srcIdx = getLevelIndex(sourceLevel);\n const tgtIdx = getLevelIndex(targetLevel);\n \n switch (constraint.levelRule) {\n case 'source>target':\n if (srcIdx <= tgtIdx) {\n return {\n type: 'level_violation',\n message: `'${relation.type}' requires source (${sourceLevel}) to be more concrete than target (${targetLevel})`,\n relation,\n sourceId: sourceSpecId,\n };\n }\n break;\n case 'source>=target':\n if (srcIdx < tgtIdx) {\n return {\n type: 'level_violation',\n message: `'${relation.type}' requires source (${sourceLevel}) to be same or more concrete than target (${targetLevel})`,\n relation,\n sourceId: sourceSpecId,\n };\n }\n break;\n case 'same':\n if (srcIdx !== tgtIdx) {\n return {\n type: 'level_violation',\n message: `'${relation.type}' requires source (${sourceLevel}) and target (${targetLevel}) to be same level`,\n relation,\n sourceId: sourceSpecId,\n };\n }\n break;\n }\n \n return null;\n}\n\n/**\n * Detect circular references\n */\nexport function detectCycles(\n relations: Array<{ sourceId: string; targetId: string; type: RelationType }>,\n): RelationValidationError[] {\n const errors: RelationValidationError[] = [];\n const graph = new Map<string, Set<string>>();\n const relationMap = new Map<string, Relation>();\n \n // Build graph\n for (const rel of relations) {\n if (!graph.has(rel.sourceId)) {\n graph.set(rel.sourceId, new Set());\n }\n graph.get(rel.sourceId)!.add(rel.targetId);\n relationMap.set(`${rel.sourceId}→${rel.targetId}`, { type: rel.type, target: rel.targetId });\n }\n \n // Detect cycles using DFS\n const visited = new Set<string>();\n const recursionStack = new Set<string>();\n const cyclePath: string[] = [];\n \n function dfs(node: string): boolean {\n visited.add(node);\n recursionStack.add(node);\n cyclePath.push(node);\n \n const neighbors = graph.get(node);\n if (neighbors) {\n for (const neighbor of neighbors) {\n if (!visited.has(neighbor)) {\n if (dfs(neighbor)) {\n return true;\n }\n } else if (recursionStack.has(neighbor)) {\n // Cycle detected\n const cycleStart = cyclePath.indexOf(neighbor);\n const cycle = cyclePath.slice(cycleStart);\n cycle.push(neighbor); // Close the cycle\n \n errors.push({\n type: 'cycle_detected',\n message: `Circular reference detected: ${cycle.join(' → ')}`,\n relation: relationMap.get(`${node}→${neighbor}`)!,\n sourceId: node,\n });\n return true;\n }\n }\n }\n \n cyclePath.pop();\n recursionStack.delete(node);\n return false;\n }\n \n for (const node of graph.keys()) {\n if (!visited.has(node)) {\n dfs(node);\n }\n }\n \n return errors;\n}\n\n/**\n * Infer model ID from spec ID (prefix-based)\n */\nexport function inferModelIdFromSpecId(specId: string): string | undefined {\n const prefixMap: Record<string, string> = {\n 'REQ': 'requirement',\n 'CR': 'constraint',\n 'UC': 'usecase',\n 'ACTOR': 'actor',\n 'TERM': 'term',\n 'COMP': 'component',\n 'ENT': 'entity',\n 'FLOW': 'process-flow',\n 'LAYER': 'layer',\n 'BND': 'boundary',\n 'SCR': 'screen',\n 'API': 'api-ref',\n 'TBL': 'table-ref',\n 'IAC': 'iac-ref',\n 'BATCH': 'batch-ref',\n };\n \n for (const [prefix, modelId] of Object.entries(prefixMap)) {\n if (specId.startsWith(prefix + '-')) {\n return modelId;\n }\n }\n \n return undefined;\n}\n","/**\n * Model base class\n * \n * All model definitions inherit from this class\n */\nimport { z, ZodType } from 'zod';\nimport {\n type ModelLevel,\n type Relation,\n type RelationValidationError,\n validateRelationLevel,\n detectCycles,\n inferModelIdFromSpecId,\n} from './relation.js';\n\n// Re-export relation types\nexport type { ModelLevel, Relation, RelationValidationError };\nexport { RELATION_TYPES, RELATION_CONSTRAINTS, RelationSchema, RelationsFieldSchema } from './relation.js';\n\n// ============================================================================\n// Type Definitions\n// ============================================================================\n\n/**\n * Lint rule definition\n */\nexport interface LintRule<T> {\n id: string;\n severity: 'error' | 'warning' | 'info';\n message: string;\n check: (spec: T) => boolean; // true if there is an issue\n}\n\n/**\n * Lint result\n */\nexport interface LintResult {\n ruleId: string;\n severity: 'error' | 'warning' | 'info';\n message: string;\n specId?: string;\n}\n\n/**\n * Exporter definition\n */\nexport interface Exporter<T> {\n format: 'markdown' | 'json' | 'mermaid';\n single?: (spec: T) => string;\n index?: (specs: T[]) => string;\n outputDir?: string;\n filename?: (spec: T) => string;\n}\n\n/**\n * External checker definition\n */\nexport interface ExternalChecker<T> {\n targetType: string; // 'openapi' | 'ddl' | 'cli' etc.\n sourcePath: (spec: T) => string;\n check: (spec: T, externalData: unknown) => CheckResult;\n}\n\n/**\n * Check result\n */\nexport interface CheckResult {\n success: boolean;\n errors: { message: string; field?: string; specId?: string }[];\n warnings: { message: string; field?: string; specId?: string }[];\n}\n\n/**\n * Coverage result\n */\nexport interface CoverageResult {\n /** Total target count */\n total: number;\n /** Covered count */\n covered: number;\n /** Uncovered count */\n uncovered: number;\n /** Coverage rate (%) */\n coveragePercent: number;\n /** Details of covered items */\n coveredItems: { id: string; description?: string }[];\n /** Details of uncovered items */\n uncoveredItems: { id: string; description?: string; sourceId?: string }[];\n}\n\n/**\n * Coverage checker definition\n * \n * Verify cross-model consistency (coverage).\n * Example: Whether TestRef covers acceptanceCriteria of Requirement\n */\nexport interface CoverageChecker<T> {\n /** Target model ID for coverage (e.g. 'requirement') */\n targetModel: string;\n /** Description of coverage check */\n description: string;\n /** Execute coverage check */\n check: (\n specs: T[],\n registry: Record<string, Map<string, unknown>>\n ) => CoverageResult;\n}\n\n// ============================================================================\n// Renderer (for embeds)\n// ============================================================================\n\n/**\n * Render context\n * Simplified version compatible with embedoc's EmbedContext\n */\nexport interface RenderContext {\n /** Parameters (filter conditions other than format, etc.) */\n params: Record<string, string | undefined>;\n /** Markdown helpers */\n markdown: {\n /** Generate table */\n table: (headers: string[], rows: (string | unknown)[][]) => string;\n };\n}\n\n/**\n * Renderer definition\n * \n * Model-specific rendering called from embeds\n */\nexport interface Renderer<T> {\n /** Format ID ('table', 'list', 'detail', 'spec-chapter', etc.) */\n format: string;\n /** Rendering process */\n render: (specs: T[], ctx: RenderContext) => string;\n}\n\n// ============================================================================\n// Model Base Class\n// ============================================================================\n\n/**\n * Model base class\n * \n * @template TSchema - Zod schema type\n */\nexport abstract class Model<TSchema extends ZodType> {\n /** Singleton instance storage (per subclass) */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private static _instances: WeakMap<new () => any, Model<ZodType>> = new WeakMap();\n\n /**\n * Get singleton instance of the model\n * Usage: RequirementModel.instance\n */\n static get instance(): Model<ZodType> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const ctor = this as unknown as new () => any;\n if (!this._instances.has(ctor)) {\n this._instances.set(ctor, new ctor());\n }\n return this._instances.get(ctor)!;\n }\n\n /** Model ID ('requirement', 'usecase', etc.) */\n abstract readonly id: string;\n \n /** Model name ('Requirement', 'UseCase', etc.) */\n abstract readonly name: string;\n \n /** ID prefix ('REQ', 'UC', etc.) */\n abstract readonly idPrefix: string;\n \n /** Zod schema */\n abstract readonly schema: TSchema;\n \n /** Model description (optional) */\n readonly description?: string;\n \n /** External SSOT type (optional, e.g. 'OpenAPI', 'DDL/Prisma') */\n readonly externalSsotType?: string;\n \n /** Spec instance type */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected get specType(): z.infer<TSchema> { return undefined as any; }\n \n /** Lint rules (override in subclass) */\n protected lintRules: LintRule<z.infer<TSchema>>[] = [];\n \n /** Exporters (override in subclass) */\n protected exporters: Exporter<z.infer<TSchema>>[] = [];\n \n /** External checker (optional) */\n protected externalChecker?: ExternalChecker<z.infer<TSchema>>;\n \n /** Coverage checker (optional) */\n protected coverageChecker?: CoverageChecker<z.infer<TSchema>>;\n \n /** Model level (set in _models/) */\n protected modelLevel?: ModelLevel;\n \n /** Renderers (for embeds, override in subclass) */\n protected renderers: Renderer<z.infer<TSchema>>[] = [];\n \n /**\n * Get model level\n * Returns modelLevel set in _models/\n */\n get level(): ModelLevel | undefined {\n return this.modelLevel;\n }\n \n /**\n * Execute schema validation\n */\n validate(spec: unknown): z.infer<TSchema> {\n return this.schema.parse(spec);\n }\n \n /**\n * Schema validation (safe version, returns error object on failure)\n */\n safeParse(spec: unknown): { success: true; data: z.infer<TSchema> } | { success: false; error: z.ZodError } {\n return this.schema.safeParse(spec);\n }\n \n /**\n * Execute lint\n */\n lint(spec: z.infer<TSchema>): LintResult[] {\n const specId = (spec as { id?: string }).id;\n return this.lintRules\n .filter(rule => rule.check(spec))\n .map(rule => ({\n ruleId: rule.id,\n severity: rule.severity,\n message: rule.message,\n specId,\n }));\n }\n \n /**\n * Execute lint for multiple specs\n */\n lintAll(specs: z.infer<TSchema>[]): LintResult[] {\n return specs.flatMap(spec => this.lint(spec));\n }\n \n /**\n * Validate level constraints of relations\n * @param spec - Spec instance (if it has relations property)\n * @returns Array of validation errors\n */\n validateRelations(spec: z.infer<TSchema>): RelationValidationError[] {\n const errors: RelationValidationError[] = [];\n const specWithRelations = spec as { id?: string; relations?: Relation[] };\n \n if (!specWithRelations.relations || !specWithRelations.id) {\n return errors;\n }\n \n // Get all models to retrieve target model levels\n const allModels = getAllModels();\n const modelLevelMap = new Map<string, ModelLevel | undefined>();\n for (const model of allModels) {\n modelLevelMap.set(model.id, model.level);\n }\n \n for (const relation of specWithRelations.relations) {\n // Infer target model ID\n const targetModelId = inferModelIdFromSpecId(relation.target);\n if (!targetModelId) {\n continue; // Skip if model ID cannot be inferred\n }\n \n const targetLevel = modelLevelMap.get(targetModelId);\n \n const error = validateRelationLevel(\n this.level,\n specWithRelations.id,\n relation,\n targetLevel,\n );\n \n if (error) {\n errors.push(error);\n }\n }\n \n return errors;\n }\n \n /**\n * Validate relations of multiple specs (including circular reference check)\n */\n validateAllRelations(specs: z.infer<TSchema>[]): RelationValidationError[] {\n const errors: RelationValidationError[] = [];\n const allRelations: Array<{ sourceId: string; targetId: string; type: string }> = [];\n \n for (const spec of specs) {\n // Individual level constraint check\n errors.push(...this.validateRelations(spec));\n \n // Collect relations for circular reference check\n const specWithRelations = spec as { id?: string; relations?: Relation[] };\n if (specWithRelations.relations && specWithRelations.id) {\n for (const rel of specWithRelations.relations) {\n allRelations.push({\n sourceId: specWithRelations.id,\n targetId: rel.target,\n type: rel.type,\n });\n }\n }\n }\n \n // Circular reference check\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n errors.push(...detectCycles(allRelations as any));\n \n return errors;\n }\n \n /**\n * Export in specified format (single spec)\n */\n exportSingle(spec: z.infer<TSchema>, format: string): string | null {\n const exporter = this.exporters.find(e => e.format === format);\n if (!exporter?.single) return null;\n return exporter.single(spec);\n }\n \n /**\n * Export in specified format (index)\n */\n exportIndex(specs: z.infer<TSchema>[], format: string): string | null {\n const exporter = this.exporters.find(e => e.format === format);\n if (!exporter?.index) return null;\n return exporter.index(specs);\n }\n \n /**\n * Get exporter output directory\n */\n getOutputDir(format: string): string | null {\n const exporter = this.exporters.find(e => e.format === format);\n return exporter?.outputDir ?? null;\n }\n \n /**\n * Get filename\n */\n getFilename(spec: z.infer<TSchema>, format: string): string | null {\n const exporter = this.exporters.find(e => e.format === format);\n if (!exporter?.filename) return null;\n return exporter.filename(spec);\n }\n \n /**\n * Check consistency with external SSOT\n */\n check(spec: z.infer<TSchema>, externalData: unknown): CheckResult {\n if (!this.externalChecker) {\n return { success: true, errors: [], warnings: [] };\n }\n return this.externalChecker.check(spec, externalData);\n }\n \n /**\n * Get external SSOT path\n */\n getExternalSourcePath(spec: z.infer<TSchema>): string | null {\n if (!this.externalChecker) return null;\n return this.externalChecker.sourcePath(spec);\n }\n \n /**\n * Execute coverage check\n * @param specs - Array of spec instances for this model\n * @param registry - Registry of all models\n */\n checkCoverage(\n specs: z.infer<TSchema>[],\n registry: Record<string, Map<string, unknown>>\n ): CoverageResult | null {\n if (!this.coverageChecker) return null;\n return this.coverageChecker.check(specs, registry);\n }\n \n /**\n * Get coverage checker\n */\n getCoverageChecker(): CoverageChecker<z.infer<TSchema>> | undefined {\n return this.coverageChecker;\n }\n \n /**\n * Get lint rules\n */\n getLintRules(): LintRule<z.infer<TSchema>>[] {\n return this.lintRules;\n }\n \n /**\n * Get exporters\n */\n getExporters(): Exporter<z.infer<TSchema>>[] {\n return this.exporters;\n }\n \n // ============================================================================\n // Renderer (for embeds)\n // ============================================================================\n \n /**\n * Render in specified format\n * @param format - Format ID ('table', 'list', 'detail', etc.)\n * @param specs - Array of specs to render\n * @param ctx - Render context\n * @returns Rendered result (Markdown string), null if no matching renderer\n */\n render(format: string, specs: z.infer<TSchema>[], ctx: RenderContext): string | null {\n const renderer = this.renderers.find(r => r.format === format);\n if (!renderer) return null;\n return renderer.render(specs, ctx);\n }\n \n /**\n * Get list of available formats\n */\n getAvailableFormats(): string[] {\n return this.renderers.map(r => r.format);\n }\n \n /**\n * Get renderers\n */\n getRenderers(): Renderer<z.infer<TSchema>>[] {\n return this.renderers;\n }\n \n /**\n * Check if renderer exists for specific format\n */\n hasRenderer(format: string): boolean {\n return this.renderers.some(r => r.format === format);\n }\n \n /**\n * Register spec instances for this model.\n * Stores specs in the global specStore keyed by this model's id.\n */\n register(specs: z.infer<TSchema>[]): void {\n if (!specStore.has(this.id)) {\n specStore.set(this.id, new Map());\n }\n const map = specStore.get(this.id)!;\n for (const spec of specs) {\n map.set((spec as { id: string }).id, spec);\n }\n }\n}\n\n// ============================================================================\n// Spec Store\n// ============================================================================\n\nconst specStore = new Map<string, Map<string, unknown>>();\n\n/**\n * Get the global spec store (model ID → spec ID → spec data)\n */\nexport function getSpecStore(): Map<string, Map<string, unknown>> {\n return specStore;\n}\n\n/**\n * Reset the spec store (clears all registered specs)\n */\nexport function resetSpecStore(): void {\n specStore.clear();\n}\n\n// ============================================================================\n// Model Registry\n// ============================================================================\n\n/** Map of registered models */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst modelRegistry = new Map<string, Model<any>>();\n\n/**\n * Register model\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function registerModel(model: Model<any>): void {\n modelRegistry.set(model.id, model);\n}\n\n/**\n * Get model\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getModel(id: string): Model<any> | undefined {\n return modelRegistry.get(id);\n}\n\n/**\n * Get all registered models\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getAllModels(): Model<any>[] {\n return Array.from(modelRegistry.values());\n}\n\n/**\n * Clear registry\n */\nexport function clearModelRegistry(): void {\n modelRegistry.clear();\n}\n\n/**\n * Register model instances from config.models array.\n * Filters out non-Model values. Call this once after config is loaded.\n */\nexport function registerModelsFromConfig(models: unknown[]): void {\n for (const model of models) {\n if (model && typeof model === 'object' && 'id' in model && 'schema' in model) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n registerModel(model as Model<any>);\n }\n }\n}\n\n/**\n * Get specs for a given model ID from specStore\n */\nexport function getSpecs(modelId: string): unknown[] {\n const map = specStore.get(modelId);\n if (!map) return [];\n return Array.from(map.values());\n}\n\n/**\n * Get all spec IDs across all models\n */\nexport function getAllSpecIds(): Set<string> {\n const ids = new Set<string>();\n for (const map of specStore.values()) {\n for (const id of map.keys()) {\n ids.add(id);\n }\n }\n return ids;\n}\n\n/**\n * Find which model type a spec ID belongs to\n */\nexport function findModelTypeBySpecId(specId: string): string | null {\n for (const [modelId, map] of specStore) {\n if (map.has(specId)) return modelId;\n }\n return null;\n}\n\n/**\n * Get a spec by ID (searches all models)\n */\nexport function getSpecById(specId: string): { modelId: string; spec: unknown } | null {\n const modelId = findModelTypeBySpecId(specId);\n if (!modelId) return null;\n return { modelId, spec: specStore.get(modelId)!.get(specId) };\n}\n","import { z } from 'zod';\nimport type {\n ModelDefinition,\n MetaModelRegistry,\n LintRule,\n LintContext,\n LintIssue,\n ExportContext,\n CheckContext,\n CheckResult,\n MarkdownExporter,\n MermaidExporter,\n ExternalChecker,\n} from '../types/meta-model.js';\n\n// ============================================================================\n// Global Registry\n// ============================================================================\n\n/**\n * Global model registry\n */\nconst globalRegistry: MetaModelRegistry = {\n definitions: new Map(),\n instances: new Map(),\n};\n\n// ============================================================================\n// Model Definition Registration\n// ============================================================================\n\n/**\n * Register model definition\n */\nexport function registerModelDefinition<T extends z.ZodTypeAny>(\n definition: ModelDefinition<T>\n): void {\n if (globalRegistry.definitions.has(definition.id)) {\n console.warn(`Model definition '${definition.id}' is already registered. Overwriting.`);\n }\n \n // Store in generic registry while maintaining type safety\n globalRegistry.definitions.set(definition.id, definition as unknown as ModelDefinition);\n \n // Initialize Map for instances\n if (!globalRegistry.instances.has(definition.id)) {\n globalRegistry.instances.set(definition.id, new Map());\n }\n}\n\n/**\n * Register multiple model definitions at once\n */\nexport function registerModelDefinitions(definitions: ModelDefinition[]): void {\n for (const def of definitions) {\n registerModelDefinition(def);\n }\n}\n\n/**\n * Get model definition\n */\nexport function getModelDefinition(modelId: string): ModelDefinition | undefined {\n return globalRegistry.definitions.get(modelId);\n}\n\n/**\n * Get all model definitions\n */\nexport function getAllModelDefinitions(): ModelDefinition[] {\n return Array.from(globalRegistry.definitions.values());\n}\n\n// ============================================================================\n// Model Instance Registration\n// ============================================================================\n\n/**\n * Register model instance\n */\nexport function registerModelInstance<T extends { id: string }>(\n modelId: string,\n instance: T\n): void {\n const definition = globalRegistry.definitions.get(modelId);\n if (!definition) {\n throw new Error(`Model definition '${modelId}' not found. Register the definition first.`);\n }\n \n // Validate with schema\n const result = definition.schema.safeParse(instance);\n if (!result.success) {\n throw new Error(\n `Invalid instance for model '${modelId}': ${result.error.message}`\n );\n }\n \n let instances = globalRegistry.instances.get(modelId);\n if (!instances) {\n instances = new Map();\n globalRegistry.instances.set(modelId, instances);\n }\n \n instances.set(instance.id, instance);\n}\n\n/**\n * Get model instance\n */\nexport function getModelInstance<T = unknown>(\n modelId: string,\n instanceId: string\n): T | undefined {\n const instances = globalRegistry.instances.get(modelId);\n return instances?.get(instanceId) as T | undefined;\n}\n\n/**\n * Get all instances of a model\n */\nexport function getAllModelInstances<T = unknown>(modelId: string): T[] {\n const instances = globalRegistry.instances.get(modelId);\n if (!instances) return [];\n return Array.from(instances.values()) as T[];\n}\n\n/**\n * Get all instances of all models (flattened)\n */\nexport function getAllInstances(): Array<{ modelId: string; instance: unknown }> {\n const result: Array<{ modelId: string; instance: unknown }> = [];\n \n for (const [modelId, instances] of globalRegistry.instances) {\n for (const instance of instances.values()) {\n result.push({ modelId, instance });\n }\n }\n \n return result;\n}\n\n// ============================================================================\n// Registry Access\n// ============================================================================\n\n/**\n * Get global registry\n */\nexport function getGlobalModelRegistry(): MetaModelRegistry {\n return globalRegistry;\n}\n\n/**\n * Reset registry (for testing)\n */\nexport function resetModelRegistry(): void {\n globalRegistry.definitions.clear();\n globalRegistry.instances.clear();\n}\n\n/**\n * Reset instances only (keep definitions)\n */\nexport function resetModelInstances(): void {\n for (const instances of globalRegistry.instances.values()) {\n instances.clear();\n }\n}\n\n// ============================================================================\n// Lint Execution\n// ============================================================================\n\n/**\n * Execute lint for specific model\n */\nexport function lintModel<T extends { id: string }>(\n modelId: string,\n instance: T,\n context: LintContext\n): Array<{ rule: LintRule<T>; issue: LintIssue }> {\n const definition = globalRegistry.definitions.get(modelId);\n if (!definition || !definition.lintRules) return [];\n \n const issues: Array<{ rule: LintRule<T>; issue: LintIssue }> = [];\n \n for (const rule of definition.lintRules as LintRule<T>[]) {\n const issue = rule.check(instance, context);\n if (issue) {\n issues.push({ rule, issue });\n }\n }\n \n return issues;\n}\n\n/**\n * Execute lint for all models\n */\nexport function lintAllModels(context: LintContext): Array<{\n modelId: string;\n instanceId: string;\n rule: LintRule<unknown>;\n issue: LintIssue;\n}> {\n const allIssues: Array<{\n modelId: string;\n instanceId: string;\n rule: LintRule<unknown>;\n issue: LintIssue;\n }> = [];\n \n for (const [modelId, instances] of globalRegistry.instances) {\n const definition = globalRegistry.definitions.get(modelId);\n if (!definition || !definition.lintRules) continue;\n \n for (const [instanceId, instance] of instances) {\n for (const rule of definition.lintRules) {\n const issue = rule.check(instance, context);\n if (issue) {\n allIssues.push({\n modelId,\n instanceId,\n rule,\n issue,\n });\n }\n }\n }\n }\n \n return allIssues;\n}\n\n// ============================================================================\n// Export Execution\n// ============================================================================\n\n/**\n * Execute Markdown export\n */\nexport function exportMarkdown(\n modelId: string,\n context: ExportContext\n): Array<{ path: string; content: string }> {\n const definition = globalRegistry.definitions.get(modelId);\n if (!definition || !definition.exporters?.markdown) return [];\n \n const exporter = definition.exporters.markdown as MarkdownExporter<unknown>;\n const instances = getAllModelInstances(modelId);\n const files: Array<{ path: string; content: string }> = [];\n \n // Generate individual files\n for (const instance of instances) {\n const content = exporter.single(instance, context);\n const filename = exporter.filename\n ? exporter.filename(instance)\n : (instance as { id: string }).id;\n \n files.push({\n path: `${context.outputDir}/${exporter.outputDir}/${filename}.md`,\n content,\n });\n }\n \n // Generate index file\n if (exporter.index && instances.length > 0) {\n const indexContent = exporter.index(instances, context);\n files.push({\n path: `${context.outputDir}/${exporter.outputDir}/index.md`,\n content: indexContent,\n });\n }\n \n return files;\n}\n\n/**\n * Execute Mermaid diagram export\n */\nexport function exportMermaid(\n modelId: string,\n context: ExportContext\n): Array<{ path: string; content: string }> {\n const definition = globalRegistry.definitions.get(modelId);\n if (!definition || !definition.exporters?.mermaid) return [];\n \n const exporters = Array.isArray(definition.exporters.mermaid)\n ? definition.exporters.mermaid\n : [definition.exporters.mermaid];\n \n const instances = getAllModelInstances(modelId);\n const files: Array<{ path: string; content: string }> = [];\n \n for (const exporter of exporters as MermaidExporter<unknown>[]) {\n const content = exporter.generate(instances, context);\n files.push({\n path: `${context.outputDir}/${exporter.outputPath}`,\n content,\n });\n }\n \n return files;\n}\n\n/**\n * Execute export for all models\n */\nexport function exportAllModels(context: ExportContext): Array<{ path: string; content: string }> {\n const files: Array<{ path: string; content: string }> = [];\n \n for (const modelId of globalRegistry.definitions.keys()) {\n files.push(...exportMarkdown(modelId, context));\n files.push(...exportMermaid(modelId, context));\n }\n \n return files;\n}\n\n// ============================================================================\n// External Check Execution\n// ============================================================================\n\n/**\n * Execute external SSOT check\n */\nexport function checkExternalSsot<T extends { id: string }>(\n modelId: string,\n externalSource: unknown,\n context: CheckContext\n): CheckResult {\n const definition = globalRegistry.definitions.get(modelId);\n if (!definition || !definition.externalChecker) {\n return { success: true, errors: [], warnings: [] };\n }\n \n const checker = definition.externalChecker as ExternalChecker<T>;\n const instances = getAllModelInstances<T>(modelId);\n \n const allErrors: CheckResult['errors'] = [];\n const allWarnings: CheckResult['warnings'] = [];\n \n for (const instance of instances) {\n const result = checker.check(instance, externalSource, context);\n allErrors.push(...result.errors);\n allWarnings.push(...result.warnings);\n }\n \n return {\n success: allErrors.length === 0,\n errors: allErrors,\n warnings: allWarnings,\n };\n}\n\n// ============================================================================\n// Reference Resolution\n// ============================================================================\n\n/**\n * Resolve reference\n */\nexport function resolveReference(\n modelId: string,\n instanceId: string,\n field: string\n): unknown | undefined {\n const definition = globalRegistry.definitions.get(modelId);\n if (!definition || !definition.references) return undefined;\n \n const refDef = definition.references.find(r => r.field === field);\n if (!refDef) return undefined;\n \n const instance = getModelInstance(modelId, instanceId) as Record<string, unknown> | undefined;\n if (!instance) return undefined;\n \n const refValue = instance[field];\n if (!refValue) return undefined;\n \n if (refDef.isArray && Array.isArray(refValue)) {\n return refValue.map(id => getModelInstance(refDef.targetModel, id as string));\n }\n \n return getModelInstance(refDef.targetModel, refValue as string);\n}\n\n/**\n * Check reference integrity\n */\nexport function checkReferenceIntegrity(): Array<{\n modelId: string;\n instanceId: string;\n field: string;\n targetModel: string;\n missingIds: string[];\n}> {\n const issues: Array<{\n modelId: string;\n instanceId: string;\n field: string;\n targetModel: string;\n missingIds: string[];\n }> = [];\n \n for (const [modelId, definition] of globalRegistry.definitions) {\n if (!definition.references) continue;\n \n const instances = globalRegistry.instances.get(modelId);\n if (!instances) continue;\n \n for (const [instanceId, instance] of instances) {\n const inst = instance as Record<string, unknown>;\n \n for (const refDef of definition.references) {\n const refValue = inst[refDef.field];\n if (!refValue) {\n if (refDef.required) {\n issues.push({\n modelId,\n instanceId,\n field: refDef.field,\n targetModel: refDef.targetModel,\n missingIds: ['(required but not provided)'],\n });\n }\n continue;\n }\n \n const targetInstances = globalRegistry.instances.get(refDef.targetModel);\n const missingIds: string[] = [];\n \n if (refDef.isArray && Array.isArray(refValue)) {\n for (const id of refValue) {\n if (!targetInstances?.has(id as string)) {\n missingIds.push(id as string);\n }\n }\n } else {\n if (!targetInstances?.has(refValue as string)) {\n missingIds.push(refValue as string);\n }\n }\n \n if (missingIds.length > 0) {\n issues.push({\n modelId,\n instanceId,\n field: refDef.field,\n targetModel: refDef.targetModel,\n missingIds,\n });\n }\n }\n }\n }\n \n return issues;\n}\n\n// ============================================================================\n// Statistics\n// ============================================================================\n\n/**\n * Get registry statistics\n */\nexport function getModelRegistryStats(): {\n definitionCount: number;\n instanceCounts: Record<string, number>;\n totalInstances: number;\n} {\n const instanceCounts: Record<string, number> = {};\n let totalInstances = 0;\n \n for (const [modelId, instances] of globalRegistry.instances) {\n instanceCounts[modelId] = instances.size;\n totalInstances += instances.size;\n }\n \n return {\n definitionCount: globalRegistry.definitions.size,\n instanceCounts,\n totalInstances,\n };\n}\n","/**\n * Configuration API for speckeeper\n * \n * Provides `defineConfig` and `defineModel` functions for users to\n * create speckeeper.config.ts files with custom model definitions.\n */\n\nimport { z } from 'zod';\nimport type {\n ModelDefinition,\n MarkdownExporter,\n MermaidExporter,\n JsonSchemaExporter,\n LintRule,\n ExternalChecker,\n ReferenceDefinition,\n} from '../types/meta-model.js';\nimport { registerModelDefinitions } from './model-registry.js';\n\n// ============================================================================\n// Config Types\n// ============================================================================\n\n/**\n * speckeeper configuration type\n */\nexport interface SpeckeeperConfigInput {\n /** Project name */\n projectName?: string;\n /** Project version */\n version?: string;\n /** Design files directory */\n designDir?: string;\n /** Docs output directory */\n docsDir?: string;\n /** Specs output directory */\n specsDir?: string;\n /** Custom model definitions (Model instances or ModelDefinition objects) */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n models?: any[];\n /** External SSOT configuration */\n externalSsot?: {\n openapi?: {\n enabled: boolean;\n paths: string[];\n };\n ddl?: {\n enabled: boolean;\n type: 'ddl' | 'prisma' | 'typeorm' | 'drizzle';\n path: string;\n };\n iac?: {\n enabled: boolean;\n type: 'cloudformation' | 'cdk' | 'terraform';\n path: string;\n };\n };\n /** Lint configuration */\n lint?: {\n /** Strict mode */\n strict?: boolean;\n /** Disable specific rules */\n disabledRules?: string[];\n };\n}\n\n/**\n * Resolved speckeeper configuration\n */\nexport interface ResolvedSpeckeeperConfig extends SpeckeeperConfigInput {\n designDir: string;\n docsDir: string;\n specsDir: string;\n}\n\n// ============================================================================\n// Config API\n// ============================================================================\n\n/**\n * Define speckeeper configuration\n * \n * @example\n * ```typescript\n * // speckeeper.config.ts\n * import { defineConfig, defineModel } from 'speckeeper';\n * \n * export default defineConfig({\n * projectName: 'My Project',\n * models: [\n * // Custom model definitions\n * ],\n * });\n * ```\n */\nexport function defineConfig(input: SpeckeeperConfigInput): ResolvedSpeckeeperConfig {\n const resolved: ResolvedSpeckeeperConfig = {\n ...input,\n designDir: input.designDir ?? 'design',\n docsDir: input.docsDir ?? 'docs',\n specsDir: input.specsDir ?? 'specs',\n };\n \n // Register custom models\n if (input.models && input.models.length > 0) {\n registerModelDefinitions(input.models);\n }\n \n return resolved;\n}\n\n// ============================================================================\n// Model Definition API\n// ============================================================================\n\n/**\n * Model definition input type\n */\nexport interface ModelDefinitionInput<T extends z.ZodTypeAny> {\n /** Unique identifier for the model (kebab-case recommended) */\n id: string;\n /** Model name (PascalCase recommended) */\n name: string;\n /** Model description */\n description: string;\n /** Zod schema */\n schema: T;\n /** Prefix for ID generation */\n idPrefix: string;\n /** Exporter configuration */\n exporters?: {\n markdown?: MarkdownExporter<z.infer<T>>;\n mermaid?: MermaidExporter<z.infer<T>> | MermaidExporter<z.infer<T>>[];\n jsonSchema?: JsonSchemaExporter;\n };\n /** Lint rules */\n lintRules?: LintRule<z.infer<T>>[];\n /** External SSOT checker */\n externalChecker?: ExternalChecker<z.infer<T>>;\n /** Reference definitions */\n references?: ReferenceDefinition[];\n /** DSL function name */\n dslName?: string;\n /** Phase */\n phase?: 'REQ' | 'HLD' | 'LLD' | 'OPS';\n}\n\n/**\n * Create a custom model definition\n * \n * @example\n * ```typescript\n * const RetryPolicyModel = defineModel({\n * id: 'retry-policy',\n * name: 'RetryPolicy',\n * description: 'Retry policy definition',\n * schema: z.object({\n * id: z.string(),\n * name: z.string(),\n * maxAttempts: z.number().min(1),\n * initialDelay: z.number().min(0),\n * backoffMultiplier: z.number().min(1),\n * }),\n * idPrefix: 'RETRY',\n * exporters: {\n * markdown: {\n * single: (m) => `# ${m.name}\\n\\n- Max Attempts: ${m.maxAttempts}`,\n * outputDir: 'docs/retry-policies',\n * },\n * },\n * lintRules: [\n * {\n * id: 'retry-max-limit',\n * description: 'maxAttempts should not exceed 10',\n * severity: 'warning',\n * check: (m) => m.maxAttempts > 10 \n * ? { message: `maxAttempts ${m.maxAttempts} exceeds recommended limit` } \n * : null,\n * },\n * ],\n * });\n * ```\n */\nexport function defineModel<T extends z.ZodTypeAny>(\n input: ModelDefinitionInput<T>\n): ModelDefinition<T> {\n const definition: ModelDefinition<T> = {\n id: input.id,\n name: input.name,\n description: input.description,\n schema: input.schema,\n idPrefix: input.idPrefix,\n exporters: input.exporters,\n lintRules: input.lintRules,\n externalChecker: input.externalChecker,\n references: input.references,\n dslName: input.dslName,\n phase: input.phase,\n };\n \n return definition;\n}\n\n// ============================================================================\n// Helper Functions for Creating Exporters\n// ============================================================================\n\n/**\n * Helper to create Markdown exporter\n */\nexport function createMarkdownExporter<T>(\n config: {\n outputDir: string;\n single: (model: T, context: unknown) => string;\n index?: (models: T[], context: unknown) => string;\n filename?: (model: T) => string;\n }\n): MarkdownExporter<T> {\n return {\n single: config.single,\n index: config.index,\n outputDir: config.outputDir,\n filename: config.filename,\n };\n}\n\n/**\n * Helper to create Mermaid diagram exporter\n */\nexport function createMermaidExporter<T>(\n config: {\n diagramType: MermaidExporter<T>['diagramType'];\n outputPath: string;\n generate: (models: T[], context: unknown) => string;\n title?: string;\n }\n): MermaidExporter<T> {\n return {\n diagramType: config.diagramType,\n outputPath: config.outputPath,\n generate: config.generate,\n title: config.title,\n };\n}\n\n/**\n * Helper to create lint rule\n */\nexport function createLintRule<T>(\n config: {\n id: string;\n description: string;\n severity: 'error' | 'warning' | 'info';\n check: (model: T, context: unknown) => { message: string; field?: string; suggestion?: string } | null;\n }\n): LintRule<T> {\n return {\n id: config.id,\n description: config.description,\n severity: config.severity,\n check: config.check,\n };\n}\n\n// ============================================================================\n// Config Loading\n// ============================================================================\n\n/**\n * Load speckeeper.config.ts file and register custom models\n */\nexport async function loadSpeckeeperConfig(configPath?: string): Promise<ResolvedSpeckeeperConfig | null> {\n const possiblePaths = configPath \n ? [configPath]\n : [\n 'speckeeper.config.ts',\n 'speckeeper.config.js',\n 'speckeeper.config.mjs',\n ];\n \n for (const path of possiblePaths) {\n try {\n const fullPath = path.startsWith('/') ? path : `${process.cwd()}/${path}`;\n const module = await import(fullPath);\n const config = module.default || module;\n \n if (config && typeof config === 'object') {\n // Register custom models\n if (config.models && Array.isArray(config.models)) {\n registerModelDefinitions(config.models);\n }\n \n return {\n ...config,\n designDir: config.designDir ?? 'design',\n docsDir: config.docsDir ?? 'docs',\n specsDir: config.specsDir ?? 'specs',\n };\n }\n } catch {\n // Config file not found or invalid, continue to next\n }\n }\n \n return null;\n}\n","import { readFileSync, existsSync } from 'node:fs';\nimport { resolve, dirname, join } from 'node:path';\nimport { parse as parseYaml } from 'yaml';\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\n/**\n * Specification-compliant output path definitions\n * \n * Human-readable artifacts (docs/):\n * requirements/ - Requirements Markdown\n * usecases/ - Use cases\n * architecture/ - Architecture (C4 diagrams)\n * data-model/ - Conceptual model (ER diagrams)\n * screens/ - Screen specifications\n * flows/ - Process flows\n * glossary/ - Glossary\n * \n * Machine-readable artifacts (specs/):\n * schemas/entities/ - Entity JSON Schema\n * index.json - Aggregated data\n */\nexport interface OutputPaths {\n // docs/ subdirectories\n requirements: string;\n usecases: string;\n architecture: string;\n dataModel: string;\n screens: string;\n flows: string;\n glossary: string;\n component: string;\n \n // specs/ subdirectories\n schemasEntities: string;\n}\n\nexport interface SpeckeeperConfig {\n // Project info\n projectName?: string;\n version?: string;\n \n // Source paths\n srcDir: string;\n requirementsDir?: string;\n designDir?: string;\n usecasesDir?: string;\n \n // Output paths\n docsDir: string;\n specsDir: string;\n \n // External SSOT paths\n externalSsot?: {\n openapi?: {\n enabled: boolean;\n paths: string[];\n microContracts?: {\n enabled: boolean;\n requiredExtensions?: string[];\n strictMode?: boolean;\n };\n };\n ddl?: {\n enabled: boolean;\n paths: string[];\n type: 'ddl' | 'prisma' | 'typeorm' | 'drizzle';\n };\n iac?: {\n enabled: boolean;\n paths: string[];\n type: 'cloudformation' | 'terraform' | 'cdk';\n };\n };\n \n // Lint configuration\n lint?: {\n architecture?: {\n allowCrossBoundaryDependencies?: boolean;\n allowCrossLayerViolations?: boolean;\n maxComponentsPerDiagram?: number;\n };\n conceptModel?: {\n requireEntityDescription?: boolean;\n requireAggregateRoot?: boolean;\n warnOnOrphanEntities?: boolean;\n namingConvention?: 'PascalCase' | 'camelCase' | 'snake_case' | 'none';\n };\n screen?: {\n warnOnOrphanScreens?: boolean;\n warnOnDeadEnds?: boolean;\n checkAuthPaths?: boolean;\n };\n phaseGate?: {\n currentPhase?: 'REQ' | 'HLD' | 'LLD' | 'OPS';\n strictMode?: boolean;\n };\n };\n \n // Build configuration\n build?: {\n generateMermaidImages?: boolean;\n mermaidCliPath?: string;\n };\n \n // Custom model definitions\n models?: unknown[];\n}\n\n// Default configuration\nconst defaultConfig: SpeckeeperConfig = {\n srcDir: 'src',\n designDir: 'design', // Directory for requirements/design TS models\n docsDir: 'docs',\n specsDir: 'specs',\n};\n\n// ============================================================================\n// Output Paths (spec-compliant)\n// ============================================================================\n\n/**\n * Get output paths compliant with specification\n */\nexport function getOutputPaths(config: SpeckeeperConfig, cwd: string = process.cwd()): OutputPaths {\n const docsDir = resolve(cwd, config.docsDir);\n const specsDir = resolve(cwd, config.specsDir);\n \n return {\n // docs/ subdirectories (compliant with spec section 7.1)\n requirements: join(docsDir, 'requirements'),\n usecases: join(docsDir, 'usecases'),\n architecture: join(docsDir, 'architecture'),\n dataModel: join(docsDir, 'data-model'),\n screens: join(docsDir, 'screens'),\n flows: join(docsDir, 'flows'),\n glossary: join(docsDir, 'glossary'),\n component: join(docsDir, 'component'),\n \n // specs/ subdirectories (compliant with spec section 7.1)\n schemasEntities: join(specsDir, 'schemas', 'entities'),\n };\n}\n\n/**\n * List of expected output paths (for drift check)\n */\nexport function getExpectedOutputDirs(config: SpeckeeperConfig, cwd: string = process.cwd()): string[] {\n const paths = getOutputPaths(config, cwd);\n return [\n paths.requirements,\n paths.usecases,\n paths.architecture,\n paths.dataModel,\n paths.screens,\n paths.flows,\n paths.glossary,\n paths.component,\n paths.schemasEntities,\n ];\n}\n\n/**\n * Validate if output path complies with specification\n */\nexport function validateOutputPaths(actualPath: string, config: SpeckeeperConfig, cwd: string = process.cwd()): {\n valid: boolean;\n expectedPaths: string[];\n message?: string;\n} {\n const expectedDirs = getExpectedOutputDirs(config, cwd);\n const docsDir = resolve(cwd, config.docsDir);\n const specsDir = resolve(cwd, config.specsDir);\n \n // Check if actualPath is under docs/ or specs/\n const isUnderDocs = actualPath.startsWith(docsDir);\n const isUnderSpecs = actualPath.startsWith(specsDir);\n \n if (!isUnderDocs && !isUnderSpecs) {\n return {\n valid: false,\n expectedPaths: expectedDirs,\n message: `Output path \"${actualPath}\" is not under docs/ or specs/`,\n };\n }\n \n // Check if under any of the expected paths\n const isValidPath = expectedDirs.some(dir => actualPath.startsWith(dir));\n \n if (!isValidPath) {\n return {\n valid: false,\n expectedPaths: expectedDirs,\n message: `Output path \"${actualPath}\" does not match spec-compliant paths. Expected one of: ${expectedDirs.map(d => d.replace(cwd + '/', '')).join(', ')}`,\n };\n }\n \n return { valid: true, expectedPaths: expectedDirs };\n}\n\n// ============================================================================\n// Configuration Loading\n// ============================================================================\n\nconst CONFIG_FILES = [\n 'speckeeper.config.yaml',\n 'speckeeper.config.yml',\n 'speckeeper.config.json',\n 'speckeeper.config.ts',\n 'speckeeper.config.js',\n];\n\nexport function findConfigFile(startDir: string = process.cwd()): string | null {\n let currentDir = startDir;\n \n while (currentDir !== dirname(currentDir)) {\n for (const configFile of CONFIG_FILES) {\n const configPath = resolve(currentDir, configFile);\n if (existsSync(configPath)) {\n return configPath;\n }\n }\n currentDir = dirname(currentDir);\n }\n \n return null;\n}\n\nexport async function loadConfig(\n configPath?: string,\n cwd: string = process.cwd()\n): Promise<SpeckeeperConfig> {\n const resolvedPath = configPath ?? findConfigFile(cwd);\n \n if (!resolvedPath) {\n return { ...defaultConfig };\n }\n \n const ext = resolvedPath.split('.').pop()?.toLowerCase();\n \n try {\n if (ext === 'yaml' || ext === 'yml') {\n const content = readFileSync(resolvedPath, 'utf-8');\n const parsed = parseYaml(content) as Partial<SpeckeeperConfig>;\n return { ...defaultConfig, ...parsed };\n }\n \n if (ext === 'json') {\n const content = readFileSync(resolvedPath, 'utf-8');\n const parsed = JSON.parse(content) as Partial<SpeckeeperConfig>;\n return { ...defaultConfig, ...parsed };\n }\n \n if (ext === 'ts' || ext === 'js') {\n // Dynamic import for TS/JS config\n const module = await import(resolvedPath);\n const parsed = module.default ?? module;\n return { ...defaultConfig, ...parsed };\n }\n \n return { ...defaultConfig };\n } catch (error) {\n console.error(`Failed to load config from ${resolvedPath}:`, error);\n return { ...defaultConfig };\n }\n}\n\n// ============================================================================\n// Configuration Validation\n// ============================================================================\n\nexport function validateConfig(config: SpeckeeperConfig): string[] {\n const errors: string[] = [];\n \n if (!config.srcDir) {\n errors.push('srcDir is required');\n }\n \n if (!config.docsDir) {\n errors.push('docsDir is required');\n }\n \n if (!config.specsDir) {\n errors.push('specsDir is required');\n }\n \n return errors;\n}\n","import { writeFileSync, mkdirSync, existsSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { createHash } from 'node:crypto';\n\n// ============================================================================\n// File Writing\n// ============================================================================\n\nexport interface WriteResult {\n path: string;\n created: boolean;\n updated: boolean;\n unchanged: boolean;\n}\n\nexport function ensureDir(dirPath: string): void {\n if (!existsSync(dirPath)) {\n mkdirSync(dirPath, { recursive: true });\n }\n}\n\nexport function writeFile(filePath: string, content: string): WriteResult {\n const dir = dirname(filePath);\n ensureDir(dir);\n \n const existed = existsSync(filePath);\n let unchanged = false;\n \n if (existed) {\n const existingContent = readFileSync(filePath, 'utf-8');\n unchanged = existingContent === content;\n }\n \n if (!unchanged) {\n writeFileSync(filePath, content, 'utf-8');\n }\n \n return {\n path: filePath,\n created: !existed,\n updated: existed && !unchanged,\n unchanged,\n };\n}\n\nexport function writeJsonFile(filePath: string, data: unknown, indent: number = 2): WriteResult {\n const content = JSON.stringify(data, null, indent) + '\\n';\n return writeFile(filePath, content);\n}\n\n// ============================================================================\n// Batch Writing\n// ============================================================================\n\nexport interface BatchWriteResult {\n results: WriteResult[];\n created: number;\n updated: number;\n unchanged: number;\n total: number;\n}\n\nexport function batchWriteFiles(\n files: Array<{ path: string; content: string }>\n): BatchWriteResult {\n const results: WriteResult[] = [];\n \n for (const { path, content } of files) {\n results.push(writeFile(path, content));\n }\n \n return {\n results,\n created: results.filter(r => r.created).length,\n updated: results.filter(r => r.updated).length,\n unchanged: results.filter(r => r.unchanged).length,\n total: results.length,\n };\n}\n\n// ============================================================================\n// Drift Detection\n// ============================================================================\n\nexport interface DriftResult {\n file: string;\n hasDrift: boolean;\n expectedHash?: string;\n actualHash?: string;\n missing?: boolean;\n}\n\nexport function computeHash(content: string): string {\n return createHash('sha256').update(content).digest('hex').slice(0, 16);\n}\n\nexport function checkFileDrift(\n filePath: string,\n expectedContent: string\n): DriftResult {\n const expectedHash = computeHash(expectedContent);\n \n if (!existsSync(filePath)) {\n return {\n file: filePath,\n hasDrift: true,\n expectedHash,\n missing: true,\n };\n }\n \n const actualContent = readFileSync(filePath, 'utf-8');\n const actualHash = computeHash(actualContent);\n \n return {\n file: filePath,\n hasDrift: expectedHash !== actualHash,\n expectedHash,\n actualHash,\n };\n}\n\nexport function checkBatchDrift(\n files: Array<{ path: string; content: string }>\n): DriftResult[] {\n return files.map(({ path, content }) => checkFileDrift(path, content));\n}\n\n// ============================================================================\n// File Discovery\n// ============================================================================\n\nimport { glob } from 'glob';\n\nexport async function findFiles(\n pattern: string,\n cwd: string = process.cwd()\n): Promise<string[]> {\n return glob(pattern, { cwd, absolute: true });\n}\n\nexport async function findTypeScriptFiles(\n srcDir: string\n): Promise<string[]> {\n return findFiles('**/*.ts', srcDir);\n}\n\nexport async function findDefinitionFiles(\n srcDir: string,\n subDir: string\n): Promise<string[]> {\n const pattern = join(srcDir, subDir, '**/*.ts');\n return glob(pattern, { absolute: true, ignore: ['**/*.d.ts', '**/index.ts'] });\n}\n\n// ============================================================================\n// Output Helpers\n// ============================================================================\n\nexport function generateDocsPath(\n baseDir: string,\n category: string,\n filename: string\n): string {\n return join(baseDir, category, filename);\n}\n\nexport function generateSpecsPath(\n baseDir: string,\n category: string,\n filename: string\n): string {\n return join(baseDir, category, filename);\n}\n"]}
1
+ {"version":3,"sources":["../src/types/common.ts","../src/types/meta-model.ts","../src/core/relation.ts","../src/core/model.ts","../src/core/model-registry.ts","../src/core/config-api.ts","../src/utils/config-loader.ts","../src/utils/file-writer.ts"],"names":["z","parseYaml","existsSync","dirname","readFileSync","join"],"mappings":";;;;;;;;AAMO,IAAM,WAAA,GAAc,CAAA,CAAE,IAAA,CAAK,CAAC,KAAA,EAAO,OAAO,KAAA,EAAO,MAAA,EAAQ,KAAA,EAAO,IAAI,CAAC;AAGrE,IAAM,cAAA,GAAiB,EAAE,IAAA,CAAK,CAAC,QAAQ,QAAA,EAAU,OAAA,EAAS,MAAM,CAAC;AAiCjE,IAAM,mBAAA,GAAsB,CAAC,EAAA,KAA8B;AAC3D,IAAM,iBAAA,GAAoB,CAAC,EAAA,KAA4B;AACvD,IAAM,gBAAA,GAAmB,CAAC,EAAA,KAA2B;AACrD,IAAM,aAAA,GAAgB,CAAC,EAAA,KAAwB;AAC/C,IAAM,cAAA,GAAiB,CAAC,EAAA,KAAyB;AACjD,IAAM,gBAAA,GAAmB,CAAC,EAAA,KAA2B;AACrD,IAAM,YAAA,GAAe,CAAC,EAAA,KAAuB;AAC7C,IAAM,cAAA,GAAiB,CAAC,EAAA,KAAyB;AACjD,IAAM,kBAAA,GAAqB,CAAC,EAAA,KAA6B;AACzD,IAAM,YAAA,GAAe,CAAC,EAAA,KAAuB;AAC7C,IAAM,mBAAA,GAAsB,CAAC,EAAA,KAA8B;AAC3D,IAAM,mBAAA,GAAsB,CAAC,EAAA,KAA8B;AAC3D,IAAM,eAAA,GAAkB,CAAC,EAAA,KAA0B;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,KAAK,OAAA,EAAS,EAAE,GAAA,EAAK,QAAA,EAAU,MAAM,CAAA;AAC9C;AAEA,eAAsB,oBACpB,MAAA,EACmB;AACnB,EAAA,OAAO,SAAA,CAAU,WAAW,MAAM,CAAA;AACpC;AAEA,eAAsB,mBAAA,CACpB,QACA,MAAA,EACmB;AACnB,EAAA,MAAM,OAAA,GAAUC,IAAAA,CAAK,MAAA,EAAQ,MAAA,EAAQ,SAAS,CAAA;AAC9C,EAAA,OAAO,IAAA,CAAK,OAAA,EAAS,EAAE,QAAA,EAAU,IAAA,EAAM,QAAQ,CAAC,WAAA,EAAa,aAAa,CAAA,EAAG,CAAA;AAC/E;AAMO,SAAS,gBAAA,CACd,OAAA,EACA,QAAA,EACA,QAAA,EACQ;AACR,EAAA,OAAOA,IAAAA,CAAK,OAAA,EAAS,QAAA,EAAU,QAAQ,CAAA;AACzC;AAEO,SAAS,iBAAA,CACd,OAAA,EACA,QAAA,EACA,QAAA,EACQ;AACR,EAAA,OAAOA,IAAAA,CAAK,OAAA,EAAS,QAAA,EAAU,QAAQ,CAAA;AACzC","file":"index.js","sourcesContent":["import { z } from 'zod';\n\n// ============================================================================\n// Phase definitions\n// ============================================================================\n\nexport const PhaseSchema = z.enum(['REQ', 'HLD', 'LLD', 'IMPL', 'OPS', 'CI']);\nexport type Phase = z.infer<typeof PhaseSchema>;\n\nexport const PrioritySchema = z.enum(['must', 'should', 'could', 'wont']);\nexport type Priority = z.infer<typeof PrioritySchema>;\n\n// ============================================================================\n// ID types (using simple string types for now)\n// ============================================================================\n\n// ID types - all are strings with semantic meaning\nexport type RequirementId = string;\nexport type ComponentId = string;\nexport type BoundaryId = string;\nexport type LayerId = string;\nexport type EntityId = string;\nexport type RelationId = string;\nexport type RuleId = string;\nexport type ScreenId = string;\nexport type TransitionId = string;\nexport type FormId = string;\nexport type UIComponentId = string;\nexport type ProcessFlowId = string;\nexport type UseCaseId = string;\nexport type ActorId = string;\nexport type DTORequirementId = string;\nexport type EventRequirementId = string;\nexport type APIRefId = string;\nexport type TableRefId = string;\nexport type IaCRefId = string;\nexport type BatchRefId = string;\nexport type ErrorCaseId = string;\nexport type TermId = string;\nexport type StateId = string;\n\n// ID creation helpers (no-op for now, but preserves API for future branding)\nexport const createRequirementId = (id: string): RequirementId => id;\nexport const createComponentId = (id: string): ComponentId => id;\nexport const createBoundaryId = (id: string): BoundaryId => id;\nexport const createLayerId = (id: string): LayerId => id;\nexport const createEntityId = (id: string): EntityId => id;\nexport const createRelationId = (id: string): RelationId => id;\nexport const createRuleId = (id: string): RuleId => id;\nexport const createScreenId = (id: string): ScreenId => id;\nexport const createTransitionId = (id: string): TransitionId => id;\nexport const createFormId = (id: string): FormId => id;\nexport const createUIComponentId = (id: string): UIComponentId => id;\nexport const createProcessFlowId = (id: string): ProcessFlowId => id;\nexport const createUseCaseId = (id: string): UseCaseId => id;\nexport const createActorId = (id: string): ActorId => id;\nexport const createDTORequirementId = (id: string): DTORequirementId => id;\nexport const createEventRequirementId = (id: string): EventRequirementId => id;\nexport const createAPIRefId = (id: string): APIRefId => id;\nexport const createTableRefId = (id: string): TableRefId => id;\nexport const createIaCRefId = (id: string): IaCRefId => id;\nexport const createBatchRefId = (id: string): BatchRefId => id;\nexport const createErrorCaseId = (id: string): ErrorCaseId => id;\nexport const createTermId = (id: string): TermId => id;\nexport const createStateId = (id: string): StateId => id;\n\n// ============================================================================\n// ID Pattern definitions\n// ============================================================================\n\nexport const ID_PATTERNS = {\n requirement: /^REQ-[A-Z]+-\\d{6}-[A-Z0-9]{4}$/,\n component: /^COMP-[A-Z]+-[A-Z0-9-]+$/,\n boundary: /^BND-[A-Z]+-[A-Z0-9-]+$/,\n layer: /^LAYER-[A-Z]+$/,\n entity: /^ENT-[A-Z]+-?[A-Z0-9-]*$/,\n relation: /^REL-[A-Z]+-[A-Z0-9-]+$/,\n rule: /^RULE-[A-Z0-9-]+$/,\n screen: /^SCR-[A-Z]+-?[A-Z0-9-]*$/,\n transition: /^TRANS-[A-Z0-9-]+$/,\n form: /^FORM-[A-Z0-9-]+$/,\n uiComponent: /^UI-[A-Z0-9-]+$/,\n processFlow: /^FLOW-[A-Z]+-[A-Z0-9-]+$/,\n useCase: /^UC-[A-Z]+-\\d{3}$/,\n actor: /^ACTOR-[A-Z]+$/,\n dtoRequirement: /^DTO-REQ-[A-Z0-9-]+$/,\n eventRequirement: /^EVT-REQ-[A-Z0-9-]+$/,\n apiRef: /^API-[A-Z0-9-]+$/,\n tableRef: /^TBL-[A-Z0-9-]+$/,\n iacRef: /^IAC-[A-Z0-9-]+$/,\n batchRef: /^BATCH-[A-Z0-9-]+$/,\n errorCase: /^ERR-[A-Z]+-\\d{3}$/,\n term: /^TERM-[A-Z0-9-]+$/,\n} as const;\n\n// ============================================================================\n// Concretization Slot (TBD management)\n// ============================================================================\n\nexport const ConcretizationSlotSchema = z.object({\n field: z.string(),\n mustDecideBy: PhaseSchema,\n value: z.union([z.string(), z.null()]).optional(),\n description: z.string().optional(),\n});\n\nexport type ConcretizationSlot = z.infer<typeof ConcretizationSlotSchema>;\n\n// ============================================================================\n// Link types\n// ============================================================================\n\nexport interface Link {\n type: 'requirement' | 'component' | 'entity' | 'screen' | 'usecase' | 'external';\n id: string;\n label?: string;\n}\n\nexport const LinkSchema = z.object({\n type: z.enum(['requirement', 'component', 'entity', 'screen', 'usecase', 'external']),\n id: z.string(),\n label: z.string().optional(),\n});\n\n// ============================================================================\n// Validation result types\n// ============================================================================\n\nexport type Severity = 'error' | 'warning' | 'info';\n\nexport interface ValidationError {\n severity: Severity;\n code: string;\n message: string;\n path?: string;\n id?: string;\n suggestions?: string[];\n}\n\nexport interface ValidationResult {\n valid: boolean;\n errors: ValidationError[];\n warnings: ValidationError[];\n}\n\n// ============================================================================\n// Generic model registry (Type definition)\n// Note: Implementation is in utils/model-loader.ts\n// ============================================================================\n\nexport interface ModelRegistrySchema {\n requirements: Map<RequirementId, unknown>;\n components: Map<ComponentId, unknown>;\n boundaries: Map<BoundaryId, unknown>;\n layers: Map<LayerId, unknown>;\n entities: Map<EntityId, unknown>;\n relations: Map<RelationId, unknown>;\n rules: Map<RuleId, unknown>;\n screens: Map<ScreenId, unknown>;\n transitions: Map<TransitionId, unknown>;\n forms: Map<FormId, unknown>;\n uiComponents: Map<UIComponentId, unknown>;\n processFlows: Map<ProcessFlowId, unknown>;\n useCases: Map<UseCaseId, unknown>;\n actors: Map<ActorId, unknown>;\n dtoRequirements: Map<DTORequirementId, unknown>;\n eventRequirements: Map<EventRequirementId, unknown>;\n apiRefs: Map<APIRefId, unknown>;\n tableRefs: Map<TableRefId, unknown>;\n iacRefs: Map<IaCRefId, unknown>;\n batchRefs: Map<BatchRefId, unknown>;\n errorCases: Map<ErrorCaseId, unknown>;\n terms: Map<TermId, unknown>;\n}\n","import { z } from 'zod';\n\n// ============================================================================\n// Meta Model Types - Types for defining models\n// ============================================================================\n\n/**\n * Export Context\n * Context information passed to exporter functions\n */\nexport interface ExportContext {\n /** Access to all models (MetaModelRegistry type, using unknown to avoid circular references) */\n registry: unknown;\n /** Configuration (SpeckeeperConfig type, using unknown to avoid circular references) */\n config: unknown;\n /** Output base directory */\n outputDir: string;\n /** Current date/time */\n generatedAt: Date;\n}\n\n/**\n * Lint Context\n * Context information passed to lint functions\n */\nexport interface LintContext {\n /** Access to all models (MetaModelRegistry type) */\n registry: unknown;\n /** Current phase */\n phase?: 'REQ' | 'HLD' | 'LLD' | 'OPS';\n /** Strict mode */\n strict?: boolean;\n}\n\n/**\n * Check Context\n * Context information passed to external SSOT check functions\n */\nexport interface CheckContext {\n /** Access to all models (MetaModelRegistry type) */\n registry: unknown;\n /** External SSOT file path */\n sourcePath: string;\n /** Configuration (SpeckeeperConfig type) */\n config: unknown;\n}\n\n/**\n * Lint Issue\n */\nexport interface LintIssue {\n /** Issue message */\n message: string;\n /** Problematic field (optional) */\n field?: string;\n /** Fix suggestion (optional) */\n suggestion?: string;\n}\n\n/**\n * Check Result\n */\nexport interface CheckResult {\n /** Whether successful */\n success: boolean;\n /** List of error messages */\n errors: CheckError[];\n /** List of warning messages */\n warnings: CheckWarning[];\n}\n\nexport interface CheckError {\n /** Error message */\n message: string;\n /** Target model ID */\n modelId: string;\n /** External SSOT reference */\n externalRef?: string;\n}\n\nexport interface CheckWarning {\n /** Warning message */\n message: string;\n /** Target model ID */\n modelId: string;\n}\n\n// ============================================================================\n// Exporter Interfaces\n// ============================================================================\n\n/**\n * Markdown Exporter\n */\nexport interface MarkdownExporter<T> {\n /** Single document generation */\n single: (model: T, context: ExportContext) => string;\n /** Index page generation (optional) */\n index?: (models: T[], context: ExportContext) => string;\n /** Output directory (relative path from docs/) */\n outputDir: string;\n /** Filename generation (default is model.id) */\n filename?: (model: T) => string;\n}\n\n/**\n * Mermaid Diagram Exporter\n */\nexport interface MermaidExporter<T> {\n /** Diagram type */\n diagramType: 'flowchart' | 'sequenceDiagram' | 'erDiagram' | 'stateDiagram' | 'C4Context' | 'C4Container' | 'C4Component' | 'custom';\n /** Diagram generation function */\n generate: (models: T[], context: ExportContext) => string;\n /** Output file path (relative path from docs/) */\n outputPath: string;\n /** Diagram title */\n title?: string;\n}\n\n/**\n * JSON Schema Exporter Settings\n */\nexport interface JsonSchemaExporter {\n /** Enabled */\n enabled: boolean;\n /** Output directory (relative path from specs/) */\n outputDir: string;\n}\n\n// ============================================================================\n// Lint Rule Interface\n// ============================================================================\n\n/**\n * Lint Rule\n */\nexport interface LintRule<T> {\n /** Rule ID */\n id: string;\n /** Rule description */\n description: string;\n /** Severity */\n severity: 'error' | 'warning' | 'info';\n /** Check function */\n check: (model: T, context: LintContext) => LintIssue | null;\n}\n\n// ============================================================================\n// External Checker Interface\n// ============================================================================\n\n/**\n * External SSOT Checker\n */\nexport interface ExternalChecker<T> {\n /** External SSOT type to check */\n targetType: 'openapi' | 'ddl' | 'iac' | 'custom';\n /** Execute check */\n check: (model: T, externalSource: unknown, context: CheckContext) => CheckResult;\n /** Get external SSOT file path (from model) */\n getSourcePath?: (model: T) => string | undefined;\n}\n\n// ============================================================================\n// Reference Definition\n// ============================================================================\n\n/**\n * Inter-model Reference Definition (for traceability)\n */\nexport interface ReferenceDefinition {\n /** Field name with reference */\n field: string;\n /** Referenced model ID */\n targetModel: string;\n /** Whether reference is required */\n required?: boolean;\n /** Whether reference is array */\n isArray?: boolean;\n}\n\n// ============================================================================\n// Model Definition Interface\n// ============================================================================\n\n/**\n * Model Definition\n * Interface for users to define new entities\n */\nexport interface ModelDefinition<T extends z.ZodTypeAny = z.ZodTypeAny> {\n /** Model unique identifier (kebab-case recommended) */\n id: string;\n /** Model name (PascalCase recommended) */\n name: string;\n /** Model description */\n description: string;\n \n /** Zod Schema */\n schema: T;\n \n /** ID prefix for generation */\n idPrefix: string;\n \n /** Exporter settings */\n exporters?: {\n /** Markdown exporter */\n markdown?: MarkdownExporter<z.infer<T>>;\n /** Mermaid diagram exporter (multiple allowed) */\n mermaid?: MermaidExporter<z.infer<T>> | MermaidExporter<z.infer<T>>[];\n /** JSON Schema exporter */\n jsonSchema?: JsonSchemaExporter;\n };\n \n /** Lint rules */\n lintRules?: LintRule<z.infer<T>>[];\n \n /** External SSOT checker */\n externalChecker?: ExternalChecker<z.infer<T>>;\n \n /** Reference definitions (for traceability) */\n references?: ReferenceDefinition[];\n \n /** DSL function name (the Xxx part of defineXxx) */\n dslName?: string;\n \n /** Phase (the phase where this model is primarily used) */\n phase?: 'REQ' | 'HLD' | 'LLD' | 'OPS';\n}\n\n// ============================================================================\n// Model Registry Interface\n// ============================================================================\n\n/**\n * Meta Model Registry\n * Manages registered model definitions and model instances\n */\nexport interface MetaModelRegistry {\n /** Registered model definitions */\n definitions: Map<string, ModelDefinition>;\n /** Model instances (Map<instanceId, instance> for each model ID) */\n instances: Map<string, Map<string, unknown>>;\n}\n\n// ============================================================================\n// Meta Config Interface (extends base config)\n// ============================================================================\n\n/**\n * Additional settings for meta model\n */\nexport interface MetaModelConfig {\n /** Custom model definitions */\n models?: ModelDefinition[];\n /** External SSOT settings */\n externalSsot?: {\n openapi?: {\n enabled: boolean;\n paths: string[];\n };\n ddl?: {\n enabled: boolean;\n type: 'ddl' | 'prisma' | 'typeorm' | 'drizzle';\n path: string;\n };\n iac?: {\n enabled: boolean;\n type: 'cloudformation' | 'cdk' | 'terraform';\n path: string;\n };\n };\n}\n\n// ============================================================================\n// Helper Types\n// ============================================================================\n\n/**\n * Base type for model instances\n * All model instances have an id\n */\nexport interface BaseModelInstance {\n id: string;\n}\n\n/**\n * Helper type for creating type-safe model definitions\n */\nexport type InferModelType<T extends ModelDefinition> = z.infer<T['schema']>;\n\n// ============================================================================\n// Zod Schemas for Meta Types\n// ============================================================================\n\nexport const ReferenceDefinitionSchema = z.object({\n field: z.string(),\n targetModel: z.string(),\n required: z.boolean().optional(),\n isArray: z.boolean().optional(),\n});\n\nexport const LintIssueSchema = z.object({\n message: z.string(),\n field: z.string().optional(),\n suggestion: z.string().optional(),\n});\n\nexport const CheckErrorSchema = z.object({\n message: z.string(),\n modelId: z.string(),\n externalRef: z.string().optional(),\n});\n\nexport const CheckWarningSchema = z.object({\n message: z.string(),\n modelId: z.string(),\n});\n\nexport const CheckResultSchema = z.object({\n success: z.boolean(),\n errors: z.array(CheckErrorSchema),\n warnings: z.array(CheckWarningSchema),\n});\n","/**\n * Definition and validation of model relations\n */\nimport { z } from 'zod';\n\n// ============================================================================\n// Model Levels\n// ============================================================================\n\n/**\n * Model abstraction level\n * \n * - L0: Business + Domain Analysis (Why / Problem space)\n * Desired outcomes/value, business flows, actors, terminology, business rules\n * - L1: Requirements (What)\n * Functional/non-functional requirements, constraints, acceptance criteria\n * - L2: Design (How / Direction)\n * Architecture, component breakdown, domain model, key sequences\n * - L3: Detailed Design/Implementation (How to build / Concrete artifacts)\n * Screen/API/DB definitions, external SSOT references\n */\nexport type ModelLevel = 'L0' | 'L1' | 'L2' | 'L3';\n\n/**\n * Get numeric index of level\n */\nexport function getLevelIndex(level: ModelLevel): number {\n return ['L0', 'L1', 'L2', 'L3'].indexOf(level);\n}\n\n// ============================================================================\n// Relation Types\n// ============================================================================\n\n/**\n * Relation types\n */\nexport const RELATION_TYPES = [\n 'dependsOn',\n 'uses',\n 'includes',\n 'implements',\n 'refines',\n 'verifies',\n 'satisfies',\n 'traces',\n 'relatedTo',\n] as const;\n\nexport type RelationType = typeof RELATION_TYPES[number];\n\n/**\n * Relation schema\n */\nexport const RelationSchema = z.object({\n /** Relation type */\n type: z.enum(RELATION_TYPES),\n /** Target ID */\n target: z.string(),\n /** Description (optional) */\n description: z.string().optional(),\n});\n\n/**\n * Relation field to add to model schemas\n * Usage: schema.extend({ relations: RelationsFieldSchema })\n */\nexport const RelationsFieldSchema = z.array(RelationSchema).optional();\n\nexport type Relation = z.infer<typeof RelationSchema>;\n\n// ============================================================================\n// Relation Constraints\n// ============================================================================\n\n/**\n * Definition of relation constraints\n */\nexport interface RelationConstraint {\n /** Allowed target levels (all levels allowed if not specified) */\n allowedTargetLevels?: ModelLevel[];\n /** Level constraint rule */\n levelRule: 'source>target' | 'source>=target' | 'same' | 'any';\n /** Direction of impact propagation */\n propagation: 'forward' | 'backward' | 'both';\n}\n\n/**\n * Constraint definitions per relation type\n * \n * Level hierarchy:\n * L0 (Business) → L1 (Requirements) → L2 (Design) → L3 (Implementation)\n * Abstract ───────────────────────────→ Concrete\n */\nexport const RELATION_CONSTRAINTS: Record<RelationType, RelationConstraint> = {\n // Concrete→Abstract (implementation/design fulfills requirements)\n 'implements': {\n allowedTargetLevels: ['L1'], // Implements requirements\n levelRule: 'source>target',\n propagation: 'forward', // A changes → B needs review\n },\n // Concrete→Abstract (design/implementation satisfies business/requirements)\n 'satisfies': {\n allowedTargetLevels: ['L0', 'L1'], // Satisfies business/requirements\n levelRule: 'source>=target',\n propagation: 'backward', // B changes → A needs update\n },\n // Concrete→Abstract (refinement: requirements refine business, design refines requirements)\n 'refines': {\n allowedTargetLevels: ['L0', 'L1'], // Refines business/requirements\n levelRule: 'source>target',\n propagation: 'backward', // B changes → A needs update\n },\n // Test→Requirements/Business (verification relationship)\n 'verifies': {\n allowedTargetLevels: ['L0', 'L1'], // Verifies business/requirements\n levelRule: 'any',\n propagation: 'backward', // B changes → A needs update\n },\n // Dependencies (same level or concrete→abstract)\n 'dependsOn': {\n levelRule: 'source>=target',\n propagation: 'backward', // B changes → A affected\n },\n // Usage relationship (no level constraint)\n 'uses': {\n levelRule: 'any',\n propagation: 'backward', // B changes → A affected\n },\n // Inclusion relationship (same level only)\n 'includes': {\n levelRule: 'same',\n propagation: 'backward', // B changes → A affected\n },\n // Bidirectional tracing\n 'traces': {\n levelRule: 'any',\n propagation: 'both',\n },\n // General relation\n 'relatedTo': {\n levelRule: 'any',\n propagation: 'both',\n },\n};\n\n// ============================================================================\n// Relation Validation\n// ============================================================================\n\n/**\n * Relation validation result\n */\nexport interface RelationValidationResult {\n valid: boolean;\n errors: RelationValidationError[];\n}\n\n/**\n * Relation validation error\n */\nexport interface RelationValidationError {\n type: 'level_violation' | 'target_level_violation' | 'self_reference' | 'cycle_detected';\n message: string;\n relation: Relation;\n sourceId: string;\n}\n\n/**\n * Validate level constraint for single relation\n * \n * @param sourceLevel - Source model level (set in _models/)\n * @param sourceSpecId - Source spec ID\n * @param relation - Relation\n * @param targetLevel - Target model level\n */\nexport function validateRelationLevel(\n sourceLevel: ModelLevel | undefined,\n sourceSpecId: string,\n relation: Relation,\n targetLevel: ModelLevel | undefined,\n): RelationValidationError | null {\n // Self-reference check\n if (sourceSpecId === relation.target) {\n return {\n type: 'self_reference',\n message: `Self-reference is not allowed: ${sourceSpecId} → ${relation.target}`,\n relation,\n sourceId: sourceSpecId,\n };\n }\n\n // Skip if level is undefined\n if (!sourceLevel || !targetLevel) {\n return null;\n }\n \n const constraint = RELATION_CONSTRAINTS[relation.type];\n \n // Target level constraint check\n if (constraint.allowedTargetLevels && \n !constraint.allowedTargetLevels.includes(targetLevel)) {\n return {\n type: 'target_level_violation',\n message: `'${relation.type}' relation target must be ${constraint.allowedTargetLevels.join(' or ')}, but target is ${targetLevel}`,\n relation,\n sourceId: sourceSpecId,\n };\n }\n \n // Level direction constraint check\n const srcIdx = getLevelIndex(sourceLevel);\n const tgtIdx = getLevelIndex(targetLevel);\n \n switch (constraint.levelRule) {\n case 'source>target':\n if (srcIdx <= tgtIdx) {\n return {\n type: 'level_violation',\n message: `'${relation.type}' requires source (${sourceLevel}) to be more concrete than target (${targetLevel})`,\n relation,\n sourceId: sourceSpecId,\n };\n }\n break;\n case 'source>=target':\n if (srcIdx < tgtIdx) {\n return {\n type: 'level_violation',\n message: `'${relation.type}' requires source (${sourceLevel}) to be same or more concrete than target (${targetLevel})`,\n relation,\n sourceId: sourceSpecId,\n };\n }\n break;\n case 'same':\n if (srcIdx !== tgtIdx) {\n return {\n type: 'level_violation',\n message: `'${relation.type}' requires source (${sourceLevel}) and target (${targetLevel}) to be same level`,\n relation,\n sourceId: sourceSpecId,\n };\n }\n break;\n }\n \n return null;\n}\n\n/**\n * Detect circular references\n */\nexport function detectCycles(\n relations: Array<{ sourceId: string; targetId: string; type: RelationType }>,\n): RelationValidationError[] {\n const errors: RelationValidationError[] = [];\n const graph = new Map<string, Set<string>>();\n const relationMap = new Map<string, Relation>();\n \n // Build graph\n for (const rel of relations) {\n if (!graph.has(rel.sourceId)) {\n graph.set(rel.sourceId, new Set());\n }\n graph.get(rel.sourceId)!.add(rel.targetId);\n relationMap.set(`${rel.sourceId}→${rel.targetId}`, { type: rel.type, target: rel.targetId });\n }\n \n // Detect cycles using DFS\n const visited = new Set<string>();\n const recursionStack = new Set<string>();\n const cyclePath: string[] = [];\n \n function dfs(node: string): boolean {\n visited.add(node);\n recursionStack.add(node);\n cyclePath.push(node);\n \n const neighbors = graph.get(node);\n if (neighbors) {\n for (const neighbor of neighbors) {\n if (!visited.has(neighbor)) {\n if (dfs(neighbor)) {\n return true;\n }\n } else if (recursionStack.has(neighbor)) {\n // Cycle detected\n const cycleStart = cyclePath.indexOf(neighbor);\n const cycle = cyclePath.slice(cycleStart);\n cycle.push(neighbor); // Close the cycle\n \n errors.push({\n type: 'cycle_detected',\n message: `Circular reference detected: ${cycle.join(' → ')}`,\n relation: relationMap.get(`${node}→${neighbor}`)!,\n sourceId: node,\n });\n return true;\n }\n }\n }\n \n cyclePath.pop();\n recursionStack.delete(node);\n return false;\n }\n \n for (const node of graph.keys()) {\n if (!visited.has(node)) {\n dfs(node);\n }\n }\n \n return errors;\n}\n\n/**\n * Infer model ID from spec ID (prefix-based)\n */\nexport function inferModelIdFromSpecId(specId: string): string | undefined {\n const prefixMap: Record<string, string> = {\n 'REQ': 'requirement',\n 'CR': 'constraint',\n 'UC': 'usecase',\n 'ACTOR': 'actor',\n 'TERM': 'term',\n 'COMP': 'component',\n 'ENT': 'entity',\n 'FLOW': 'process-flow',\n 'LAYER': 'layer',\n 'BND': 'boundary',\n 'SCR': 'screen',\n 'API': 'api-ref',\n 'TBL': 'table-ref',\n 'IAC': 'iac-ref',\n 'BATCH': 'batch-ref',\n };\n \n for (const [prefix, modelId] of Object.entries(prefixMap)) {\n if (specId.startsWith(prefix + '-')) {\n return modelId;\n }\n }\n \n return undefined;\n}\n","/**\n * Model base class\n * \n * All model definitions inherit from this class\n */\nimport { z, ZodType } from 'zod';\nimport {\n type ModelLevel,\n type Relation,\n type RelationValidationError,\n validateRelationLevel,\n detectCycles,\n inferModelIdFromSpecId,\n} from './relation.js';\n\n// Re-export relation types\nexport type { ModelLevel, Relation, RelationValidationError };\nexport { RELATION_TYPES, RELATION_CONSTRAINTS, RelationSchema, RelationsFieldSchema } from './relation.js';\n\n// ============================================================================\n// Type Definitions\n// ============================================================================\n\n/**\n * Lint rule definition\n */\nexport interface LintRule<T> {\n id: string;\n severity: 'error' | 'warning' | 'info';\n message: string;\n check: (spec: T) => boolean; // true if there is an issue\n}\n\n/**\n * Lint result\n */\nexport interface LintResult {\n ruleId: string;\n severity: 'error' | 'warning' | 'info';\n message: string;\n specId?: string;\n}\n\n/**\n * Exporter definition\n */\nexport interface Exporter<T> {\n format: 'markdown' | 'json' | 'mermaid';\n single?: (spec: T) => string;\n index?: (specs: T[]) => string;\n outputDir?: string;\n filename?: (spec: T) => string;\n}\n\n/**\n * External checker definition\n */\nexport interface ExternalChecker<T> {\n targetType: string; // 'openapi' | 'ddl' | 'cli' etc.\n sourcePath: (spec: T) => string;\n check: (spec: T, externalData: unknown) => CheckResult;\n}\n\n/**\n * Check result\n */\nexport interface CheckResult {\n success: boolean;\n errors: { message: string; field?: string; specId?: string }[];\n warnings: { message: string; field?: string; specId?: string }[];\n}\n\n/**\n * Coverage result\n */\nexport interface CoverageResult {\n /** Total target count */\n total: number;\n /** Covered count */\n covered: number;\n /** Uncovered count */\n uncovered: number;\n /** Coverage rate (%) */\n coveragePercent: number;\n /** Details of covered items */\n coveredItems: { id: string; description?: string }[];\n /** Details of uncovered items */\n uncoveredItems: { id: string; description?: string; sourceId?: string }[];\n}\n\n/**\n * Coverage checker definition\n * \n * Verify cross-model consistency (coverage).\n * Example: Whether TestRef covers acceptanceCriteria of Requirement\n */\nexport interface CoverageChecker<T> {\n /** Target model ID for coverage (e.g. 'requirement') */\n targetModel: string;\n /** Description of coverage check */\n description: string;\n /** Execute coverage check */\n check: (\n specs: T[],\n registry: Record<string, Map<string, unknown>>\n ) => CoverageResult;\n}\n\n// ============================================================================\n// Renderer (for embeds)\n// ============================================================================\n\n/**\n * Render context\n * Simplified version compatible with embedoc's EmbedContext\n */\nexport interface RenderContext {\n /** Parameters (filter conditions other than format, etc.) */\n params: Record<string, string | undefined>;\n /** Markdown helpers */\n markdown: {\n /** Generate table */\n table: (headers: string[], rows: (string | unknown)[][]) => string;\n };\n}\n\n/**\n * Renderer definition\n * \n * Model-specific rendering called from embeds\n */\nexport interface Renderer<T> {\n /** Format ID ('table', 'list', 'detail', 'spec-chapter', etc.) */\n format: string;\n /** Rendering process */\n render: (specs: T[], ctx: RenderContext) => string;\n}\n\n// ============================================================================\n// Model Base Class\n// ============================================================================\n\n/**\n * Model base class\n * \n * @template TSchema - Zod schema type\n */\nexport abstract class Model<TSchema extends ZodType> {\n /** Singleton instance storage (per subclass) */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private static _instances: WeakMap<new () => any, Model<ZodType>> = new WeakMap();\n\n /**\n * Get singleton instance of the model\n * Usage: RequirementModel.instance\n */\n static get instance(): Model<ZodType> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const ctor = this as unknown as new () => any;\n if (!this._instances.has(ctor)) {\n this._instances.set(ctor, new ctor());\n }\n return this._instances.get(ctor)!;\n }\n\n /** Model ID ('requirement', 'usecase', etc.) */\n abstract readonly id: string;\n \n /** Model name ('Requirement', 'UseCase', etc.) */\n abstract readonly name: string;\n \n /** ID prefix ('REQ', 'UC', etc.) */\n abstract readonly idPrefix: string;\n \n /** Zod schema */\n abstract readonly schema: TSchema;\n \n /** Model description (optional) */\n readonly description?: string;\n \n /** External SSOT type (optional, e.g. 'OpenAPI', 'DDL/Prisma') */\n readonly externalSsotType?: string;\n \n /** Spec instance type */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected get specType(): z.infer<TSchema> { return undefined as any; }\n \n /** Lint rules (override in subclass) */\n protected lintRules: LintRule<z.infer<TSchema>>[] = [];\n \n /** Exporters (override in subclass) */\n protected exporters: Exporter<z.infer<TSchema>>[] = [];\n \n /** External checker (optional) */\n protected externalChecker?: ExternalChecker<z.infer<TSchema>>;\n \n /** Coverage checker (optional) */\n protected coverageChecker?: CoverageChecker<z.infer<TSchema>>;\n \n /** Model level (set in _models/) */\n protected modelLevel?: ModelLevel;\n \n /** Renderers (for embeds, override in subclass) */\n protected renderers: Renderer<z.infer<TSchema>>[] = [];\n \n /**\n * Get model level\n * Returns modelLevel set in _models/\n */\n get level(): ModelLevel | undefined {\n return this.modelLevel;\n }\n \n /**\n * Execute schema validation\n */\n validate(spec: unknown): z.infer<TSchema> {\n return this.schema.parse(spec);\n }\n \n /**\n * Schema validation (safe version, returns error object on failure)\n */\n safeParse(spec: unknown): { success: true; data: z.infer<TSchema> } | { success: false; error: z.ZodError } {\n return this.schema.safeParse(spec);\n }\n \n /**\n * Execute lint\n */\n lint(spec: z.infer<TSchema>): LintResult[] {\n const specId = (spec as { id?: string }).id;\n return this.lintRules\n .filter(rule => rule.check(spec))\n .map(rule => ({\n ruleId: rule.id,\n severity: rule.severity,\n message: rule.message,\n specId,\n }));\n }\n \n /**\n * Execute lint for multiple specs\n */\n lintAll(specs: z.infer<TSchema>[]): LintResult[] {\n return specs.flatMap(spec => this.lint(spec));\n }\n \n /**\n * Validate level constraints of relations\n * @param spec - Spec instance (if it has relations property)\n * @returns Array of validation errors\n */\n validateRelations(spec: z.infer<TSchema>): RelationValidationError[] {\n const errors: RelationValidationError[] = [];\n const specWithRelations = spec as { id?: string; relations?: Relation[] };\n \n if (!specWithRelations.relations || !specWithRelations.id) {\n return errors;\n }\n \n // Get all models to retrieve target model levels\n const allModels = getAllModels();\n const modelLevelMap = new Map<string, ModelLevel | undefined>();\n for (const model of allModels) {\n modelLevelMap.set(model.id, model.level);\n }\n \n for (const relation of specWithRelations.relations) {\n // Infer target model ID\n const targetModelId = inferModelIdFromSpecId(relation.target);\n if (!targetModelId) {\n continue; // Skip if model ID cannot be inferred\n }\n \n const targetLevel = modelLevelMap.get(targetModelId);\n \n const error = validateRelationLevel(\n this.level,\n specWithRelations.id,\n relation,\n targetLevel,\n );\n \n if (error) {\n errors.push(error);\n }\n }\n \n return errors;\n }\n \n /**\n * Validate relations of multiple specs (including circular reference check)\n */\n validateAllRelations(specs: z.infer<TSchema>[]): RelationValidationError[] {\n const errors: RelationValidationError[] = [];\n const allRelations: Array<{ sourceId: string; targetId: string; type: string }> = [];\n \n for (const spec of specs) {\n // Individual level constraint check\n errors.push(...this.validateRelations(spec));\n \n // Collect relations for circular reference check\n const specWithRelations = spec as { id?: string; relations?: Relation[] };\n if (specWithRelations.relations && specWithRelations.id) {\n for (const rel of specWithRelations.relations) {\n allRelations.push({\n sourceId: specWithRelations.id,\n targetId: rel.target,\n type: rel.type,\n });\n }\n }\n }\n \n // Circular reference check\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n errors.push(...detectCycles(allRelations as any));\n \n return errors;\n }\n \n /**\n * Export in specified format (single spec)\n */\n exportSingle(spec: z.infer<TSchema>, format: string): string | null {\n const exporter = this.exporters.find(e => e.format === format);\n if (!exporter?.single) return null;\n return exporter.single(spec);\n }\n \n /**\n * Export in specified format (index)\n */\n exportIndex(specs: z.infer<TSchema>[], format: string): string | null {\n const exporter = this.exporters.find(e => e.format === format);\n if (!exporter?.index) return null;\n return exporter.index(specs);\n }\n \n /**\n * Get exporter output directory\n */\n getOutputDir(format: string): string | null {\n const exporter = this.exporters.find(e => e.format === format);\n return exporter?.outputDir ?? null;\n }\n \n /**\n * Get filename\n */\n getFilename(spec: z.infer<TSchema>, format: string): string | null {\n const exporter = this.exporters.find(e => e.format === format);\n if (!exporter?.filename) return null;\n return exporter.filename(spec);\n }\n \n /**\n * Check consistency with external SSOT\n */\n check(spec: z.infer<TSchema>, externalData: unknown): CheckResult {\n if (!this.externalChecker) {\n return { success: true, errors: [], warnings: [] };\n }\n return this.externalChecker.check(spec, externalData);\n }\n \n /**\n * Get external SSOT path\n */\n getExternalSourcePath(spec: z.infer<TSchema>): string | null {\n if (!this.externalChecker) return null;\n return this.externalChecker.sourcePath(spec);\n }\n \n /**\n * Execute coverage check\n * @param specs - Array of spec instances for this model\n * @param registry - Registry of all models\n */\n checkCoverage(\n specs: z.infer<TSchema>[],\n registry: Record<string, Map<string, unknown>>\n ): CoverageResult | null {\n if (!this.coverageChecker) return null;\n return this.coverageChecker.check(specs, registry);\n }\n \n /**\n * Get coverage checker\n */\n getCoverageChecker(): CoverageChecker<z.infer<TSchema>> | undefined {\n return this.coverageChecker;\n }\n \n /**\n * Get lint rules\n */\n getLintRules(): LintRule<z.infer<TSchema>>[] {\n return this.lintRules;\n }\n \n /**\n * Get exporters\n */\n getExporters(): Exporter<z.infer<TSchema>>[] {\n return this.exporters;\n }\n \n // ============================================================================\n // Renderer (for embeds)\n // ============================================================================\n \n /**\n * Render in specified format\n * @param format - Format ID ('table', 'list', 'detail', etc.)\n * @param specs - Array of specs to render\n * @param ctx - Render context\n * @returns Rendered result (Markdown string), null if no matching renderer\n */\n render(format: string, specs: z.infer<TSchema>[], ctx: RenderContext): string | null {\n const renderer = this.renderers.find(r => r.format === format);\n if (!renderer) return null;\n return renderer.render(specs, ctx);\n }\n \n /**\n * Get list of available formats\n */\n getAvailableFormats(): string[] {\n return this.renderers.map(r => r.format);\n }\n \n /**\n * Get renderers\n */\n getRenderers(): Renderer<z.infer<TSchema>>[] {\n return this.renderers;\n }\n \n /**\n * Check if renderer exists for specific format\n */\n hasRenderer(format: string): boolean {\n return this.renderers.some(r => r.format === format);\n }\n \n /**\n * Register spec instances for this model.\n * Stores specs in the global specStore keyed by this model's id.\n */\n register(specs: z.infer<TSchema>[]): void {\n if (!specStore.has(this.id)) {\n specStore.set(this.id, new Map());\n }\n const map = specStore.get(this.id)!;\n for (const spec of specs) {\n map.set((spec as { id: string }).id, spec);\n }\n }\n}\n\n// ============================================================================\n// Spec Store\n// ============================================================================\n\nconst specStore = new Map<string, Map<string, unknown>>();\n\n/**\n * Get the global spec store (model ID → spec ID → spec data)\n */\nexport function getSpecStore(): Map<string, Map<string, unknown>> {\n return specStore;\n}\n\n/**\n * Reset the spec store (clears all registered specs)\n */\nexport function resetSpecStore(): void {\n specStore.clear();\n}\n\n// ============================================================================\n// Model Registry\n// ============================================================================\n\n/** Map of registered models */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst modelRegistry = new Map<string, Model<any>>();\n\n/**\n * Register model\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function registerModel(model: Model<any>): void {\n modelRegistry.set(model.id, model);\n}\n\n/**\n * Get model\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getModel(id: string): Model<any> | undefined {\n return modelRegistry.get(id);\n}\n\n/**\n * Get all registered models\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getAllModels(): Model<any>[] {\n return Array.from(modelRegistry.values());\n}\n\n/**\n * Clear registry\n */\nexport function clearModelRegistry(): void {\n modelRegistry.clear();\n}\n\n/**\n * Register model instances from config.models array.\n * Filters out non-Model values. Call this once after config is loaded.\n */\nexport function registerModelsFromConfig(models: unknown[]): void {\n for (const model of models) {\n if (model && typeof model === 'object' && 'id' in model && 'schema' in model) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n registerModel(model as Model<any>);\n }\n }\n}\n\n/**\n * Get specs for a given model ID from specStore\n */\nexport function getSpecs(modelId: string): unknown[] {\n const map = specStore.get(modelId);\n if (!map) return [];\n return Array.from(map.values());\n}\n\n/**\n * Get all spec IDs across all models\n */\nexport function getAllSpecIds(): Set<string> {\n const ids = new Set<string>();\n for (const map of specStore.values()) {\n for (const id of map.keys()) {\n ids.add(id);\n }\n }\n return ids;\n}\n\n/**\n * Find which model type a spec ID belongs to\n */\nexport function findModelTypeBySpecId(specId: string): string | null {\n for (const [modelId, map] of specStore) {\n if (map.has(specId)) return modelId;\n }\n return null;\n}\n\n/**\n * Get a spec by ID (searches all models)\n */\nexport function getSpecById(specId: string): { modelId: string; spec: unknown } | null {\n const modelId = findModelTypeBySpecId(specId);\n if (!modelId) return null;\n return { modelId, spec: specStore.get(modelId)!.get(specId) };\n}\n\n// ============================================================================\n// SpecModule: Common interface for spec data files\n// ============================================================================\n\n/**\n * A single (Model, data[]) pair.\n * Uses structural typing (not nominal Model<any>) so that\n * compiled dist/ Model instances are compatible with src/ types.\n */\nexport interface SpecEntry {\n model: { id: string; register: (data: unknown[]) => void };\n data: unknown[];\n}\n\n/**\n * Common export interface for spec data files.\n * Each spec file exports a SpecModule via defineSpecs().\n */\nexport interface SpecModule {\n entries: SpecEntry[];\n}\n\n/**\n * Aggregated result from mergeSpecs().\n */\nexport interface MergedDesign {\n models: SpecEntry['model'][];\n specs: SpecEntry[];\n}\n\n/**\n * Define spec data in a spec file. Returns a SpecModule.\n *\n * @example\n * ```typescript\n * export default defineSpecs(\n * [FunctionalRequirementModel.instance, functionalRequirements],\n * [NonFunctionalRequirementModel.instance, nonFunctionalRequirements],\n * );\n * ```\n */\nexport function defineSpecs(...entries: [SpecEntry['model'], unknown[]][]): SpecModule {\n return {\n entries: entries.map(([model, data]) => ({ model, data })),\n };\n}\n\n/**\n * Merge multiple SpecModules into a single MergedDesign.\n * Models are deduplicated by model.id.\n *\n * @example\n * ```typescript\n * // design/index.ts\n * export default mergeSpecs(requirements, usecases, glossary);\n * ```\n */\nexport function mergeSpecs(...modules: SpecModule[]): MergedDesign {\n const modelMap = new Map<string, SpecEntry['model']>();\n const allSpecs: SpecEntry[] = [];\n\n for (const mod of modules) {\n for (const entry of mod.entries) {\n modelMap.set(entry.model.id, entry.model);\n allSpecs.push(entry);\n }\n }\n\n return {\n models: Array.from(modelMap.values()),\n specs: allSpecs,\n };\n}\n\n/**\n * Build a registry (modelId -> Map<specId, spec>) from config.specs.\n * Pure function — no global state.\n */\nexport function buildRegistryFromConfig(\n specs: SpecEntry[] | undefined\n): Record<string, Map<string, unknown>> {\n const registry: Record<string, Map<string, unknown>> = {};\n if (!specs) return registry;\n for (const entry of specs) {\n if (!registry[entry.model.id]) {\n registry[entry.model.id] = new Map();\n }\n const map = registry[entry.model.id];\n for (const spec of entry.data) {\n map.set((spec as { id: string }).id, spec);\n }\n }\n return registry;\n}\n\n/**\n * Get specs for a model ID from config.specs.\n * Pure function — no global state.\n */\nexport function getSpecsFromConfig(\n specs: SpecEntry[] | undefined,\n modelId: string\n): unknown[] {\n if (!specs) return [];\n return specs\n .filter(e => e.model.id === modelId)\n .flatMap(e => e.data);\n}\n\n/**\n * Find which model type a spec ID belongs to, from config.specs.\n * Pure function — no global state.\n */\nexport function findModelTypeFromConfig(\n specs: SpecEntry[] | undefined,\n specId: string\n): string | null {\n if (!specs) return null;\n for (const entry of specs) {\n for (const spec of entry.data) {\n if ((spec as { id: string }).id === specId) {\n return entry.model.id;\n }\n }\n }\n return null;\n}\n","import { z } from 'zod';\nimport type {\n ModelDefinition,\n MetaModelRegistry,\n LintRule,\n LintContext,\n LintIssue,\n ExportContext,\n CheckContext,\n CheckResult,\n MarkdownExporter,\n MermaidExporter,\n ExternalChecker,\n} from '../types/meta-model.js';\n\n// ============================================================================\n// Global Registry\n// ============================================================================\n\n/**\n * Global model registry\n */\nconst globalRegistry: MetaModelRegistry = {\n definitions: new Map(),\n instances: new Map(),\n};\n\n// ============================================================================\n// Model Definition Registration\n// ============================================================================\n\n/**\n * Register model definition\n */\nexport function registerModelDefinition<T extends z.ZodTypeAny>(\n definition: ModelDefinition<T>\n): void {\n if (globalRegistry.definitions.has(definition.id)) {\n console.warn(`Model definition '${definition.id}' is already registered. Overwriting.`);\n }\n \n // Store in generic registry while maintaining type safety\n globalRegistry.definitions.set(definition.id, definition as unknown as ModelDefinition);\n \n // Initialize Map for instances\n if (!globalRegistry.instances.has(definition.id)) {\n globalRegistry.instances.set(definition.id, new Map());\n }\n}\n\n/**\n * Register multiple model definitions at once\n */\nexport function registerModelDefinitions(definitions: ModelDefinition[]): void {\n for (const def of definitions) {\n registerModelDefinition(def);\n }\n}\n\n/**\n * Get model definition\n */\nexport function getModelDefinition(modelId: string): ModelDefinition | undefined {\n return globalRegistry.definitions.get(modelId);\n}\n\n/**\n * Get all model definitions\n */\nexport function getAllModelDefinitions(): ModelDefinition[] {\n return Array.from(globalRegistry.definitions.values());\n}\n\n// ============================================================================\n// Model Instance Registration\n// ============================================================================\n\n/**\n * Register model instance\n */\nexport function registerModelInstance<T extends { id: string }>(\n modelId: string,\n instance: T\n): void {\n const definition = globalRegistry.definitions.get(modelId);\n if (!definition) {\n throw new Error(`Model definition '${modelId}' not found. Register the definition first.`);\n }\n \n // Validate with schema\n const result = definition.schema.safeParse(instance);\n if (!result.success) {\n throw new Error(\n `Invalid instance for model '${modelId}': ${result.error.message}`\n );\n }\n \n let instances = globalRegistry.instances.get(modelId);\n if (!instances) {\n instances = new Map();\n globalRegistry.instances.set(modelId, instances);\n }\n \n instances.set(instance.id, instance);\n}\n\n/**\n * Get model instance\n */\nexport function getModelInstance<T = unknown>(\n modelId: string,\n instanceId: string\n): T | undefined {\n const instances = globalRegistry.instances.get(modelId);\n return instances?.get(instanceId) as T | undefined;\n}\n\n/**\n * Get all instances of a model\n */\nexport function getAllModelInstances<T = unknown>(modelId: string): T[] {\n const instances = globalRegistry.instances.get(modelId);\n if (!instances) return [];\n return Array.from(instances.values()) as T[];\n}\n\n/**\n * Get all instances of all models (flattened)\n */\nexport function getAllInstances(): Array<{ modelId: string; instance: unknown }> {\n const result: Array<{ modelId: string; instance: unknown }> = [];\n \n for (const [modelId, instances] of globalRegistry.instances) {\n for (const instance of instances.values()) {\n result.push({ modelId, instance });\n }\n }\n \n return result;\n}\n\n// ============================================================================\n// Registry Access\n// ============================================================================\n\n/**\n * Get global registry\n */\nexport function getGlobalModelRegistry(): MetaModelRegistry {\n return globalRegistry;\n}\n\n/**\n * Reset registry (for testing)\n */\nexport function resetModelRegistry(): void {\n globalRegistry.definitions.clear();\n globalRegistry.instances.clear();\n}\n\n/**\n * Reset instances only (keep definitions)\n */\nexport function resetModelInstances(): void {\n for (const instances of globalRegistry.instances.values()) {\n instances.clear();\n }\n}\n\n// ============================================================================\n// Lint Execution\n// ============================================================================\n\n/**\n * Execute lint for specific model\n */\nexport function lintModel<T extends { id: string }>(\n modelId: string,\n instance: T,\n context: LintContext\n): Array<{ rule: LintRule<T>; issue: LintIssue }> {\n const definition = globalRegistry.definitions.get(modelId);\n if (!definition || !definition.lintRules) return [];\n \n const issues: Array<{ rule: LintRule<T>; issue: LintIssue }> = [];\n \n for (const rule of definition.lintRules as LintRule<T>[]) {\n const issue = rule.check(instance, context);\n if (issue) {\n issues.push({ rule, issue });\n }\n }\n \n return issues;\n}\n\n/**\n * Execute lint for all models\n */\nexport function lintAllModels(context: LintContext): Array<{\n modelId: string;\n instanceId: string;\n rule: LintRule<unknown>;\n issue: LintIssue;\n}> {\n const allIssues: Array<{\n modelId: string;\n instanceId: string;\n rule: LintRule<unknown>;\n issue: LintIssue;\n }> = [];\n \n for (const [modelId, instances] of globalRegistry.instances) {\n const definition = globalRegistry.definitions.get(modelId);\n if (!definition || !definition.lintRules) continue;\n \n for (const [instanceId, instance] of instances) {\n for (const rule of definition.lintRules) {\n const issue = rule.check(instance, context);\n if (issue) {\n allIssues.push({\n modelId,\n instanceId,\n rule,\n issue,\n });\n }\n }\n }\n }\n \n return allIssues;\n}\n\n// ============================================================================\n// Export Execution\n// ============================================================================\n\n/**\n * Execute Markdown export\n */\nexport function exportMarkdown(\n modelId: string,\n context: ExportContext\n): Array<{ path: string; content: string }> {\n const definition = globalRegistry.definitions.get(modelId);\n if (!definition || !definition.exporters?.markdown) return [];\n \n const exporter = definition.exporters.markdown as MarkdownExporter<unknown>;\n const instances = getAllModelInstances(modelId);\n const files: Array<{ path: string; content: string }> = [];\n \n // Generate individual files\n for (const instance of instances) {\n const content = exporter.single(instance, context);\n const filename = exporter.filename\n ? exporter.filename(instance)\n : (instance as { id: string }).id;\n \n files.push({\n path: `${context.outputDir}/${exporter.outputDir}/${filename}.md`,\n content,\n });\n }\n \n // Generate index file\n if (exporter.index && instances.length > 0) {\n const indexContent = exporter.index(instances, context);\n files.push({\n path: `${context.outputDir}/${exporter.outputDir}/index.md`,\n content: indexContent,\n });\n }\n \n return files;\n}\n\n/**\n * Execute Mermaid diagram export\n */\nexport function exportMermaid(\n modelId: string,\n context: ExportContext\n): Array<{ path: string; content: string }> {\n const definition = globalRegistry.definitions.get(modelId);\n if (!definition || !definition.exporters?.mermaid) return [];\n \n const exporters = Array.isArray(definition.exporters.mermaid)\n ? definition.exporters.mermaid\n : [definition.exporters.mermaid];\n \n const instances = getAllModelInstances(modelId);\n const files: Array<{ path: string; content: string }> = [];\n \n for (const exporter of exporters as MermaidExporter<unknown>[]) {\n const content = exporter.generate(instances, context);\n files.push({\n path: `${context.outputDir}/${exporter.outputPath}`,\n content,\n });\n }\n \n return files;\n}\n\n/**\n * Execute export for all models\n */\nexport function exportAllModels(context: ExportContext): Array<{ path: string; content: string }> {\n const files: Array<{ path: string; content: string }> = [];\n \n for (const modelId of globalRegistry.definitions.keys()) {\n files.push(...exportMarkdown(modelId, context));\n files.push(...exportMermaid(modelId, context));\n }\n \n return files;\n}\n\n// ============================================================================\n// External Check Execution\n// ============================================================================\n\n/**\n * Execute external SSOT check\n */\nexport function checkExternalSsot<T extends { id: string }>(\n modelId: string,\n externalSource: unknown,\n context: CheckContext\n): CheckResult {\n const definition = globalRegistry.definitions.get(modelId);\n if (!definition || !definition.externalChecker) {\n return { success: true, errors: [], warnings: [] };\n }\n \n const checker = definition.externalChecker as ExternalChecker<T>;\n const instances = getAllModelInstances<T>(modelId);\n \n const allErrors: CheckResult['errors'] = [];\n const allWarnings: CheckResult['warnings'] = [];\n \n for (const instance of instances) {\n const result = checker.check(instance, externalSource, context);\n allErrors.push(...result.errors);\n allWarnings.push(...result.warnings);\n }\n \n return {\n success: allErrors.length === 0,\n errors: allErrors,\n warnings: allWarnings,\n };\n}\n\n// ============================================================================\n// Reference Resolution\n// ============================================================================\n\n/**\n * Resolve reference\n */\nexport function resolveReference(\n modelId: string,\n instanceId: string,\n field: string\n): unknown | undefined {\n const definition = globalRegistry.definitions.get(modelId);\n if (!definition || !definition.references) return undefined;\n \n const refDef = definition.references.find(r => r.field === field);\n if (!refDef) return undefined;\n \n const instance = getModelInstance(modelId, instanceId) as Record<string, unknown> | undefined;\n if (!instance) return undefined;\n \n const refValue = instance[field];\n if (!refValue) return undefined;\n \n if (refDef.isArray && Array.isArray(refValue)) {\n return refValue.map(id => getModelInstance(refDef.targetModel, id as string));\n }\n \n return getModelInstance(refDef.targetModel, refValue as string);\n}\n\n/**\n * Check reference integrity\n */\nexport function checkReferenceIntegrity(): Array<{\n modelId: string;\n instanceId: string;\n field: string;\n targetModel: string;\n missingIds: string[];\n}> {\n const issues: Array<{\n modelId: string;\n instanceId: string;\n field: string;\n targetModel: string;\n missingIds: string[];\n }> = [];\n \n for (const [modelId, definition] of globalRegistry.definitions) {\n if (!definition.references) continue;\n \n const instances = globalRegistry.instances.get(modelId);\n if (!instances) continue;\n \n for (const [instanceId, instance] of instances) {\n const inst = instance as Record<string, unknown>;\n \n for (const refDef of definition.references) {\n const refValue = inst[refDef.field];\n if (!refValue) {\n if (refDef.required) {\n issues.push({\n modelId,\n instanceId,\n field: refDef.field,\n targetModel: refDef.targetModel,\n missingIds: ['(required but not provided)'],\n });\n }\n continue;\n }\n \n const targetInstances = globalRegistry.instances.get(refDef.targetModel);\n const missingIds: string[] = [];\n \n if (refDef.isArray && Array.isArray(refValue)) {\n for (const id of refValue) {\n if (!targetInstances?.has(id as string)) {\n missingIds.push(id as string);\n }\n }\n } else {\n if (!targetInstances?.has(refValue as string)) {\n missingIds.push(refValue as string);\n }\n }\n \n if (missingIds.length > 0) {\n issues.push({\n modelId,\n instanceId,\n field: refDef.field,\n targetModel: refDef.targetModel,\n missingIds,\n });\n }\n }\n }\n }\n \n return issues;\n}\n\n// ============================================================================\n// Statistics\n// ============================================================================\n\n/**\n * Get registry statistics\n */\nexport function getModelRegistryStats(): {\n definitionCount: number;\n instanceCounts: Record<string, number>;\n totalInstances: number;\n} {\n const instanceCounts: Record<string, number> = {};\n let totalInstances = 0;\n \n for (const [modelId, instances] of globalRegistry.instances) {\n instanceCounts[modelId] = instances.size;\n totalInstances += instances.size;\n }\n \n return {\n definitionCount: globalRegistry.definitions.size,\n instanceCounts,\n totalInstances,\n };\n}\n","/**\n * Configuration API for speckeeper\n * \n * Provides `defineConfig` and `defineModel` functions for users to\n * create speckeeper.config.ts files with custom model definitions.\n */\n\nimport { z } from 'zod';\nimport type {\n ModelDefinition,\n MarkdownExporter,\n MermaidExporter,\n JsonSchemaExporter,\n LintRule,\n ExternalChecker,\n ReferenceDefinition,\n} from '../types/meta-model.js';\nimport { registerModelDefinitions } from './model-registry.js';\n\n// ============================================================================\n// Config Types\n// ============================================================================\n\n/**\n * speckeeper configuration type\n */\nexport interface SpeckeeperConfigInput {\n /** Project name */\n projectName?: string;\n /** Project version */\n version?: string;\n /** Design files directory */\n designDir?: string;\n /** Docs output directory */\n docsDir?: string;\n /** Specs output directory */\n specsDir?: string;\n /** Custom model definitions (Model instances or ModelDefinition objects) */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n models?: any[];\n /** Spec data entries from design/index.ts via mergeSpecs() */\n specs?: import('../core/model.js').SpecEntry[];\n /** External SSOT configuration */\n externalSsot?: {\n openapi?: {\n enabled: boolean;\n paths: string[];\n };\n ddl?: {\n enabled: boolean;\n type: 'ddl' | 'prisma' | 'typeorm' | 'drizzle';\n path: string;\n };\n iac?: {\n enabled: boolean;\n type: 'cloudformation' | 'cdk' | 'terraform';\n path: string;\n };\n };\n /** Lint configuration */\n lint?: {\n /** Strict mode */\n strict?: boolean;\n /** Disable specific rules */\n disabledRules?: string[];\n };\n}\n\n/**\n * Resolved speckeeper configuration\n */\nexport interface ResolvedSpeckeeperConfig extends SpeckeeperConfigInput {\n designDir: string;\n docsDir: string;\n specsDir: string;\n}\n\n// ============================================================================\n// Config API\n// ============================================================================\n\n/**\n * Define speckeeper configuration\n * \n * @example\n * ```typescript\n * // speckeeper.config.ts\n * import { defineConfig, defineModel } from 'speckeeper';\n * \n * export default defineConfig({\n * projectName: 'My Project',\n * models: [\n * // Custom model definitions\n * ],\n * });\n * ```\n */\nexport function defineConfig(input: SpeckeeperConfigInput): ResolvedSpeckeeperConfig {\n const resolved: ResolvedSpeckeeperConfig = {\n ...input,\n designDir: input.designDir ?? 'design',\n docsDir: input.docsDir ?? 'docs',\n specsDir: input.specsDir ?? 'specs',\n };\n \n // Register custom models\n if (input.models && input.models.length > 0) {\n registerModelDefinitions(input.models);\n }\n \n return resolved;\n}\n\n// ============================================================================\n// Model Definition API\n// ============================================================================\n\n/**\n * Model definition input type\n */\nexport interface ModelDefinitionInput<T extends z.ZodTypeAny> {\n /** Unique identifier for the model (kebab-case recommended) */\n id: string;\n /** Model name (PascalCase recommended) */\n name: string;\n /** Model description */\n description: string;\n /** Zod schema */\n schema: T;\n /** Prefix for ID generation */\n idPrefix: string;\n /** Exporter configuration */\n exporters?: {\n markdown?: MarkdownExporter<z.infer<T>>;\n mermaid?: MermaidExporter<z.infer<T>> | MermaidExporter<z.infer<T>>[];\n jsonSchema?: JsonSchemaExporter;\n };\n /** Lint rules */\n lintRules?: LintRule<z.infer<T>>[];\n /** External SSOT checker */\n externalChecker?: ExternalChecker<z.infer<T>>;\n /** Reference definitions */\n references?: ReferenceDefinition[];\n /** DSL function name */\n dslName?: string;\n /** Phase */\n phase?: 'REQ' | 'HLD' | 'LLD' | 'OPS';\n}\n\n/**\n * Create a custom model definition\n * \n * @example\n * ```typescript\n * const RetryPolicyModel = defineModel({\n * id: 'retry-policy',\n * name: 'RetryPolicy',\n * description: 'Retry policy definition',\n * schema: z.object({\n * id: z.string(),\n * name: z.string(),\n * maxAttempts: z.number().min(1),\n * initialDelay: z.number().min(0),\n * backoffMultiplier: z.number().min(1),\n * }),\n * idPrefix: 'RETRY',\n * exporters: {\n * markdown: {\n * single: (m) => `# ${m.name}\\n\\n- Max Attempts: ${m.maxAttempts}`,\n * outputDir: 'docs/retry-policies',\n * },\n * },\n * lintRules: [\n * {\n * id: 'retry-max-limit',\n * description: 'maxAttempts should not exceed 10',\n * severity: 'warning',\n * check: (m) => m.maxAttempts > 10 \n * ? { message: `maxAttempts ${m.maxAttempts} exceeds recommended limit` } \n * : null,\n * },\n * ],\n * });\n * ```\n */\nexport function defineModel<T extends z.ZodTypeAny>(\n input: ModelDefinitionInput<T>\n): ModelDefinition<T> {\n const definition: ModelDefinition<T> = {\n id: input.id,\n name: input.name,\n description: input.description,\n schema: input.schema,\n idPrefix: input.idPrefix,\n exporters: input.exporters,\n lintRules: input.lintRules,\n externalChecker: input.externalChecker,\n references: input.references,\n dslName: input.dslName,\n phase: input.phase,\n };\n \n return definition;\n}\n\n// ============================================================================\n// Helper Functions for Creating Exporters\n// ============================================================================\n\n/**\n * Helper to create Markdown exporter\n */\nexport function createMarkdownExporter<T>(\n config: {\n outputDir: string;\n single: (model: T, context: unknown) => string;\n index?: (models: T[], context: unknown) => string;\n filename?: (model: T) => string;\n }\n): MarkdownExporter<T> {\n return {\n single: config.single,\n index: config.index,\n outputDir: config.outputDir,\n filename: config.filename,\n };\n}\n\n/**\n * Helper to create Mermaid diagram exporter\n */\nexport function createMermaidExporter<T>(\n config: {\n diagramType: MermaidExporter<T>['diagramType'];\n outputPath: string;\n generate: (models: T[], context: unknown) => string;\n title?: string;\n }\n): MermaidExporter<T> {\n return {\n diagramType: config.diagramType,\n outputPath: config.outputPath,\n generate: config.generate,\n title: config.title,\n };\n}\n\n/**\n * Helper to create lint rule\n */\nexport function createLintRule<T>(\n config: {\n id: string;\n description: string;\n severity: 'error' | 'warning' | 'info';\n check: (model: T, context: unknown) => { message: string; field?: string; suggestion?: string } | null;\n }\n): LintRule<T> {\n return {\n id: config.id,\n description: config.description,\n severity: config.severity,\n check: config.check,\n };\n}\n\n// ============================================================================\n// Config Loading\n// ============================================================================\n\n/**\n * Load speckeeper.config.ts file and register custom models\n */\nexport async function loadSpeckeeperConfig(configPath?: string): Promise<ResolvedSpeckeeperConfig | null> {\n const possiblePaths = configPath \n ? [configPath]\n : [\n 'speckeeper.config.ts',\n 'speckeeper.config.js',\n 'speckeeper.config.mjs',\n ];\n \n for (const path of possiblePaths) {\n try {\n const fullPath = path.startsWith('/') ? path : `${process.cwd()}/${path}`;\n const module = await import(fullPath);\n const config = module.default || module;\n \n if (config && typeof config === 'object') {\n // Register custom models\n if (config.models && Array.isArray(config.models)) {\n registerModelDefinitions(config.models);\n }\n \n return {\n ...config,\n designDir: config.designDir ?? 'design',\n docsDir: config.docsDir ?? 'docs',\n specsDir: config.specsDir ?? 'specs',\n };\n }\n } catch {\n // Config file not found or invalid, continue to next\n }\n }\n \n return null;\n}\n","import { readFileSync, existsSync } from 'node:fs';\nimport { resolve, dirname, join } from 'node:path';\nimport { parse as parseYaml } from 'yaml';\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\n/**\n * Specification-compliant output path definitions\n * \n * Human-readable artifacts (docs/):\n * requirements/ - Requirements Markdown\n * usecases/ - Use cases\n * architecture/ - Architecture (C4 diagrams)\n * data-model/ - Conceptual model (ER diagrams)\n * screens/ - Screen specifications\n * flows/ - Process flows\n * glossary/ - Glossary\n * \n * Machine-readable artifacts (specs/):\n * schemas/entities/ - Entity JSON Schema\n * index.json - Aggregated data\n */\nexport interface OutputPaths {\n // docs/ subdirectories\n requirements: string;\n usecases: string;\n architecture: string;\n dataModel: string;\n screens: string;\n flows: string;\n glossary: string;\n component: string;\n \n // specs/ subdirectories\n schemasEntities: string;\n}\n\nexport interface SpeckeeperConfig {\n // Project info\n projectName?: string;\n version?: string;\n \n // Source paths\n srcDir: string;\n requirementsDir?: string;\n designDir?: string;\n usecasesDir?: string;\n \n // Output paths\n docsDir: string;\n specsDir: string;\n \n // External SSOT paths\n externalSsot?: {\n openapi?: {\n enabled: boolean;\n paths: string[];\n microContracts?: {\n enabled: boolean;\n requiredExtensions?: string[];\n strictMode?: boolean;\n };\n };\n ddl?: {\n enabled: boolean;\n paths: string[];\n type: 'ddl' | 'prisma' | 'typeorm' | 'drizzle';\n };\n iac?: {\n enabled: boolean;\n paths: string[];\n type: 'cloudformation' | 'terraform' | 'cdk';\n };\n };\n \n // Lint configuration\n lint?: {\n architecture?: {\n allowCrossBoundaryDependencies?: boolean;\n allowCrossLayerViolations?: boolean;\n maxComponentsPerDiagram?: number;\n };\n conceptModel?: {\n requireEntityDescription?: boolean;\n requireAggregateRoot?: boolean;\n warnOnOrphanEntities?: boolean;\n namingConvention?: 'PascalCase' | 'camelCase' | 'snake_case' | 'none';\n };\n screen?: {\n warnOnOrphanScreens?: boolean;\n warnOnDeadEnds?: boolean;\n checkAuthPaths?: boolean;\n };\n phaseGate?: {\n currentPhase?: 'REQ' | 'HLD' | 'LLD' | 'OPS';\n strictMode?: boolean;\n };\n };\n \n // Build configuration\n build?: {\n generateMermaidImages?: boolean;\n mermaidCliPath?: string;\n };\n \n // Custom model definitions\n models?: unknown[];\n \n // Spec data entries (from design/index.ts via mergeSpecs())\n specs?: import('../core/model.js').SpecEntry[];\n}\n\n// Default configuration\nconst defaultConfig: SpeckeeperConfig = {\n srcDir: 'src',\n designDir: 'design', // Directory for requirements/design TS models\n docsDir: 'docs',\n specsDir: 'specs',\n};\n\n// ============================================================================\n// Output Paths (spec-compliant)\n// ============================================================================\n\n/**\n * Get output paths compliant with specification\n */\nexport function getOutputPaths(config: SpeckeeperConfig, cwd: string = process.cwd()): OutputPaths {\n const docsDir = resolve(cwd, config.docsDir);\n const specsDir = resolve(cwd, config.specsDir);\n \n return {\n // docs/ subdirectories (compliant with spec section 7.1)\n requirements: join(docsDir, 'requirements'),\n usecases: join(docsDir, 'usecases'),\n architecture: join(docsDir, 'architecture'),\n dataModel: join(docsDir, 'data-model'),\n screens: join(docsDir, 'screens'),\n flows: join(docsDir, 'flows'),\n glossary: join(docsDir, 'glossary'),\n component: join(docsDir, 'component'),\n \n // specs/ subdirectories (compliant with spec section 7.1)\n schemasEntities: join(specsDir, 'schemas', 'entities'),\n };\n}\n\n/**\n * List of expected output paths (for drift check)\n */\nexport function getExpectedOutputDirs(config: SpeckeeperConfig, cwd: string = process.cwd()): string[] {\n const paths = getOutputPaths(config, cwd);\n return [\n paths.requirements,\n paths.usecases,\n paths.architecture,\n paths.dataModel,\n paths.screens,\n paths.flows,\n paths.glossary,\n paths.component,\n paths.schemasEntities,\n ];\n}\n\n/**\n * Validate if output path complies with specification\n */\nexport function validateOutputPaths(actualPath: string, config: SpeckeeperConfig, cwd: string = process.cwd()): {\n valid: boolean;\n expectedPaths: string[];\n message?: string;\n} {\n const expectedDirs = getExpectedOutputDirs(config, cwd);\n const docsDir = resolve(cwd, config.docsDir);\n const specsDir = resolve(cwd, config.specsDir);\n \n // Check if actualPath is under docs/ or specs/\n const isUnderDocs = actualPath.startsWith(docsDir);\n const isUnderSpecs = actualPath.startsWith(specsDir);\n \n if (!isUnderDocs && !isUnderSpecs) {\n return {\n valid: false,\n expectedPaths: expectedDirs,\n message: `Output path \"${actualPath}\" is not under docs/ or specs/`,\n };\n }\n \n // Check if under any of the expected paths\n const isValidPath = expectedDirs.some(dir => actualPath.startsWith(dir));\n \n if (!isValidPath) {\n return {\n valid: false,\n expectedPaths: expectedDirs,\n message: `Output path \"${actualPath}\" does not match spec-compliant paths. Expected one of: ${expectedDirs.map(d => d.replace(cwd + '/', '')).join(', ')}`,\n };\n }\n \n return { valid: true, expectedPaths: expectedDirs };\n}\n\n// ============================================================================\n// Configuration Loading\n// ============================================================================\n\nconst CONFIG_FILES = [\n 'speckeeper.config.yaml',\n 'speckeeper.config.yml',\n 'speckeeper.config.json',\n 'speckeeper.config.ts',\n 'speckeeper.config.js',\n];\n\nexport function findConfigFile(startDir: string = process.cwd()): string | null {\n let currentDir = startDir;\n \n while (currentDir !== dirname(currentDir)) {\n for (const configFile of CONFIG_FILES) {\n const configPath = resolve(currentDir, configFile);\n if (existsSync(configPath)) {\n return configPath;\n }\n }\n currentDir = dirname(currentDir);\n }\n \n return null;\n}\n\nexport async function loadConfig(\n configPath?: string,\n cwd: string = process.cwd()\n): Promise<SpeckeeperConfig> {\n const resolvedPath = configPath ?? findConfigFile(cwd);\n \n if (!resolvedPath) {\n return { ...defaultConfig };\n }\n \n const ext = resolvedPath.split('.').pop()?.toLowerCase();\n \n try {\n if (ext === 'yaml' || ext === 'yml') {\n const content = readFileSync(resolvedPath, 'utf-8');\n const parsed = parseYaml(content) as Partial<SpeckeeperConfig>;\n return { ...defaultConfig, ...parsed };\n }\n \n if (ext === 'json') {\n const content = readFileSync(resolvedPath, 'utf-8');\n const parsed = JSON.parse(content) as Partial<SpeckeeperConfig>;\n return { ...defaultConfig, ...parsed };\n }\n \n if (ext === 'ts' || ext === 'js') {\n const module = await import(resolvedPath);\n const parsed = module.default ?? module;\n return { ...defaultConfig, ...parsed };\n }\n \n return { ...defaultConfig };\n } catch (error) {\n console.error(`Failed to load config from ${resolvedPath}:`, error);\n return { ...defaultConfig };\n }\n}\n\n// ============================================================================\n// Configuration Validation\n// ============================================================================\n\nexport function validateConfig(config: SpeckeeperConfig): string[] {\n const errors: string[] = [];\n \n if (!config.srcDir) {\n errors.push('srcDir is required');\n }\n \n if (!config.docsDir) {\n errors.push('docsDir is required');\n }\n \n if (!config.specsDir) {\n errors.push('specsDir is required');\n }\n \n return errors;\n}\n","import { writeFileSync, mkdirSync, existsSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { createHash } from 'node:crypto';\n\n// ============================================================================\n// File Writing\n// ============================================================================\n\nexport interface WriteResult {\n path: string;\n created: boolean;\n updated: boolean;\n unchanged: boolean;\n}\n\nexport function ensureDir(dirPath: string): void {\n if (!existsSync(dirPath)) {\n mkdirSync(dirPath, { recursive: true });\n }\n}\n\nexport function writeFile(filePath: string, content: string): WriteResult {\n const dir = dirname(filePath);\n ensureDir(dir);\n \n const existed = existsSync(filePath);\n let unchanged = false;\n \n if (existed) {\n const existingContent = readFileSync(filePath, 'utf-8');\n unchanged = existingContent === content;\n }\n \n if (!unchanged) {\n writeFileSync(filePath, content, 'utf-8');\n }\n \n return {\n path: filePath,\n created: !existed,\n updated: existed && !unchanged,\n unchanged,\n };\n}\n\nexport function writeJsonFile(filePath: string, data: unknown, indent: number = 2): WriteResult {\n const content = JSON.stringify(data, null, indent) + '\\n';\n return writeFile(filePath, content);\n}\n\n// ============================================================================\n// Batch Writing\n// ============================================================================\n\nexport interface BatchWriteResult {\n results: WriteResult[];\n created: number;\n updated: number;\n unchanged: number;\n total: number;\n}\n\nexport function batchWriteFiles(\n files: Array<{ path: string; content: string }>\n): BatchWriteResult {\n const results: WriteResult[] = [];\n \n for (const { path, content } of files) {\n results.push(writeFile(path, content));\n }\n \n return {\n results,\n created: results.filter(r => r.created).length,\n updated: results.filter(r => r.updated).length,\n unchanged: results.filter(r => r.unchanged).length,\n total: results.length,\n };\n}\n\n// ============================================================================\n// Drift Detection\n// ============================================================================\n\nexport interface DriftResult {\n file: string;\n hasDrift: boolean;\n expectedHash?: string;\n actualHash?: string;\n missing?: boolean;\n}\n\nexport function computeHash(content: string): string {\n return createHash('sha256').update(content).digest('hex').slice(0, 16);\n}\n\nexport function checkFileDrift(\n filePath: string,\n expectedContent: string\n): DriftResult {\n const expectedHash = computeHash(expectedContent);\n \n if (!existsSync(filePath)) {\n return {\n file: filePath,\n hasDrift: true,\n expectedHash,\n missing: true,\n };\n }\n \n const actualContent = readFileSync(filePath, 'utf-8');\n const actualHash = computeHash(actualContent);\n \n return {\n file: filePath,\n hasDrift: expectedHash !== actualHash,\n expectedHash,\n actualHash,\n };\n}\n\nexport function checkBatchDrift(\n files: Array<{ path: string; content: string }>\n): DriftResult[] {\n return files.map(({ path, content }) => checkFileDrift(path, content));\n}\n\n// ============================================================================\n// File Discovery\n// ============================================================================\n\nimport { glob } from 'glob';\n\nexport async function findFiles(\n pattern: string,\n cwd: string = process.cwd()\n): Promise<string[]> {\n return glob(pattern, { cwd, absolute: true });\n}\n\nexport async function findTypeScriptFiles(\n srcDir: string\n): Promise<string[]> {\n return findFiles('**/*.ts', srcDir);\n}\n\nexport async function findDefinitionFiles(\n srcDir: string,\n subDir: string\n): Promise<string[]> {\n const pattern = join(srcDir, subDir, '**/*.ts');\n return glob(pattern, { absolute: true, ignore: ['**/*.d.ts', '**/index.ts'] });\n}\n\n// ============================================================================\n// Output Helpers\n// ============================================================================\n\nexport function generateDocsPath(\n baseDir: string,\n category: string,\n filename: string\n): string {\n return join(baseDir, category, filename);\n}\n\nexport function generateSpecsPath(\n baseDir: string,\n category: string,\n filename: string\n): string {\n return join(baseDir, category, filename);\n}\n"]}
@@ -1,8 +1,7 @@
1
1
  /**
2
- * Design specifications index
2
+ * Design entry point
3
3
  */
4
+ import { mergeSpecs } from 'speckeeper';
5
+ import requirements from './requirements.ts';
4
6
 
5
- // Requirements
6
- export { requirements } from './requirements.ts';
7
-
8
- console.log('Design specifications loaded!');
7
+ export default mergeSpecs(requirements);