speckeeper 0.1.0 → 0.2.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/README.md +36 -21
- package/dist/cli.js +1806 -299
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +36 -31
- package/dist/index.js +46 -164
- package/dist/index.js.map +1 -1
- package/dist/templates/init/design/requirements.ts +6 -3
- package/package.json +1 -1
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","../src/utils/model-loader.ts"],"names":["z","parseYaml","existsSync","dirname","readFileSync","join","globalRegistry","resolve"],"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,C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A,OAAO,MAAA;AACT;AAKO,SAAS,aAAA,CACd,UACA,EAAA,EAC4B;AAC5B,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,GAAG,KAAK,MAAA,CAAO,OAAA,CAAQ,QAAQ,CAAA,EAAG;AAClD,IAAA,IAAK,GAAA,CAA6B,GAAA,CAAI,EAAE,CAAA,EAAG;AACzC,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT;AAKO,SAAS,YAAA,CACd,UACA,EAAA,EACsD;AACtD,EAAA,MAAM,IAAA,GAAO,aAAA,CAAc,QAAA,EAAU,EAAE,CAAA;AACvC,EAAA,IAAI,CAAC,MAAM,OAAO,IAAA;AAElB,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,KAAA,EAAO,QAAA,CAAS,IAAI,CAAA,CAAE,IAAI,EAAE;AAAA,GAC9B;AACF","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// ============================================================================\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","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","/**\n * Model Loader\n * \n * Load models defined in TypeScript and convert to usable format for build command\n */\n\nimport { existsSync, readdirSync, statSync } from 'node:fs';\nimport { join, resolve, extname, basename } from 'node:path';\nimport type { SpeckeeperConfig } from './config-loader.js';\nimport { registerModel as coreRegisterModel } from '../core/model.js';\n\n// ============================================================================\n// Registry Types\n// ============================================================================\n\n/**\n * Model registry - stores all loaded models\n */\nexport interface ModelRegistry {\n requirements: Map<string, unknown>;\n useCases: Map<string, unknown>;\n actors: Map<string, unknown>;\n components: Map<string, unknown>;\n entities: Map<string, unknown>;\n relations: Map<string, unknown>;\n rules: Map<string, unknown>;\n screens: Map<string, unknown>;\n transitions: Map<string, unknown>;\n forms: Map<string, unknown>;\n processFlows: Map<string, unknown>;\n glossaryTerms: Map<string, unknown>;\n apiRefs: Map<string, unknown>;\n tableRefs: Map<string, unknown>;\n testRefs: Map<string, unknown>;\n layers: Map<string, unknown>;\n boundaries: Map<string, unknown>;\n artifacts: Map<string, unknown>;\n}\n\nexport function createEmptyRegistry(): ModelRegistry {\n return {\n requirements: new Map(),\n useCases: new Map(),\n actors: new Map(),\n components: new Map(),\n entities: new Map(),\n relations: new Map(),\n rules: new Map(),\n screens: new Map(),\n transitions: new Map(),\n forms: new Map(),\n processFlows: new Map(),\n glossaryTerms: new Map(),\n apiRefs: new Map(),\n tableRefs: new Map(),\n testRefs: new Map(),\n layers: new Map(),\n boundaries: new Map(),\n artifacts: new Map(),\n };\n}\n\n// ============================================================================\n// Global Registry (shared registry for DSL functions to register to)\n// ============================================================================\n\nlet globalRegistry: ModelRegistry = createEmptyRegistry();\n\nexport function getGlobalRegistry(): ModelRegistry {\n return globalRegistry;\n}\n\nexport function resetGlobalRegistry(): void {\n globalRegistry = createEmptyRegistry();\n}\n\n/**\n * Function for DSL functions to register models\n */\nexport function registerModel(\n type: keyof ModelRegistry,\n id: string,\n model: unknown\n): void {\n globalRegistry[type].set(id, model);\n}\n\n// ============================================================================\n// Model Registration from Exports\n// ============================================================================\n\n/**\n * Determine if value is a Model class instance\n */\nfunction isModelInstance(value: unknown): value is { id: string; name: string; idPrefix: string; schema: unknown } {\n if (!value || typeof value !== 'object') return false;\n const obj = value as Record<string, unknown>;\n return (\n typeof obj.id === 'string' &&\n typeof obj.name === 'string' &&\n typeof obj.idPrefix === 'string' &&\n obj.schema !== undefined &&\n typeof obj.validate === 'function' &&\n typeof obj.lint === 'function'\n );\n}\n\n/**\n * Detect models from imported module exports and register to globalRegistry\n */\nfunction registerExportedModels(module: Record<string, unknown>): void {\n for (const [exportName, exportValue] of Object.entries(module)) {\n if (!exportValue || typeof exportValue !== 'object') continue;\n \n // Detect and register Model class instances\n if (isModelInstance(exportValue)) {\n // Register to core model registry\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n coreRegisterModel(exportValue as any);\n continue;\n }\n \n // Process arrays\n if (Array.isArray(exportValue)) {\n registerArrayItems(exportName, exportValue);\n continue;\n }\n \n const value = exportValue as Record<string, unknown>;\n \n // Detect ArchitectureModel (has components, layers, boundaries, relations)\n if (value.components && value.layers && value.boundaries && value.relations) {\n const arch = value as { \n name?: string;\n components: { id?: string }[]; \n layers: { id?: string }[]; \n boundaries: { id?: string }[];\n relations: { id?: string }[];\n };\n for (const comp of arch.components) {\n if (comp.id) globalRegistry.components.set(comp.id, comp);\n }\n for (const layer of arch.layers) {\n if (layer.id) globalRegistry.layers.set(layer.id, layer);\n }\n for (const boundary of arch.boundaries) {\n if (boundary.id) globalRegistry.boundaries.set(boundary.id, boundary);\n }\n for (const rel of arch.relations) {\n if (rel.id) globalRegistry.relations.set(rel.id, rel);\n }\n continue;\n }\n \n // Detect ConceptModel (has entities, relations, rules)\n if (value.entities && value.relations && Array.isArray(value.entities)) {\n const concept = value as { \n entities: { id?: string }[]; \n relations: { id?: string }[];\n rules?: { id?: string }[];\n };\n for (const entity of concept.entities) {\n if (entity.id) globalRegistry.entities.set(entity.id, entity);\n }\n for (const rel of concept.relations) {\n if (rel.id) globalRegistry.relations.set(rel.id, rel);\n }\n for (const rule of concept.rules || []) {\n if (rule.id) globalRegistry.rules.set(rule.id, rule);\n }\n continue;\n }\n \n // Detect UseCaseModel (has useCases, actors)\n if (value.useCases && value.actors) {\n const ucModel = value as { \n useCases: { id?: string }[]; \n actors: { id?: string }[];\n };\n for (const uc of ucModel.useCases) {\n if (uc.id) globalRegistry.useCases.set(uc.id, uc);\n }\n for (const actor of ucModel.actors) {\n if (actor.id) globalRegistry.actors.set(actor.id, actor);\n }\n continue;\n }\n \n // Detect Glossary (array with terms or {terms: []} format)\n if (value.terms && Array.isArray(value.terms)) {\n const glossary = value as { terms: { id?: string }[] };\n for (const term of glossary.terms) {\n if (term.id) globalRegistry.glossaryTerms.set(term.id, term);\n }\n continue;\n }\n \n // Detect single Requirement\n if (value.id && value.title && (value.kind || value.type || value.acceptance)) {\n globalRegistry.requirements.set(value.id as string, value);\n continue;\n }\n \n // Detect single Entity\n if (value.id && value.name && value.attributes && Array.isArray(value.attributes)) {\n globalRegistry.entities.set(value.id as string, value);\n continue;\n }\n \n // Detect single UseCase\n if (value.id && value.name && value.actor && value.mainFlow) {\n globalRegistry.useCases.set(value.id as string, value);\n continue;\n }\n \n // Detect single Actor\n if (value.id && value.name && value.type && ['human', 'system', 'external'].includes(value.type as string)) {\n globalRegistry.actors.set(value.id as string, value);\n continue;\n }\n \n // Detect single Term\n if (value.id && (value.term || value.abbreviation) && value.definition) {\n globalRegistry.glossaryTerms.set(value.id as string, value);\n continue;\n }\n }\n}\n\n/**\n * Detect items from array and register to registry\n */\nfunction registerArrayItems(exportName: string, items: unknown[]): void {\n for (const item of items) {\n if (!item || typeof item !== 'object') continue;\n const obj = item as Record<string, unknown>;\n if (!obj.id || typeof obj.id !== 'string') continue;\n \n // Infer type from export name or object structure\n // requirements / allRequirements / functionalRequirements etc.\n if (exportName.toLowerCase().includes('requirement') || \n exportName.toLowerCase().includes('constraints') ||\n (obj.type && obj.acceptanceCriteria)) {\n globalRegistry.requirements.set(obj.id, item);\n continue;\n }\n \n // useCases / usecases\n if (exportName.toLowerCase().includes('usecase') || \n (obj.actor && obj.mainFlow)) {\n globalRegistry.useCases.set(obj.id, item);\n continue;\n }\n \n // actors\n if (exportName.toLowerCase().includes('actor') ||\n (obj.type && ['human', 'system', 'external'].includes(obj.type as string) && !obj.mainFlow)) {\n globalRegistry.actors.set(obj.id, item);\n continue;\n }\n \n // components / containers\n if (exportName.toLowerCase().includes('component') ||\n exportName.toLowerCase().includes('container') ||\n (obj.type && ['person', 'system', 'container', 'component'].includes(obj.type as string))) {\n globalRegistry.components.set(obj.id, item);\n continue;\n }\n \n // entities\n if (exportName.toLowerCase().includes('entit') ||\n (obj.name && obj.attributes && Array.isArray(obj.attributes))) {\n globalRegistry.entities.set(obj.id, item);\n continue;\n }\n \n // terms / acronyms / glossary\n if (exportName.toLowerCase().includes('term') ||\n exportName.toLowerCase().includes('acronym') ||\n exportName.toLowerCase().includes('glossary') ||\n (obj.term && obj.definition)) {\n globalRegistry.glossaryTerms.set(obj.id, item);\n continue;\n }\n \n // relations\n if (exportName.toLowerCase().includes('relation') ||\n (obj.from && obj.to && obj.label)) {\n globalRegistry.relations.set(obj.id, item);\n continue;\n }\n \n // layers\n if (exportName.toLowerCase().includes('layer') ||\n (obj.name && typeof obj.order === 'number')) {\n globalRegistry.layers.set(obj.id, item);\n continue;\n }\n \n // boundaries\n if (exportName.toLowerCase().includes('boundar') ||\n (obj.type && ['system', 'context', 'container', 'deployment'].includes(obj.type as string) && obj.description)) {\n globalRegistry.boundaries.set(obj.id, item);\n continue;\n }\n \n // screens\n if (exportName.toLowerCase().includes('screen') ||\n (obj.type && ['page', 'modal', 'drawer', 'panel', 'wizard'].includes(obj.type as string) && obj.auth)) {\n globalRegistry.screens.set(obj.id, item);\n continue;\n }\n \n // testRefs\n if (exportName.toLowerCase().includes('testref') ||\n exportName.toLowerCase().includes('test-ref') ||\n (obj.source && obj.verifiesRequirements && Array.isArray(obj.verifiesRequirements))) {\n globalRegistry.testRefs.set(obj.id, item);\n continue;\n }\n \n // artifacts\n if (exportName.toLowerCase().includes('artifact') ||\n (obj.category && obj.location && obj.purpose &&\n ['ssot', 'human-readable', 'machine-readable', 'implementation'].includes(obj.category as string))) {\n globalRegistry.artifacts.set(obj.id, item);\n continue;\n }\n }\n}\n\n// ============================================================================\n// Model Loading\n// ============================================================================\n\n/**\n * Dynamically import TS files from specified directory and collect models\n */\nexport async function loadModelsFromDirectory(\n dirPath: string,\n options: { recursive?: boolean } = {}\n): Promise<string[]> {\n const loadedFiles: string[] = [];\n \n if (!existsSync(dirPath)) {\n return loadedFiles;\n }\n \n const entries = readdirSync(dirPath);\n \n for (const entry of entries) {\n const fullPath = join(dirPath, entry);\n const stat = statSync(fullPath);\n \n if (stat.isDirectory() && options.recursive) {\n const subFiles = await loadModelsFromDirectory(fullPath, options);\n loadedFiles.push(...subFiles);\n } else if (stat.isFile()) {\n const ext = extname(entry);\n // Target .ts, .js, .mts, .mjs files\n if (['.ts', '.js', '.mts', '.mjs'].includes(ext) && !entry.endsWith('.d.ts')) {\n // Exclude index.ts (possibly a re-export file)\n if (basename(entry, ext) === 'index') {\n continue;\n }\n \n try {\n // Dynamic import\n const module = await import(fullPath);\n loadedFiles.push(fullPath);\n \n // Register exported models to globalRegistry\n registerExportedModels(module);\n } catch (error) {\n console.error(`Failed to load model from ${fullPath}:`, error);\n }\n }\n }\n }\n \n return loadedFiles;\n}\n\n/**\n * Load all models based on configuration\n */\nexport async function loadAllModels(\n config: SpeckeeperConfig,\n cwd: string = process.cwd()\n): Promise<{\n registry: ModelRegistry;\n loadedFiles: string[];\n errors: Array<{ file: string; error: unknown }>;\n}> {\n // Reset registry\n resetGlobalRegistry();\n \n const loadedFiles: string[] = [];\n const errors: Array<{ file: string; error: unknown }> = [];\n \n // Load from design/ directory (compliant with spec section 7.1)\n const designDir = resolve(cwd, config.designDir || 'design');\n \n // Standard directory structure (compliant with spec section 7.1)\n const modelDirs = [\n { path: join(designDir, 'requirements') },\n { path: join(designDir, 'usecases') },\n { path: join(designDir, 'architecture') },\n { path: join(designDir, 'data-model') },\n { path: join(designDir, 'screens') },\n { path: join(designDir, 'flows') },\n { path: join(designDir, 'glossary') },\n // Also load files directly under design/ by default (index.ts, etc.)\n { path: designDir },\n ];\n \n for (const { path: dirPath } of modelDirs) {\n if (!existsSync(dirPath)) {\n continue;\n }\n \n try {\n const files = await loadModelsFromDirectory(dirPath, { recursive: true });\n loadedFiles.push(...files);\n } catch (error) {\n errors.push({ file: dirPath, error });\n }\n }\n \n return {\n registry: getGlobalRegistry(),\n loadedFiles,\n errors,\n };\n}\n\n// ============================================================================\n// Registry Helpers\n// ============================================================================\n\n/**\n * Get registry statistics\n */\nexport function getRegistryStats(registry: ModelRegistry): Record<string, number> {\n const stats: Record<string, number> = {};\n \n for (const [key, map] of Object.entries(registry)) {\n stats[key] = (map as Map<string, unknown>).size;\n }\n \n return stats;\n}\n\n/**\n * Get all IDs in registry\n */\nexport function getAllIds(registry: ModelRegistry): Set<string> {\n const allIds = new Set<string>();\n \n for (const map of Object.values(registry)) {\n for (const id of (map as Map<string, unknown>).keys()) {\n allIds.add(id);\n }\n }\n \n return allIds;\n}\n\n/**\n * Identify model type from ID\n */\nexport function findModelType(\n registry: ModelRegistry,\n id: string\n): keyof ModelRegistry | null {\n for (const [type, map] of Object.entries(registry)) {\n if ((map as Map<string, unknown>).has(id)) {\n return type as keyof ModelRegistry;\n }\n }\n return null;\n}\n\n/**\n * Get model by ID\n */\nexport function getModelById(\n registry: ModelRegistry,\n id: string\n): { type: keyof ModelRegistry; model: unknown } | null {\n const type = findModelType(registry, id);\n if (!type) return null;\n \n return {\n type,\n model: registry[type].get(id),\n };\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","../src/utils/model-loader.ts"],"names":["z","parseYaml","existsSync","dirname","readFileSync","join","resolve"],"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,KAA6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,CAAA,EAAG;AACjD,IAAA,KAAA,CAAM,GAAG,IAAI,GAAA,CAAI,IAAA;AAAA,EACnB;AAEA,EAAA,OAAO,KAAA;AACT;AAKO,SAAS,UAAU,QAAA,EAAsC;AAC9D,EAAA,MAAM,MAAA,uBAAa,GAAA,EAAY;AAE/B,EAAA,KAAA,MAAW,GAAA,IAAO,MAAA,CAAO,MAAA,CAAO,QAAQ,CAAA,EAAG;AACzC,IAAA,KAAA,MAAW,EAAA,IAAM,GAAA,CAAI,IAAA,EAAK,EAAG;AAC3B,MAAA,MAAA,CAAO,IAAI,EAAE,CAAA;AAAA,IACf;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT;AAKO,SAAS,aAAA,CACd,UACA,EAAA,EACe;AACf,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,GAAG,KAAK,MAAA,CAAO,OAAA,CAAQ,QAAQ,CAAA,EAAG;AAClD,IAAA,IAAI,GAAA,CAAI,GAAA,CAAI,EAAE,CAAA,EAAG;AACf,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT;AAKO,SAAS,YAAA,CACd,UACA,EAAA,EACyC;AACzC,EAAA,MAAM,IAAA,GAAO,aAAA,CAAc,QAAA,EAAU,EAAE,CAAA;AACvC,EAAA,IAAI,CAAC,MAAM,OAAO,IAAA;AAElB,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,KAAA,EAAO,QAAA,CAAS,IAAI,CAAA,CAAE,IAAI,EAAE;AAAA,GAC9B;AACF","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","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","/**\n * Model Loader\n * \n * Load models and specs from design/ directory.\n * Spec registration is done explicitly via Model.register() in each spec file.\n */\n\nimport { existsSync, readdirSync, statSync } from 'node:fs';\nimport { join, resolve, extname, basename } from 'node:path';\nimport type { SpeckeeperConfig } from './config-loader.js';\nimport {\n registerModel as coreRegisterModel,\n clearModelRegistry,\n getSpecStore,\n resetSpecStore,\n} from '../core/model.js';\n\n// ============================================================================\n// Registry Types\n// ============================================================================\n\n/**\n * Model registry - stores all loaded spec data.\n * Keys are model IDs (e.g. 'functional-requirement', 'usecase').\n * Values are Maps of spec ID -> spec data.\n */\nexport type ModelRegistry = Record<string, Map<string, unknown>>;\n\n// ============================================================================\n// Model Instance Detection\n// ============================================================================\n\n/**\n * Determine if value is a Model class instance\n */\nfunction isModelInstance(value: unknown): value is { id: string; name: string; idPrefix: string; schema: unknown } {\n if (!value || typeof value !== 'object') return false;\n const obj = value as Record<string, unknown>;\n return (\n typeof obj.id === 'string' &&\n typeof obj.name === 'string' &&\n typeof obj.idPrefix === 'string' &&\n obj.schema !== undefined &&\n typeof obj.validate === 'function' &&\n typeof obj.lint === 'function'\n );\n}\n\n/**\n * Detect and register Model class instances from module exports.\n * Only registers Model instances to the core model registry.\n * Spec data registration is handled by Model.register() calls in spec files.\n */\nfunction registerExportedModelInstances(module: Record<string, unknown>): void {\n for (const [, exportValue] of Object.entries(module)) {\n if (!exportValue || typeof exportValue !== 'object') continue;\n if (isModelInstance(exportValue)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n coreRegisterModel(exportValue as any);\n }\n }\n}\n\n// ============================================================================\n// File Loading\n// ============================================================================\n\n/**\n * Dynamically import TS files from specified directory.\n * Model class instances found in exports are registered to core registry.\n * Spec data is registered via Model.register() side effects during import.\n */\nexport async function loadModelsFromDirectory(\n dirPath: string,\n options: { recursive?: boolean } = {}\n): Promise<string[]> {\n const loadedFiles: string[] = [];\n\n if (!existsSync(dirPath)) {\n return loadedFiles;\n }\n\n const entries = readdirSync(dirPath);\n\n for (const entry of entries) {\n const fullPath = join(dirPath, entry);\n const stat = statSync(fullPath);\n\n if (stat.isDirectory() && options.recursive) {\n const subFiles = await loadModelsFromDirectory(fullPath, options);\n loadedFiles.push(...subFiles);\n } else if (stat.isFile()) {\n const ext = extname(entry);\n if (['.ts', '.js', '.mts', '.mjs'].includes(ext) && !entry.endsWith('.d.ts')) {\n if (basename(entry, ext) === 'index') {\n continue;\n }\n\n try {\n const module = await import(fullPath);\n loadedFiles.push(fullPath);\n registerExportedModelInstances(module);\n } catch (error) {\n console.error(`Failed to load from ${fullPath}:`, error);\n }\n }\n }\n }\n\n return loadedFiles;\n}\n\n/**\n * Load all models and specs based on configuration.\n * \n * 1. Reset spec store and model registry\n * 2. Register Model class instances from config.models\n * 3. Scan design/ files (triggers Model.register() calls as side effects)\n * 4. Build registry from specStore\n */\nexport async function loadAllModels(\n config: SpeckeeperConfig,\n cwd: string = process.cwd()\n): Promise<{\n registry: ModelRegistry;\n loadedFiles: string[];\n errors: Array<{ file: string; error: unknown }>;\n}> {\n resetSpecStore();\n clearModelRegistry();\n\n const loadedFiles: string[] = [];\n const errors: Array<{ file: string; error: unknown }> = [];\n\n // Register Model class instances from config.models first\n if (config.models && Array.isArray(config.models)) {\n for (const model of config.models) {\n if (isModelInstance(model)) {\n coreRegisterModel(model as Parameters<typeof coreRegisterModel>[0]);\n }\n }\n }\n\n const designDir = resolve(cwd, config.designDir || 'design');\n\n const modelDirs = [\n { path: join(designDir, '_models') },\n { path: join(designDir, 'requirements') },\n { path: join(designDir, 'usecases') },\n { path: join(designDir, 'architecture') },\n { path: join(designDir, 'data-model') },\n { path: join(designDir, 'screens') },\n { path: join(designDir, 'flows') },\n { path: join(designDir, 'glossary') },\n { path: designDir },\n ];\n\n for (const { path: dirPath } of modelDirs) {\n if (!existsSync(dirPath)) {\n continue;\n }\n\n try {\n const files = await loadModelsFromDirectory(dirPath, { recursive: true });\n loadedFiles.push(...files);\n } catch (error) {\n errors.push({ file: dirPath, error });\n }\n }\n\n // Build registry from specStore (populated by Model.register() calls)\n const store = getSpecStore();\n const registry: ModelRegistry = {};\n for (const [modelId, specMap] of store) {\n registry[modelId] = specMap;\n }\n\n return {\n registry,\n loadedFiles,\n errors,\n };\n}\n\n// ============================================================================\n// Registry Helpers\n// ============================================================================\n\n/**\n * Get specs from registry for a given model ID\n */\nexport function getSpecsFromRegistry(registry: ModelRegistry, modelId: string): unknown[] {\n const map = registry[modelId];\n if (!map) return [];\n return Array.from(map.values());\n}\n\n/**\n * Get registry statistics\n */\nexport function getRegistryStats(registry: ModelRegistry): Record<string, number> {\n const stats: Record<string, number> = {};\n\n for (const [key, map] of Object.entries(registry)) {\n stats[key] = map.size;\n }\n\n return stats;\n}\n\n/**\n * Get all IDs in registry\n */\nexport function getAllIds(registry: ModelRegistry): Set<string> {\n const allIds = new Set<string>();\n\n for (const map of Object.values(registry)) {\n for (const id of map.keys()) {\n allIds.add(id);\n }\n }\n\n return allIds;\n}\n\n/**\n * Identify model type from ID\n */\nexport function findModelType(\n registry: ModelRegistry,\n id: string\n): string | null {\n for (const [type, map] of Object.entries(registry)) {\n if (map.has(id)) {\n return type;\n }\n }\n return null;\n}\n\n/**\n * Get model by ID\n */\nexport function getModelById(\n registry: ModelRegistry,\n id: string\n): { type: string; model: unknown } | null {\n const type = findModelType(registry, id);\n if (!type) return null;\n\n return {\n type,\n model: registry[type].get(id),\n };\n}\n"]}
|