Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:29:15 +08:00
commit be476a3fea
76 changed files with 12812 additions and 0 deletions

View File

@@ -0,0 +1,68 @@
# Ontological Documentation Skill
This skill provides comprehensive tools and templates for creating ontological documentation of software systems.
## Directory Structure
```
ontological-documentation/
├── SKILL.md # Main skill definition
├── README.md # This file
├── references/ # Reference guides
│ ├── concept_extraction_guide.md
│ ├── documentation_templates.md
│ └── ontology_patterns.md
├── scripts/ # Utility scripts
│ ├── extract_concepts.py
│ └── generate_ontology_diagram.py
└── assets/ # Examples and templates
├── examples/
│ └── ecommerce-ontology.md
└── ontology-templates/
└── domain-ontology.md
```
## What's Included
### Reference Guides
- **concept_extraction_guide.md**: Methodologies for extracting domain concepts from codebases
- **documentation_templates.md**: Standardized templates for documenting concepts and relationships
- **ontology_patterns.md**: Common patterns and best practices for ontological documentation
### Scripts
- **extract_concepts.py**: Automated concept extraction from Python and JavaScript/TypeScript code
- **generate_ontology_diagram.py**: Generate Mermaid, PlantUML, GraphViz, and JSON-LD diagrams
### Examples & Templates
- **ecommerce-ontology.md**: Complete example of e-commerce domain ontology
- **domain-ontology.md**: Template for documenting new domain ontologies
## Usage
This skill activates automatically when working on:
- Domain modeling and architecture documentation
- Creating conceptual frameworks
- Extracting and documenting business concepts from code
- Building knowledge graphs and semantic models
## Quick Start
1. Read [SKILL.md](SKILL.md) for the full skill definition
2. Review the [concept extraction guide](references/concept_extraction_guide.md)
3. Use the [templates](references/documentation_templates.md) for your documentation
4. Check the [e-commerce example](assets/examples/ecommerce-ontology.md) for inspiration
## Scripts Usage
### Extract Concepts
```bash
python scripts/extract_concepts.py /path/to/codebase
```
### Generate Diagrams
```bash
python scripts/generate_ontology_diagram.py ontology.json --format mermaid
```

View File

@@ -0,0 +1,399 @@
---
name: grey-haven-ontological-documentation
description: Create comprehensive ontological documentation for Grey Haven systems - extract domain concepts from TanStack Start and FastAPI codebases, model semantic relationships, generate visual representations of system architecture, and document business domains. Use when onboarding, documenting architecture, or analyzing legacy systems.
---
# Grey Haven Ontological Documentation
Create comprehensive ontological documentation that captures fundamental concepts, relationships, and classification systems within Grey Haven codebases and systems.
## When to Use This Skill
Use this skill when you need to:
- Document the conceptual structure and domain model of Grey Haven applications
- Extract and organize business concepts from TanStack Start or FastAPI codebases
- Create visual representations of multi-tenant system architectures
- Build semantic maps of entities, services, and their tenant-isolated interactions
- Design or document domain models for new Grey Haven features
- Analyze and communicate complex architectures to stakeholders
- Create knowledge graphs for Grey Haven development teams
- Onboard new developers to Grey Haven project structure
## Core Capabilities
### 1. Concept Extraction from Grey Haven Codebases
**TanStack Start (Frontend) Extraction:**
- Drizzle schema tables and relationships
- React components and their hierarchies
- TanStack Router route structure
- Better-auth session and user models
- Server functions and their dependencies
- Multi-tenant data patterns (tenant_id isolation)
**FastAPI (Backend) Extraction:**
- SQLModel entities and relationships
- Repository pattern implementations
- Service layer business logic
- API endpoint hierarchies
- Multi-tenant repository filters
- Pydantic schemas and validation models
### 2. Grey Haven Architecture Patterns
**Identify and Document:**
- **Multi-Tenant Patterns**: tenant_id isolation, RLS roles (admin/authenticated/anon)
- **Repository Pattern**: BaseRepository with automatic tenant filtering
- **Service Layer**: Business logic separation from endpoints
- **Database Conventions**: snake_case fields, UUID primary keys, timestamps
- **Authentication**: Better-auth integration with session management
- **Deployment**: Cloudflare Workers architecture
### 3. Visual Documentation Formats
**Mermaid Diagrams** (for README files):
```mermaid
erDiagram
USER ||--o{ ORGANIZATION : belongs_to
USER {
uuid id PK
string email_address UK
uuid tenant_id FK
timestamp created_at
}
ORGANIZATION ||--o{ TEAM : contains
ORGANIZATION {
uuid id PK
string name
uuid tenant_id FK
timestamp created_at
}
```
**System Architecture**:
```mermaid
graph TB
Client[TanStack Start Client]
Server[Server Functions]
Auth[Better-auth]
DB[(PostgreSQL + RLS)]
Client -->|Authenticated Requests| Server
Client -->|Auth Flow| Auth
Server -->|Query with tenant_id| DB
Auth -->|Session Validation| DB
```
### 4. Domain Model Documentation Template
```markdown
## Entity: User
### Definition
Represents an authenticated user in the Grey Haven system with multi-tenant isolation.
### Database Schema
- **Table**: users (snake_case)
- **Primary Key**: id (UUID)
- **Tenant Isolation**: tenant_id (UUID, indexed)
- **Unique Constraints**: email_address per tenant
- **Timestamps**: created_at, updated_at (automatic)
### Relationships
- **Belongs To**: Organization (via tenant_id)
- **Has Many**: Sessions (Better-auth)
- **Has Many**: TeamMemberships
### Business Rules
- Email must be unique within tenant
- Cannot access data from other tenants
- Session expires after 30 days of inactivity
- RLS enforces tenant_id filtering at database level
### TypeScript Type
```typescript
interface User {
id: string;
emailAddress: string;
tenantId: string;
createdAt: Date;
updatedAt: Date;
}
```
### Python Model
```python
class User(SQLModel, table=True):
__tablename__ = "users"
id: UUID = Field(default_factory=uuid4, primary_key=True)
email_address: str = Field(unique=True, index=True)
tenant_id: UUID = Field(foreign_key="organizations.id", index=True)
created_at: datetime = Field(default_factory=datetime.utcnow)
updated_at: datetime = Field(default_factory=datetime.utcnow)
```
```
## Workflow
### Step 1: Discovery and Extraction
**For TanStack Start Projects:**
1. Analyze Drizzle schema files in `src/lib/server/schema/`
2. Map React component structure in `src/lib/components/`
3. Document TanStack Router routes in `src/routes/`
4. Extract server functions from `src/lib/server/functions/`
5. Identify tenant isolation patterns
**For FastAPI Projects:**
1. Analyze SQLModel models in `app/db/models/`
2. Map repository pattern in `app/db/repositories/`
3. Document service layer in `app/services/`
4. Extract API routes from `app/routers/`
5. Identify BaseRepository tenant filtering
### Step 2: Ontology Construction
**Categorize by Grey Haven Patterns:**
1. **Core Entities** (tables with tenant_id)
- User, Organization, Team, etc.
- Always include tenant_id
- UUID primary keys
- snake_case field names
2. **Service Boundaries**
- Repository layer (data access)
- Service layer (business logic)
- Router layer (API endpoints)
- Clear separation of concerns
3. **Relationships and Dependencies**
- Foreign key relationships
- Repository dependencies
- Service composition
- API endpoint groupings
4. **Multi-Tenant Patterns**
- RLS role usage (admin/authenticated/anon)
- tenant_id filtering in repositories
- Session-based tenant resolution
- Cross-tenant access prevention
### Step 3: Documentation Creation
**Use Grey Haven Documentation Standards:**
1. **Entity Documentation**
- Definition and purpose
- Database schema with exact field names
- Relationships to other entities
- Business rules and constraints
- TypeScript and Python representations
2. **Service Documentation**
- Service responsibilities
- Repository dependencies
- Business logic patterns
- Multi-tenant considerations
3. **API Documentation**
- Endpoint hierarchies
- Request/response schemas
- Authentication requirements
- Tenant isolation verification
### Step 4: Visualization
**Create Diagrams For:**
1. **Database ERD** - All tables with relationships and tenant_id fields
2. **Service Dependencies** - Repository → Service → Router layers
3. **Authentication Flow** - Better-auth integration with multi-tenant context
4. **Deployment Architecture** - Cloudflare Workers, Neon PostgreSQL, Redis
5. **Data Flow** - Client → Server Functions → Repository → Database (with RLS)
## Common Use Cases
### Use Case 1: New Developer Onboarding
*"I need to understand how Grey Haven's multi-tenant architecture works."*
**Approach:**
1. Extract all entities with tenant_id fields
2. Document BaseRepository tenant filtering pattern
3. Create ERD showing tenant_id relationships
4. Explain RLS roles and session-based tenant resolution
5. Show data flow with tenant isolation
### Use Case 2: Feature Design Documentation
*"Document the domain model for the new billing feature before implementation."*
**Approach:**
1. Design entity schema following Grey Haven conventions
2. Plan repository and service layer structure
3. Document API endpoints with tenant isolation
4. Create Mermaid diagrams for the feature
5. Validate multi-tenant patterns
### Use Case 3: Architecture Review
*"Analyze the current codebase to identify inconsistencies in multi-tenant patterns."*
**Approach:**
1. Extract all repositories and check tenant_id filtering
2. Review entities for proper tenant_id indexing
3. Audit RLS role usage across the application
4. Identify missing tenant isolation
5. Generate compliance report
### Use Case 4: Legacy Code Analysis
*"Understand the original domain model before refactoring the user management system."*
**Approach:**
1. Extract current User entity and relationships
2. Map all services depending on User
3. Document authentication flow with Better-auth
4. Identify refactoring boundaries
5. Create before/after architecture diagrams
## Grey Haven Specific Patterns
### Multi-Tenant Entity Pattern
```typescript
// Drizzle Schema (TanStack Start)
export const usersTable = pgTable("users", {
id: uuid("id").primaryKey().defaultRandom(),
emailAddress: text("email_address").unique().notNull(),
tenantId: uuid("tenant_id").references(() => organizationsTable.id).notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at").defaultNow().notNull(),
});
```
```python
# SQLModel (FastAPI)
class User(SQLModel, table=True):
__tablename__ = "users"
id: UUID = Field(default_factory=uuid4, primary_key=True)
email_address: str = Field(unique=True, index=True)
tenant_id: UUID = Field(foreign_key="organizations.id", index=True)
created_at: datetime = Field(default_factory=datetime.utcnow)
updated_at: datetime = Field(default_factory=datetime.utcnow)
```
### Repository Pattern with Tenant Isolation
```python
# BaseRepository with automatic tenant filtering
class BaseRepository(Generic[T]):
def __init__(self, session: AsyncSession, model: type[T]):
self.session = session
self.model = model
async def get_by_id(self, id: UUID, tenant_id: UUID) -> Optional[T]:
"""Automatic tenant isolation."""
result = await self.session.execute(
select(self.model)
.where(self.model.id == id)
.where(self.model.tenant_id == tenant_id) # Always filter
)
return result.scalar_one_or_none()
```
### RLS Role Pattern
```typescript
// Database connections with RLS roles
const adminDb = drizzle(process.env.DATABASE_URL_ADMIN); // Full access
const authenticatedDb = drizzle(process.env.DATABASE_URL_AUTHENTICATED); // Tenant-scoped
const anonDb = drizzle(process.env.DATABASE_URL_ANON); // Public only
```
## Documentation Output Structure
### Directory Organization
```
documentation/
├── architecture/
│ ├── system-overview.md
│ ├── multi-tenant-architecture.md
│ └── deployment-architecture.md
├── domain-model/
│ ├── entities/
│ │ ├── user.md
│ │ ├── organization.md
│ │ └── team.md
│ ├── relationships.md
│ └── business-rules.md
├── diagrams/
│ ├── database-erd.mmd
│ ├── service-dependencies.mmd
│ ├── auth-flow.mmd
│ └── deployment.mmd
└── ontology.json
```
### Ontology JSON Structure
```json
{
"version": "1.0.0",
"system": "Grey Haven Application",
"architecture": "Multi-tenant TanStack Start + FastAPI",
"entities": [
{
"name": "User",
"table": "users",
"primaryKey": "id",
"tenantKey": "tenant_id",
"fields": [...],
"relationships": [...],
"businessRules": [...]
}
],
"services": [...],
"patterns": {
"multiTenant": true,
"rls": true,
"repositoryPattern": true
}
}
```
## When to Apply This Skill
Use ontological documentation when:
- Onboarding new developers to Grey Haven projects
- Designing new features with domain modeling
- Documenting multi-tenant architecture
- Analyzing legacy code before refactoring
- Creating architecture presentations for stakeholders
- Building knowledge bases for Grey Haven teams
- Ensuring consistency across TanStack Start and FastAPI implementations
- Auditing multi-tenant isolation patterns
- Planning database migrations or schema changes
## Integration with Other Grey Haven Skills
**Works Best With:**
- `grey-haven-database-conventions` - Ensure proper schema design
- `grey-haven-project-structure` - Understand codebase organization
- `grey-haven-authentication-patterns` - Document Better-auth integration
- `grey-haven-data-modeling` - Design Drizzle and SQLModel schemas
- `grey-haven-api-design-standards` - Document API hierarchies
## Critical Reminders
1. **Always document tenant_id** - Every entity must show tenant isolation
2. **Follow naming conventions** - snake_case for database, camelCase for TypeScript
3. **Include both TypeScript and Python** - Grey Haven uses both stacks
4. **Show RLS roles** - Document admin/authenticated/anon usage
5. **Repository pattern is required** - All data access goes through repositories
6. **UUID primary keys** - Never use auto-increment integers
7. **Timestamps are automatic** - created_at and updated_at
8. **Multi-tenant first** - Every design considers tenant isolation
9. **Visual diagrams required** - Mermaid for all architecture documentation
10. **Cross-reference skills** - Link to relevant Grey Haven skills
## Template References
These patterns are from Grey Haven's actual templates:
- **Frontend**: `cvi-template` (TanStack Start + React 19 + Drizzle)
- **Backend**: `cvi-backend-template` (FastAPI + SQLModel + Repository Pattern)
- **Multi-tenant**: Neon PostgreSQL with RLS

View File

@@ -0,0 +1,236 @@
# Ontological Documentation Checklist
Systematic checklist for creating comprehensive ontological documentation.
## Pre-Documentation
- [ ] **Identify codebase scope** (frontend, backend, or full-stack)
- [ ] **Understand domain** (business concepts, terminology)
- [ ] **Set up documentation tools** (Mermaid, diagramming tools)
- [ ] **Review existing documentation** (READMEs, architecture docs)
- [ ] **Identify stakeholders** (who will use this documentation)
## Concept Extraction
### Frontend (TanStack Start)
- [ ] **Database schema extracted** (Drizzle tables, relationships)
- [ ] **Component hierarchy mapped** (React component tree)
- [ ] **Routes documented** (TanStack Router structure)
- [ ] **State management identified** (Context, queries, mutations)
- [ ] **Server functions cataloged** (API surface)
### Backend (FastAPI)
- [ ] **SQLModel entities documented** (all models)
- [ ] **Relationships mapped** (foreign keys, associations)
- [ ] **Repository pattern documented** (all repositories)
- [ ] **Service layer mapped** (business logic)
- [ ] **API endpoints cataloged** (all routes)
- [ ] **Pydantic schemas listed** (request/response models)
### Multi-Tenant Patterns
- [ ] **tenant_id fields identified** on all tables
- [ ] **RLS policies documented** (row level security)
- [ ] **Tenant isolation verified** in queries
- [ ] **Repository filters documented** (automatic tenant filtering)
- [ ] **Admin vs user access documented**
## Entity Documentation
### For Each Entity
- [ ] **Name and purpose** clearly stated
- [ ] **Attributes documented** (all fields with types)
- [ ] **Relationships documented** (to other entities)
- [ ] **Constraints documented** (unique, required, validation)
- [ ] **Business rules noted** (validation, lifecycle)
### Database Entities
- [ ] **Table name** documented
- [ ] **Primary key** identified
- [ ] **Foreign keys** documented
- [ ] **Indexes** listed
- [ ] **Timestamps** (created_at, updated_at)
- [ ] **Tenant isolation** (tenant_id field)
## Relationship Mapping
### Types of Relationships
- [ ] **One-to-One** relationships documented
- [ ] **One-to-Many** relationships documented
- [ ] **Many-to-Many** relationships documented
- [ ] **Join tables** identified (for many-to-many)
- [ ] **Cascade behavior** documented (delete, update)
### Relationship Documentation
- [ ] **Source entity** identified
- [ ] **Target entity** identified
- [ ] **Relationship name** clear and descriptive
- [ ] **Cardinality** specified
- [ ] **Business meaning** explained
## Architecture Documentation
### System Components
- [ ] **Frontend components** listed and categorized
- [ ] **Backend services** documented
- [ ] **Database** structure documented
- [ ] **External services** identified (Stripe, Resend, etc.)
- [ ] **Authentication system** documented (Better-auth)
### Data Flow
- [ ] **User actions****Frontend** flow documented
- [ ] **Frontend****Backend** API calls documented
- [ ] **Backend****Database** queries documented
- [ ] **Backend****External services** documented
- [ ] **Response flow** back to user documented
## Visualization
### Diagrams Created
- [ ] **Entity-Relationship Diagram** (ERD) for database
- [ ] **Component Hierarchy** for React components
- [ ] **Architecture Overview** showing all systems
- [ ] **Data Flow Diagrams** for critical paths
- [ ] **Multi-Tenant Isolation** diagram
### Diagram Quality
- [ ] **Clear labels** on all elements
- [ ] **Legend provided** (symbols explained)
- [ ] **Color coding** used effectively
- [ ] **Readable font size** and layout
- [ ] **Diagrams source-controlled** (Mermaid or PlantUML)
## Domain Model
### Business Concepts
- [ ] **Core domain entities** identified
- [ ] **Business processes** documented
- [ ] **Business rules** captured
- [ ] **Domain terminology** defined
- [ ] **Invariants** documented
### Semantic Relationships
- [ ] **"Is-a" relationships** (inheritance)
- [ ] **"Has-a" relationships** (composition)
- [ ] **"Uses" relationships** (dependencies)
- [ ] **Aggregation** relationships
- [ ] **Association** relationships
## Grey Haven Specific
### Multi-Tenant Architecture
- [ ] **Tenant model** documented
- [ ] **Organization model** documented
- [ ] **User-Tenant relationship** explained
- [ ] **Team structure** documented (if applicable)
- [ ] **RLS roles** explained (admin, authenticated, anon)
### Authentication & Authorization
- [ ] **Better-auth integration** documented
- [ ] **Session management** explained
- [ ] **User roles** documented
- [ ] **Permission model** explained
- [ ] **OAuth providers** listed
### Database Conventions
- [ ] **Naming conventions** documented (snake_case)
- [ ] **UUID usage** explained (primary keys)
- [ ] **Timestamp fields** standardized
- [ ] **Soft deletes** documented (if used)
- [ ] **Audit fields** documented (if used)
## Documentation Quality
### Completeness
- [ ] **All entities** documented
- [ ] **All relationships** documented
- [ ] **All business rules** captured
- [ ] **All external integrations** noted
- [ ] **All deployment architecture** documented
### Clarity
- [ ] **Technical jargon** explained
- [ ] **Domain terminology** consistent
- [ ] **Examples provided** where helpful
- [ ] **Diagrams clear** and readable
- [ ] **Navigation easy** (links, TOC)
### Maintainability
- [ ] **Documentation source-controlled** (with code)
- [ ] **Update process** defined
- [ ] **Ownership** assigned (who maintains)
- [ ] **Review schedule** established
- [ ] **Feedback mechanism** in place
## Automation
### Scripts Used
- [ ] **extract_concepts.py** run successfully
- [ ] **generate_ontology_diagram.py** produced diagrams
- [ ] **Output reviewed** and verified
- [ ] **Customizations documented**
- [ ] **Scripts committed** to repository
### Continuous Documentation
- [ ] **Documentation updates** in PR checklist
- [ ] **Schema changes** trigger doc updates
- [ ] **API changes** trigger doc updates
- [ ] **CI checks** for documentation completeness
## Stakeholder Review
### Technical Review
- [ ] **Developers reviewed** documentation
- [ ] **Technical accuracy** verified
- [ ] **Missing information** identified
- [ ] **Feedback incorporated**
### Business Review
- [ ] **Domain experts reviewed** business concepts
- [ ] **Business terminology** verified
- [ ] **Business rules** confirmed
- [ ] **Use cases validated**
## Deployment
### Documentation Delivery
- [ ] **Documentation committed** to repository
- [ ] **README updated** with links
- [ ] **Wiki/Confluence** updated (if used)
- [ ] **Team notified** of new documentation
- [ ] **Onboarding materials** updated
### Accessibility
- [ ] **Documentation discoverable** (easy to find)
- [ ] **Navigation clear** (links, search)
- [ ] **Formats appropriate** (markdown, diagrams)
- [ ] **Mobile-friendly** (if applicable)
## Scoring
- **90+ items checked**: Excellent - Comprehensive documentation ✅
- **75-89 items**: Good - Most areas covered ⚠️
- **60-74 items**: Fair - Significant gaps exist 🔴
- **<60 items**: Poor - Inadequate documentation ❌
## Priority Items
Address these first:
1. **Entity documentation** - Core to understanding
2. **Relationship mapping** - Critical for navigation
3. **Multi-tenant patterns** - Security-critical
4. **Data flow diagrams** - Helps debugging
5. **Automation setup** - Saves time
## Related Resources
- [Concept Extraction Guide](../reference/concept_extraction_guide.md)
- [Ontology Patterns](../reference/ontology_patterns.md)
- [Examples](../examples/INDEX.md)
- [Templates](../templates/)
- [Scripts](../scripts/)
---
**Total Items**: 100+ documentation checks
**Critical Items**: Entity docs, Relationships, Multi-tenant, Data flow
**Last Updated**: 2025-11-09

View File

@@ -0,0 +1,69 @@
# Ontological Documentation Examples
Real-world examples of creating ontological documentation for Grey Haven systems.
## Available Examples
1. **[TanStack Start Ontology](tanstack-start-example.md)** - Frontend codebase analysis
- Extracting concepts from Drizzle schemas
- Mapping React component hierarchies
- Documenting multi-tenant patterns
- Visualizing route structure
2. **[FastAPI Ontology](fastapi-example.md)** - Backend codebase analysis
- SQLModel entity relationships
- Repository pattern documentation
- Service layer mapping
- API endpoint hierarchy
3. **[Multi-Tenant System Architecture](multi-tenant-ontology.md)** - Complete system documentation
- Tenant isolation patterns
- RLS policies visualization
- Database schema relationships
- Authentication flow
4. **[Domain Model Extraction](domain-model-extraction.md)** - Business concept mapping
- Identifying domain entities
- Relationship mapping
- Business rule documentation
- Semantic relationships
## Recommended Path
**For new projects:**
1. Start with [domain-model-extraction.md](domain-model-extraction.md)
2. Document frontend with [tanstack-start-example.md](tanstack-start-example.md)
3. Document backend with [fastapi-example.md](fastapi-example.md)
4. Complete system view with [multi-tenant-ontology.md](multi-tenant-ontology.md)
**For existing systems:**
1. Run extraction scripts on codebase
2. Follow [domain-model-extraction.md](domain-model-extraction.md) to identify concepts
3. Use templates to document findings
## Quick Reference
### Frontend Ontology
- See [tanstack-start-example.md](tanstack-start-example.md)
- Use `scripts/extract_concepts.py` for automation
### Backend Ontology
- See [fastapi-example.md](fastapi-example.md)
- Focus on repository and service patterns
### Visualization
- See [multi-tenant-ontology.md](multi-tenant-ontology.md)
- Use `scripts/generate_ontology_diagram.py`
## Related Materials
- **[Concept Extraction Guide](../reference/concept_extraction_guide.md)** - How to extract concepts
- **[Ontology Patterns](../reference/ontology_patterns.md)** - Common patterns
- **[Templates](../templates/)** - Ready-to-use ontology templates
- **[Scripts](../scripts/)** - Automation scripts
---
**Total Examples**: 4 comprehensive guides
**Coverage**: TanStack Start, FastAPI, Multi-tenant, Domain modeling
**Last Updated**: 2025-11-09

View File

@@ -0,0 +1,98 @@
# E-Commerce Domain Ontology Example
## Overview
This example demonstrates an ontological documentation approach for a typical e-commerce system.
## Core Concepts
### Primary Entities
```
E-Commerce Domain
├── Customer Management
│ ├── Customer
│ ├── CustomerProfile
│ └── Address
├── Product Management
│ ├── Product
│ ├── Category
│ └── ProductVariant
├── Order Management
│ ├── Order
│ ├── OrderLine
│ └── OrderStatus
└── Payment Management
├── Payment
├── PaymentMethod
└── PaymentStatus
```
### Key Relationships
#### Customer Relationships
- **Customer** has-a **CustomerProfile**
- **Customer** has-many **Address**
- **Customer** places-many **Order**
- **Customer** has-many **Payment**
#### Product Relationships
- **Product** belongs-to **Category**
- **Product** has-many **ProductVariant**
- **ProductVariant** appears-in **OrderLine**
#### Order Relationships
- **Order** contains-many **OrderLine**
- **Order** has-a **OrderStatus**
- **Order** has-a **Payment**
- **OrderLine** references-a **ProductVariant**
## Business Rules
### Customer Rules
- Customer must have at least one address
- Customer profile must include valid email
- Customer can have multiple shipping addresses
### Order Rules
- Order must have at least one order line
- Order total must equal sum of order line totals
- Order status progression is immutable
### Payment Rules
- Payment amount must match order total
- Payment method must be valid for customer
- Payment status affects order fulfillment
## Implementation Examples
### Order Entity Example
```python
class Order:
def __init__(self, customer: Customer):
self.customer = customer
self.order_lines: List[OrderLine] = []
self.status = OrderStatus.PENDING
self.created_at = datetime.now()
def add_product(self, product: ProductVariant, quantity: int):
# Add business logic for adding products
pass
def calculate_total(self) -> Money:
# Calculate order total
pass
```
### Relationship Example
```python
# Order -> Customer relationship
class Order:
def __init__(self, customer: Customer):
self.customer_id = customer.id # Reference relationship
self.customer = customer # Object relationship
```
## Documentation Links
- [Customer Documentation](customer-concept.md)
- [Product Documentation](product-concept.md)
- [Order Documentation](order-concept.md)
- [Payment Documentation](payment-concept.md)

View File

@@ -0,0 +1,43 @@
# Ontological Documentation Reference
Technical reference for creating ontological documentation of Grey Haven systems.
## Reference Materials
1. **[Concept Extraction Guide](concept_extraction_guide.md)** - How to extract concepts from code
- TanStack Start extraction patterns
- FastAPI extraction patterns
- Identifying entities and relationships
- Semantic analysis techniques
2. **[Ontology Patterns](ontology_patterns.md)** - Common Grey Haven patterns
- Multi-tenant patterns
- Repository pattern
- Service layer patterns
- Authentication patterns
- Database conventions
3. **[Documentation Templates](documentation_templates.md)** - Template formats
- Entity documentation
- Relationship diagrams
- Architecture overviews
- Domain model templates
4. **[Visualization Techniques](visualization-techniques.md)** - Diagram creation
- Mermaid diagrams
- Entity-relationship diagrams
- Component hierarchies
- Data flow diagrams
## Quick Links
- For examples: See [examples/](../examples/INDEX.md)
- For templates: See [templates/](../templates/)
- For scripts: See [scripts/](../scripts/)
- For checklists: See [checklists/](../checklists/)
---
**Coverage**: Concept extraction, Patterns, Templates, Visualization
**Platforms**: TanStack Start, FastAPI
**Last Updated**: 2025-11-09

View File

@@ -0,0 +1,55 @@
# Reference Guides
This directory contains comprehensive reference guides for ontological documentation.
## Files
### concept_extraction_guide.md
Methodologies and techniques for identifying and extracting domain concepts, entities, and relationships from software codebases.
**Topics covered:**
- Static code analysis techniques
- Naming convention analysis
- Data structure analysis
- Configuration and metadata analysis
- Language-specific extraction patterns (Python, JavaScript/TypeScript, Java)
- Concept categorization framework
- Relationship identification
- Extraction workflow
- Quality assurance
### documentation_templates.md
Standardized templates for creating comprehensive ontological documentation.
**Templates included:**
- Concept Definition Template
- Relationship Documentation Template
- Domain Model Overview Template
- Ontology Change Log Template
- API Ontology Template
- Database Schema Ontology Template
- Event-Driven Architecture Ontology Template
### ontology_patterns.md
Common ontological patterns and taxonomies found in software systems.
**Patterns covered:**
- Fundamental relationship types (Is-A, Part-Of, Instance-Of, Depends-On, Associates-With)
- Layered Architecture Pattern
- Domain-Driven Design Pattern
- MVC Pattern Ontology
- Microservices Pattern Ontology
- Taxonomy classification systems
- Ontology validation rules
## Usage
These guides are designed to be used together:
1. Start with **ontology_patterns.md** to understand common patterns
2. Use **concept_extraction_guide.md** to extract concepts from your codebase
3. Apply **documentation_templates.md** to document your findings
## Integration with Main Skill
These references support the main [SKILL.md](../SKILL.md) and are automatically available when the ontological documentation skill is activated.

View File

@@ -0,0 +1,271 @@
# Concept Extraction Guide for Software Systems
This guide provides methodologies and techniques for identifying and extracting domain concepts, entities, and relationships from software codebases to build ontological documentation.
## Extraction Methodologies
### 1. Static Code Analysis
#### Class and Interface Analysis
- **Objective**: Identify conceptual entities and their hierarchies
- **Sources**: Class definitions, interface declarations, type annotations
- **Techniques**:
- Parse AST (Abstract Syntax Trees) to find type definitions
- Extract inheritance relationships (extends, implements)
- Identify composition patterns through member variables
- Analyze method signatures for behavioral concepts
#### Function and Method Analysis
- **Objective**: Discover actions, processes, and behavioral concepts
- **Sources**: Function definitions, method declarations
- **Techniques**:
- Group related functions into conceptual categories
- Identify command/query patterns (CQRS)
- Extract business process flows from method call chains
- Map function parameters to conceptual relationships
#### Import and Dependency Analysis
- **Objective**: Understand system boundaries and external dependencies
- **Sources**: Import statements, package dependencies, service calls
- **Techniques**:
- Map module dependencies to conceptual relationships
- Identify external system boundaries
- Categorize dependencies (internal, external, third-party)
- Analyze dependency graphs for architectural insights
### 2. Naming Convention Analysis
#### Semantic Naming Patterns
- **Entity Nouns**: User, Order, Product, Account (domain objects)
- **Process Verbs**: ProcessPayment, ValidateInput, SendEmail (actions)
- **State Adjectives**: Active, Pending, Completed, Expired (states)
- **Role-based Names**: AdminService, UserGateway, PaymentProcessor (roles)
#### Naming Pattern Recognition
```
Entity + Pattern = Concept Type
- User + Repository = Data Access Concept
- Order + Service = Business Logic Concept
- Payment + Gateway = Integration Concept
- Notification + Event = Event Concept
```
### 3. Data Structure Analysis
#### Database Schema Analysis
- **Tables as Entities**: Each table represents a domain concept
- **Foreign Keys as Relationships**: FKs define relationships between concepts
- **Indexes as Properties**: Important attributes for concept identification
- **Constraints as Rules**: Business rules and validation logic
#### API Contract Analysis
- **REST Resources**: URL paths often map to domain concepts
- **GraphQL Types**: Schema types define conceptual models
- **Message Schemas**: Event/message structures reveal concepts
- **OpenAPI Specifications**: Complete conceptual model of external interface
### 4. Configuration and Metadata Analysis
#### Configuration Files
- **Application Settings**: System behavior concepts
- **Feature Flags**: Feature-based concept organization
- **Environment Variables**: Deployment and environment concepts
- **Routing Tables**: Navigation and flow concepts
#### Documentation and Comments
- **README Files**: High-level conceptual overview
- **Code Comments**: Designer intent and conceptual explanations
- **API Documentation**: External conceptual contracts
- **Architecture Diagrams**: Visual conceptual relationships
## Extraction Techniques by Language
### Python
```python
# Key patterns to identify:
class UserService: # Service concept
def __init__(self, user_repo): # Dependency relationship
self.user_repo = user_repo
def create_user(self, user_dto): # Action concept
# Domain logic here
pass
# Look for:
# - Class definitions (entities, services, repositories)
# - Method names (actions, processes)
# - Parameter types (relationships)
# - Decorators (cross-cutting concerns)
```
### JavaScript/TypeScript
```typescript
// Key patterns to identify:
interface User { # Entity concept
id: string;
name: string;
}
class UserService { # Service concept
constructor(private userRepo: UserRepository) {} # Dependency
async createUser(userData: CreateUserDto): Promise<User> { # Action + types
// Implementation
}
}
// Look for:
# - Interface definitions (contracts, entities)
# - Class definitions (services, controllers)
# - Type annotations (concept properties)
# - Decorators (metadata, concerns)
```
### Java
```java
// Key patterns to identify:
@Entity # Entity annotation
public class User { # Entity concept
@Id
private Long id;
@OneToMany # Relationship annotation
private List<Order> orders;
}
@Service # Service annotation
public class UserService { # Service concept
@Autowired # Dependency injection
private UserRepository userRepo;
public User createUser(UserDto userDto) { // Action + type
// Implementation
}
}
// Look for:
# - Annotations (component types, relationships)
# - Class definitions (entities, services)
# - Interface definitions (contracts)
# - Method signatures (actions, processes)
```
## Concept Categorization Framework
### Primary Categories
1. **Domain Entities** (Nouns)
- Core business objects: User, Order, Product, Account
- Usually persistent, have identity
- Contain business logic and state
2. **Value Objects** (Nouns)
- Immutable concepts without identity: Address, Money, DateRange
- Defined by their attributes
- Often embedded in entities
3. **Services** (Verb + Noun)
- Business logic coordinators: UserService, PaymentService
- Stateless operations
- Orchestrate domain objects
4. **Repositories** (Noun + Repository/Store)
- Data access abstractions: UserRepository, OrderRepository
- Collection-like interfaces
- Hide storage details
5. **Controllers/Handlers** (Noun + Controller/Handler)
- Request/response coordination: UserController, OrderController
- Interface between external world and domain
- Thin layer, delegate to services
### Secondary Categories
6. **Events/Notifications** (Past Tense Verbs + Noun)
- State changes: OrderCreated, PaymentProcessed, UserRegistered
- Asynchronous communication
- Decouple system components
7. **DTOs/Models** (Noun + Dto/Model)
- Data transfer objects: UserDto, OrderModel
- External contract representations
- No business logic
8. **Utilities/Helpers** (Adjective/Noun + Utility/Helper)
- Cross-cutting functionality: ValidationHelper, EmailUtility
- Reusable operations
- No domain concepts
## Relationship Identification
### Direct Relationships
- **Inheritance**: `class Admin extends User` (Is-A)
- **Composition**: `class Order { private List<OrderLine> lines; }` (Part-Of)
- **Dependency**: `UserService(UserRepository repo)` (Depends-On)
### Indirect Relationships
- **Shared Interfaces**: Implement same interface (Associates-With)
- **Common Patterns**: Similar naming or structure (Similar-To)
- **Event Connections**: Producer-consumer patterns (Communicates-With)
### Semantic Relationships
- **Temporal**: CreatedBefore, UpdatedAfter
- **Spatial**: Contains, LocatedWithin
- **Causal**: Triggers, Enables, Prevents
- **Logical**: Implies, Contradicts, Equivalent
## Extraction Workflow
### Phase 1: Automated Extraction
1. Run static analysis tools to identify:
- Class/interface definitions
- Inheritance hierarchies
- Import dependencies
- Method signatures
### Phase 2: Manual Analysis
1. Review automated results for semantic accuracy
2. Identify implicit concepts not captured by code
3. Map business terminology to technical concepts
4. Validate relationships with domain experts
### Phase 3: Ontology Construction
1. Organize concepts into hierarchies
2. Define relationships between concepts
3. Add semantic metadata and descriptions
4. Validate completeness and consistency
### Phase 4: Documentation Generation
1. Create visual representations
2. Generate textual documentation
3. Create interactive navigation
4. Establish maintenance processes
## Quality Assurance
### Validation Checks
- [ ] All identified concepts have clear definitions
- [ ] Relationships are correctly classified
- [ ] No circular inheritance exists
- [ ] Domain terminology is consistent
- [ ] Technical and business concepts are aligned
### Review Process
1. **Developer Review**: Technical accuracy and completeness
2. **Domain Expert Review**: Business concept validation
3. **Architecture Review**: Consistency with system design
4. **Documentation Review**: Clarity and usability
## Maintenance Strategies
### Continuous Updates
- Monitor code changes for new concepts
- Update ontology when requirements evolve
- Regular reviews with stakeholders
- Automated validation checks
### Version Management
- Tag ontology versions with releases
- Track concept evolution over time
- Maintain change logs
- Backward compatibility considerations

View File

@@ -0,0 +1,447 @@
# Ontological Documentation Templates
This document provides standardized templates for creating comprehensive ontological documentation for software systems.
## Core Documentation Templates
### 1. Concept Definition Template
```markdown
# [Concept Name]
## Quick Reference
- **Type**: [Entity/Value Object/Service/Repository/etc.]
- **Category**: [Domain/Business/Infrastructure/etc.]
- **Status**: [Active/Deprecated/Experimental]
- **Owner**: [Team/Person responsible]
## Definition
[Clear, concise definition of the concept. What is it? What purpose does it serve?]
## Purpose and Scope
**Why this concept exists:**
- [Problem it solves]
- [Business requirement it addresses]
- [Technical necessity]
**Scope and Boundaries:**
- [What's included]
- [What's excluded]
- [Related but separate concepts]
## Characteristics
### Essential Properties
- **Property 1**: [Description] - [Type] - [Constraints]
- **Property 2**: [Description] - [Type] - [Constraints]
### Behavioral Aspects
- **Action 1**: [Description] - [Preconditions] - [Postconditions]
- **Action 2**: [Description] - [Preconditions] - [Postconditions]
### Constraints and Rules
- [Business rule 1]
- [Validation rule 2]
- [Integrity constraint 3]
## Relationships
### Hierarchical Relationships
- **Is-A**: [Parent Concept] - [Rationale]
- **Has-A**: [Child Components] - [Composition details]
### Dependency Relationships
- **Depends-On**: [Required Concept] - [Dependency type]
- **Required-By**: [Dependent Concept] - [Usage context]
### Association Relationships
- **Associates-With**: [Related Concept] - [Nature of association]
- **Similar-To**: [Analogous Concept] - [Comparison points]
## Implementation
### Code Representation
```python
# Example implementation
class [ConceptName]:
def __init__(self):
self.property1 = None
self.property2 = None
```
### Data Structure
- **Storage Format**: [Database table, JSON, etc.]
- **Serialization**: [How it's represented in API/transport]
- **Persistence**: [Where and how it's stored]
### Lifecycle
- **Creation**: [How instances are created]
- **Evolution**: [How instances change over time]
- **Deletion**: [How instances are removed]
## Examples
### Concrete Examples
1. **Example 1**: [Specific instance with explanation]
- [Context]
- [Properties]
- [Behavior]
2. **Example 2**: [Another specific instance]
- [Context]
- [Properties]
- [Behavior]
### Usage Patterns
- **Pattern 1**: [Common usage scenario]
- **Pattern 2**: [Another usage scenario]
## Evolution and History
- **Created**: [Date] - [Initial reason]
- **Major Changes**: [Change history]
- **Future Roadmap**: [Planned modifications]
## Related Documentation
- [Link to related concepts]
- [Link to implementation details]
- [Link to API documentation]
- [Link to user documentation]
```
### 2. Relationship Documentation Template
```markdown
# [Relationship Type]: [Source Concept] → [Target Concept]
## Relationship Overview
- **Type**: [Is-A/Part-Of/Depends-On/Associates-With/etc.]
- **Source**: [Source Concept Name]
- **Target**: [Target Concept Name]
- **Strength**: [Strong/Medium/Weak]
- **Direction**: [Unidirectional/Bidirectional]
## Definition
[Clear explanation of what this relationship means in the domain context]
## Rationale
**Why this relationship exists:**
- [Business reason]
- [Technical necessity]
- [Domain modeling decision]
## Characteristics
### Cardinality
- **Source → Target**: [One-to-One/One-to-Many/Many-to-Many]
- **Minimum**: [Required/Optional - specify minimum]
- **Maximum**: [Unbounded/Specific limit]
### Constraints
- **Existence Constraint**: [Rules about when relationship can exist]
- **Deletion Constraint**: [What happens when one end is deleted]
- **Update Constraint**: [How relationship changes are handled]
### Semantic Properties
- **Transitivity**: [Whether relationship is transitive]
- **Symmetry**: [Whether relationship is symmetric]
- **Reflexivity**: [Whether relationship is reflexive]
## Implementation
### Code Representation
```python
# Example implementation
class SourceConcept:
def __init__(self):
self.target_concepts = [] # Relationship implementation
```
### Data Modeling
- **Foreign Keys**: [How relationship is stored in database]
- **Join Tables**: [If applicable, for many-to-many relationships]
- **Indexing**: [Performance considerations]
### API Representation
- **REST Endpoints**: [How relationship is exposed in API]
- **GraphQL Schema**: [How relationship appears in GraphQL]
- **Serialization**: [How relationship is represented in JSON/XML]
## Examples
### Example Instances
1. **Example 1**: [Specific relationship instance]
- **Source Instance**: [Details]
- **Target Instance**: [Details]
- **Context**: [When and why this exists]
2. **Example 2**: [Another specific instance]
- **Source Instance**: [Details]
- **Target Instance**: [Details]
- **Context**: [When and why this exists]
### Usage Patterns
- **Creation Pattern**: [How relationships are established]
- **Query Pattern**: [How relationships are accessed]
- **Modification Pattern**: [How relationships are changed]
## Validation Rules
### Business Rules
- [Rule 1]: [Description and validation logic]
- [Rule 2]: [Description and validation logic]
### Technical Constraints
- [Constraint 1]: [Technical limitation or requirement]
- [Constraint 2]: [Performance or scalability consideration]
## Related Documentation
- [Source Concept Documentation]
- [Target Concept Documentation]
- [Related Relationships]
- [Implementation Details]
```
### 3. Domain Model Overview Template
```markdown
# [Domain Name] Domain Model
## Executive Summary
[Brief overview of the domain and its core concepts]
## Core Concepts Map
[Visual representation or hierarchical list of main concepts]
### Primary Entities
- **[Entity 1]**: [Brief description]
- **[Entity 2]**: [Brief description]
- **[Entity 3]**: [Brief description]
### Supporting Concepts
- **[Value Object 1]**: [Brief description]
- **[Service 1]**: [Brief description]
- **[Repository 1]**: [Brief description]
## Concept Hierarchy
```
[Top-level concepts]
├── [Category 1]
│ ├── [Sub-concept 1.1]
│ ├── [Sub-concept 1.2]
│ └── [Sub-concept 1.3]
├── [Category 2]
│ ├── [Sub-concept 2.1]
│ └── [Sub-concept 2.2]
└── [Category 3]
├── [Sub-concept 3.1]
└── [Sub-concept 3.2]
```
## Key Relationships
### Critical Relationships
1. **[Relationship 1]**: [Source] → [Target]
- [Importance and impact]
- [Business significance]
2. **[Relationship 2]**: [Source] → [Target]
- [Importance and impact]
- [Business significance]
### Relationship Patterns
- **Composition Pattern**: [Description]
- **Dependency Pattern**: [Description]
- **Association Pattern**: [Description]
## Business Rules and Constraints
### Domain Rules
1. **[Rule 1]**: [Description] - [Impact]
2. **[Rule 2]**: [Description] - [Impact]
### Invariants
- **Invariant 1**: [What must always be true]
- **Invariant 2**: [What must always be true]
## Processes and Workflows
### Core Business Processes
1. **[Process 1]**
- **Trigger**: [What starts the process]
- **Steps**: [Sequence of actions]
- **Actors**: [Who/what participates]
- **Outcomes**: [Results and side effects]
2. **[Process 2]**
- **Trigger**: [What starts the process]
- **Steps**: [Sequence of actions]
- **Actors**: [Who/what participates]
- **Outcomes**: [Results and side effects]
### State Machines
- **[Entity 1] States**: [State transitions and conditions]
- **[Entity 2] States**: [State transitions and conditions]
## Integration Points
### External Systems
- **[System 1]**: [Integration type and purpose]
- **[System 2]**: [Integration type and purpose]
### Data Flows
- **Inbound Data**: [What data comes from where]
- **Outbound Data**: [What data goes to where]
## Evolution Strategy
### Current State
- [Description of current domain model state]
### Planned Changes
- **[Change 1]**: [Description and timeline]
- **[Change 2]**: [Description and timeline]
### Migration Strategy
- [How to transition from current to future state]
## Quality Metrics
### Model Health
- **Complexity**: [Assessment of model complexity]
- **Consistency**: [How consistent the model is]
- **Completeness**: [Gaps and coverage]
### Usage Metrics
- **Most Used Concepts**: [Statistics on concept usage]
- **Relationship Density**: [How interconnected concepts are]
- **Change Frequency**: [How often concepts change]
## Related Documentation
- [Link to detailed concept documentation]
- [Link to API documentation]
- [Link to business requirements]
- [Link to technical architecture]
```
### 4. Ontology Change Log Template
```markdown
# Ontology Change Log
## Version [Version Number] - [Date]
### Summary
[Brief overview of changes in this version]
### Added Concepts
- **[Concept Name]**: [Reason for addition] - [Impact]
- **[Concept Name]**: [Reason for addition] - [Impact]
### Modified Concepts
- **[Concept Name]**: [Changes made] - [Reason for change] - [Impact]
- **[Concept Name]**: [Changes made] - [Reason for change] - [Impact]
### Removed Concepts
- **[Concept Name]**: [Reason for removal] - [Migration strategy]
### Added Relationships
- **[Relationship]**: [Source] → [Target] - [Reason]
### Modified Relationships
- **[Relationship]**: [Source] → [Target] - [Changes] - [Reason]
### Removed Relationships
- **[Relationship]**: [Source] → [Target] - [Reason] - [Impact]
### Breaking Changes
- **[Change Description]**: [Impact on dependent systems] - [Migration required]
### Migration Guide
[Step-by-step guide for adapting to these changes]
## Previous Versions
[Link to previous change logs]
```
## Specialized Templates
### API Ontology Template
```markdown
# [API Name] Ontology
## Resource Model
[List of all resources and their relationships]
## Semantic Operations
[CRUD operations and their domain meanings]
## Media Types
[Content types and their semantic significance]
## Hypermedia Controls
[HATEOAS relationships and link semantics]
```
### Database Schema Ontology Template
```markdown
# [Database Name] Schema Ontology
## Table Concepts
[Tables as domain concepts]
## Column Semantics
[Columns as concept properties]
## Constraint Logic
[Constraints as business rules]
## Trigger Semantics
[Triggers as automated processes]
```
### Event-Driven Architecture Ontology Template
```markdown
# [System Name] Event Ontology
## Event Taxonomy
[Categorization of all events]
## Event Relationships
[Causal and temporal relationships]
## Event Semantics
[Meaning and significance of events]
## Process Integration
[How events drive business processes]
```
## Template Usage Guidelines
### When to Use Each Template
1. **Concept Definition**: Use for every significant domain concept
2. **Relationship Documentation**: Use for critical or complex relationships
3. **Domain Model Overview**: Use for bounded contexts or major domains
4. **Change Log**: Use for every ontology modification
5. **Specialized Templates**: Use for specific architectural patterns
### Quality Checklist
For each documentation entry:
- [ ] Definition is clear and unambiguous
- [ ] Purpose and scope are well-defined
- [ ] Relationships are accurately described
- [ ] Examples are relevant and illustrative
- [ ] Implementation details are correct
- [ ] Related documentation is linked
- [ ] Review date is recorded
- [ ] Owner is identified
### Review Process
1. **Self-Review**: Check completeness and accuracy
2. **Peer Review**: Get feedback from other developers
3. **Domain Expert Review**: Validate with domain experts
4. **Architecture Review**: Ensure alignment with system architecture
5. **Documentation Review**: Check for clarity and usability

View File

@@ -0,0 +1,230 @@
# Ontological Patterns in Software Documentation
This document describes common ontological patterns and taxonomies found in software systems for creating effective conceptual documentation.
## Core Ontological Concepts
### Fundamental Relationship Types
**Is-A (Inheritance/Hyponymy)**
- Description: A concept is a subtype or specialization of another concept
- Example: `User` is-a `Person`, `Manager` is-a `Employee`
- Code pattern: Class inheritance, interface implementation
- Documentation: Use "extends," "inherits from," "is a type of"
**Part-Of (Mereology/Composition)**
- Description: A concept is a component or constituent of another concept
- Example: `Wheel` is-part-of `Car`, `Method` is-part-of `Class`
- Code pattern: Object composition, nested classes, containment relationships
- Documentation: Use "contains," "comprises," "consists of"
**Instance-Of (Instantiation)**
- Description: An object is an instance of a concept/class
- Example: `john_doe` is-instance-of `User`, `order_123` is-instance-of `Order`
- Code pattern: Object creation, variable assignment
- Documentation: Use "instance of," "example of," "specific case of"
**Depends-On (Dependency)**
- Description: A concept requires or relies on another concept
- Example: `OrderService` depends-on `PaymentGateway`, `Controller` depends-on `Service`
- Code pattern: Import statements, dependency injection, method calls
- Documentation: Use "requires," "uses," "relies on"
**Associates-With (Association)**
- Description: A concept has a loose semantic connection to another concept
- Example: `User` associates-with `Order`, `Product` associates-with `Category`
- Code pattern: Foreign keys, bidirectional references, event subscriptions
- Documentation: Use "related to," "connected with," "associated with"
## Common Software Ontology Patterns
### Layered Architecture Pattern
```
Presentation Layer
├── Controllers
├── Views
└── ViewModels
Business Logic Layer
├── Services
├── Domain Models
└── Business Rules
Data Access Layer
├── Repositories
├── Data Mappers
└── Database Models
Infrastructure Layer
├── External APIs
├── Message Queues
└── File Storage
```
**Relationships:**
- Controllers depend-on Services
- Services depend-on Repositories
- Repositories depend-on Database Models
- ViewModels part-of Presentation Layer
### Domain-Driven Design Pattern
**Entities**: Objects with distinct identity
- `Customer`, `Order`, `Product`
**Value Objects**: Objects defined by their attributes
- `Address`, `Money`, `DateRange`
**Aggregates**: Clusters of domain objects
- `OrderAggregate` contains `Order`, `OrderLine`, `OrderStatus`
**Repositories**: Collections of aggregate roots
- `CustomerRepository`, `OrderRepository`
**Domain Services**: Business logic that doesn't fit in entities
- `PaymentService`, `ShippingService`
### MVC Pattern Ontology
```
Model
├── Entity Models
├── View Models
└── Data Transfer Objects
View
├── Templates
├── Components
└── Layouts
Controller
├── Action Methods
├── Route Handlers
└── API Endpoints
```
**Relationships:**
- Controllers manipulate Models
- Controllers select Views
- Views display Models
- Models notify Views of changes
### Microservices Pattern Ontology
**Service Categories:**
- **API Gateway**: Entry point for external requests
- **Core Services**: Business logic services
- **Supporting Services**: Shared functionality (auth, logging)
- **Data Services**: Database operations
**Service Relationships:**
- `API Gateway` routes-to `Core Services`
- `Core Services` call `Supporting Services`
- `Services` publish-to `Message Broker`
- `Services` read-from `Configuration Service`
## Taxonomy Classification Systems
### Functional Classification
**By Purpose:**
- Business Logic Components
- Data Management Components
- Presentation Components
- Integration Components
- Infrastructure Components
**By Lifecycle:**
- Singleton Components
- Scoped Components
- Transient Components
- Request-scoped Components
### Structural Classification
**By Abstraction Level:**
- Interface Layer (highest abstraction)
- Service Layer
- Repository Layer
- Data Layer (lowest abstraction)
**By Coupling:**
- Tightly Coupled Components
- Loosely Coupled Components
- Decoupled Components
## Documentation Templates
### Concept Documentation Template
```markdown
# [Concept Name]
## Definition
Brief, clear definition of the concept
## Purpose
Why this concept exists and what problem it solves
## Characteristics
Key attributes and properties of the concept
## Relationships
- **Is-A**: [Parent concepts]
- **Part-Of**: [Containing concepts]
- **Depends-On**: [Required concepts]
- **Associates-With**: [Related concepts]
## Examples
Concrete examples of the concept in use
## Implementation Notes
Technical implementation details and considerations
```
### Relationship Documentation Template
```markdown
# [Relationship Type]: [Source] → [Target]
## Relationship Description
Description of the semantic relationship
## Cardinality
- One-to-One, One-to-Many, Many-to-Many
- Required vs Optional
## Constraints
Rules and limitations on the relationship
## Implementation
How the relationship is implemented in code
## Examples
Specific examples of the relationship
```
## Ontology Validation Rules
### Consistency Rules
1. **No Circular Inheritance**: A class cannot inherit from itself (directly or indirectly)
2. **Complete Relationships**: All referenced concepts must be defined
3. **Consistent Naming**: Use consistent terminology throughout the ontology
4. **Proper Abstraction Levels**: Related concepts should be at similar abstraction levels
### Completeness Rules
1. **Defined Concepts**: All concepts must have clear definitions
2. **Documented Relationships**: All relationships should be explicitly documented
3. **Coverage**: Important domain concepts should be represented
4. **Hierarchy**: Concepts should be organized in logical hierarchies
### Best Practices
1. **Use Standard Terminology**: Prefer established domain vocabulary
2. **Avoid Ambiguity**: Define terms clearly and consistently
3. **Maintain Separation**: Separate conceptual models from implementation details
4. **Document Rationale**: Explain why certain relationships exist
5. **Regular Review**: Update ontology as system evolves

View File

@@ -0,0 +1,114 @@
# Ontological Documentation Scripts
This directory contains utility scripts for automated concept extraction and diagram generation.
## Scripts
### extract_concepts.py
Analyzes codebases to extract domain concepts, entities, and relationships for building ontological documentation.
**Features:**
- Supports Python and JavaScript/TypeScript
- Extracts classes, functions, inheritance relationships, and imports
- Builds ontological structure with relationships (is_a, part_of, depends_on, associates_with)
- Generates JSON ontology representation
- Creates Mermaid diagrams
**Usage:**
```bash
# Analyze a single file
python extract_concepts.py /path/to/file.py
# Analyze a directory
python extract_concepts.py /path/to/codebase
# Save output to file
python extract_concepts.py /path/to/codebase > ontology.json
```
**Output:**
- JSON ontology structure
- Mermaid diagram representation
### generate_ontology_diagram.py
Generates visual representations of ontologies in various formats.
**Features:**
- Supports multiple diagram formats (Mermaid, PlantUML, GraphViz DOT, JSON-LD)
- Customizable relationship symbols
- Semantic web compatibility (JSON-LD output)
- Styled diagrams with concept type differentiation
**Usage:**
```bash
# Generate all formats
python generate_ontology_diagram.py ontology.json
# Generate specific format
python generate_ontology_diagram.py ontology.json --format mermaid
# Specify output directory
python generate_ontology_diagram.py ontology.json --output ./diagrams
# Available formats: mermaid, plantuml, dot, json-ld, all
```
**Output Examples:**
Mermaid:
```bash
python generate_ontology_diagram.py ontology.json --format mermaid
# Creates: ontology_mermaid.md
```
PlantUML:
```bash
python generate_ontology_diagram.py ontology.json --format plantuml
# Creates: ontology_plantuml.puml
```
GraphViz DOT:
```bash
python generate_ontology_diagram.py ontology.json --format dot
# Creates: ontology.dot
```
JSON-LD:
```bash
python generate_ontology_diagram.py ontology.json --format json-ld
# Creates: ontology_jsonld.json
```
## Requirements
Both scripts use only Python standard library modules:
- `ast` - Python AST parsing
- `re` - Regular expressions
- `json` - JSON processing
- `pathlib` - Path handling
- `argparse` - Command-line argument parsing
No additional dependencies required!
## Example Workflow
```bash
# 1. Extract concepts from codebase
python extract_concepts.py /path/to/codebase > ontology.json
# 2. Generate diagrams
python generate_ontology_diagram.py ontology.json --output ./docs/diagrams
# 3. Review generated documentation
ls ./docs/diagrams/
# ontology_mermaid.md
# ontology_plantuml.puml
# ontology.dot
# ontology_jsonld.json
```
## Integration with Skill
These scripts support the main [SKILL.md](../SKILL.md) by providing automated tools for concept extraction and visualization. Use them to bootstrap your ontological documentation process.

View File

@@ -0,0 +1,259 @@
#!/usr/bin/env python3
"""
Concept Extraction Script for Ontological Documentation
This script analyzes codebases to extract domain concepts, entities, and relationships
for building ontological documentation. It supports multiple programming languages
and can identify inheritance hierarchies, composition patterns, and semantic relationships.
"""
import ast
import re
import json
import sys
from pathlib import Path
from typing import Dict, List, Set, Tuple, Any
from collections import defaultdict
class ConceptExtractor:
"""Extracts ontological concepts from source code."""
def __init__(self):
self.concepts = defaultdict(dict)
self.relationships = defaultdict(list)
self.taxonomies = defaultdict(list)
def extract_from_python(self, file_path: Path) -> Dict[str, Any]:
"""Extract concepts from Python source code."""
try:
with open(file_path, 'r', encoding='utf-8') as f:
tree = ast.parse(f.read())
visitor = ClassVisitor()
visitor.visit(tree)
return {
'classes': visitor.classes,
'inheritance': visitor.inheritance,
'imports': visitor.imports,
'functions': visitor.functions
}
except Exception as e:
return {'error': str(e)}
def extract_from_javascript(self, file_path: Path) -> Dict[str, Any]:
"""Extract concepts from JavaScript/TypeScript source code."""
concepts = {
'classes': [],
'interfaces': [],
'functions': [],
'imports': []
}
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# Extract class declarations
class_pattern = r'(?:class|interface)\s+(\w+)(?:\s+extends\s+(\w+))?'
for match in re.finditer(class_pattern, content):
class_name = match.group(1)
parent_class = match.group(2)
concepts['classes'].append({
'name': class_name,
'parent': parent_class,
'type': 'class' if 'class' in match.group(0) else 'interface'
})
# Extract function declarations
func_pattern = r'(?:function\s+(\w+)|const\s+(\w+)\s*=\s*(?:\([^)]*\)\s*)?=>|(\w+)\s*:\s*\([^)]*\)\s*=>)'
for match in re.finditer(func_pattern, content):
func_name = match.group(1) or match.group(2) or match.group(3)
if func_name:
concepts['functions'].append({'name': func_name})
# Extract imports
import_pattern = r'import\s+.*?from\s+["\']([^"\']+)["\']'
for match in re.finditer(import_pattern, content):
concepts['imports'].append({'source': match.group(1)})
except Exception as e:
concepts['error'] = str(e)
return concepts
def build_ontology(self, extracted_data: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Build ontological structure from extracted data."""
ontology = {
'concepts': {},
'relationships': {
'is_a': [], # inheritance
'part_of': [], # composition
'depends_on': [], # dependencies
'associates_with': [] # loose associations
},
'taxonomies': {}
}
all_classes = []
all_functions = []
all_imports = []
# Collect all entities
for data in extracted_data:
if 'classes' in data:
all_classes.extend(data['classes'])
if 'functions' in data:
all_functions.extend(data['functions'])
if 'imports' in data:
all_imports.extend(data['imports'])
# Build concepts
for cls in all_classes:
if isinstance(cls, dict):
concept_name = cls.get('name', str(cls))
ontology['concepts'][concept_name] = {
'type': 'class',
'properties': cls
}
# Build inheritance relationships
parent = cls.get('parent')
if parent:
ontology['relationships']['is_a'].append({
'subject': concept_name,
'object': parent
})
for func in all_functions:
if isinstance(func, dict):
func_name = func.get('name', str(func))
ontology['concepts'][func_name] = {
'type': 'function',
'properties': func
}
return ontology
def generate_mermaid_diagram(self, ontology: Dict[str, Any]) -> str:
"""Generate Mermaid diagram from ontology."""
lines = ["graph TD"]
# Add concepts as nodes
for concept_name, concept_data in ontology['concepts'].items():
concept_type = concept_data.get('type', 'concept')
if concept_type == 'class':
lines.append(f" {concept_name}[({concept_name})]")
else:
lines.append(f" {concept_name}[{concept_name}]")
# Add relationships
for rel_type, relationships in ontology['relationships'].items():
for rel in relationships:
subject = rel['subject']
obj = rel['object']
if rel_type == 'is_a':
lines.append(f" {subject} --|> {obj}")
elif rel_type == 'part_of':
lines.append(f" {subject} --* {obj}")
elif rel_type == 'depends_on':
lines.append(f" {subject} -.-> {obj}")
else:
lines.append(f" {subject} --- {obj}")
return "\n".join(lines)
class ClassVisitor(ast.NodeVisitor):
"""AST visitor for Python class analysis."""
def __init__(self):
self.classes = []
self.inheritance = []
self.imports = []
self.functions = []
def visit_ClassDef(self, node):
class_info = {
'name': node.name,
'bases': [base.id for base in node.bases if hasattr(base, 'id')],
'methods': [],
'line_number': node.lineno
}
for item in node.body:
if isinstance(item, ast.FunctionDef):
class_info['methods'].append({
'name': item.name,
'args': [arg.arg for arg in item.args.args],
'line_number': item.lineno
})
self.classes.append(class_info)
# Track inheritance
for base in node.bases:
if hasattr(base, 'id'):
self.inheritance.append({
'child': node.name,
'parent': base.id
})
self.generic_visit(node)
def visit_Import(self, node):
for alias in node.names:
self.imports.append({
'module': alias.name,
'alias': alias.asname
})
self.generic_visit(node)
def visit_FunctionDef(self, node):
func_info = {
'name': node.name,
'args': [arg.arg for arg in node.args.args],
'line_number': node.lineno
}
self.functions.append(func_info)
self.generic_visit(node)
def main():
"""Main function to run concept extraction."""
if len(sys.argv) < 2:
print("Usage: python extract_concepts.py <file_or_directory_path>")
sys.exit(1)
path = Path(sys.argv[1])
extractor = ConceptExtractor()
extracted_data = []
if path.is_file():
if path.suffix == '.py':
data = extractor.extract_from_python(path)
extracted_data.append(data)
elif path.suffix in ['.js', '.ts', '.jsx', '.tsx']:
data = extractor.extract_from_javascript(path)
extracted_data.append(data)
elif path.is_dir():
for file_path in path.rglob('*'):
if file_path.is_file():
if file_path.suffix == '.py':
data = extractor.extract_from_python(file_path)
extracted_data.append(data)
elif file_path.suffix in ['.js', '.ts', '.jsx', '.tsx']:
data = extractor.extract_from_javascript(file_path)
extracted_data.append(data)
ontology = extractor.build_ontology(extracted_data)
# Output as JSON
print(json.dumps(ontology, indent=2))
# Also generate Mermaid diagram
diagram = extractor.generate_mermaid_diagram(ontology)
print("\n--- Mermaid Diagram ---")
print(diagram)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,288 @@
#!/usr/bin/env python3
"""
Ontology Diagram Generator
This script generates visual representations of ontologies in various formats
including Mermaid, PlantUML, GraphViz DOT, and JSON-LD for semantic web applications.
"""
import json
import sys
import argparse
import re
from pathlib import Path
from typing import Dict, List, Any, Optional
class OntologyDiagramGenerator:
"""Generates diagrams for ontological documentation."""
def __init__(self):
self.relationship_symbols = {
'is_a': '--|>', # Inheritance
'part_of': '--*', # Composition
'depends_on': '-.->', # Dependency
'associates_with': '---', # Association
'instance_of': '..>' # Instantiation
}
def generate_mermaid(self, ontology: Dict[str, Any]) -> str:
"""Generate Mermaid diagram from ontology."""
lines = ["graph TD"]
lines.append(" %% Ontology Diagram")
lines.append(" %% Generated from ontological documentation")
# Add styling
lines.extend([
" classDef concept fill:#e1f5fe,stroke:#01579b,stroke-width:2px",
" classDef class fill:#f3e5f5,stroke:#4a148c,stroke-width:2px",
" classDef interface fill:#e8f5e8,stroke:#1b5e20,stroke-width:2px",
" classDef function fill:#fff3e0,stroke:#e65100,stroke-width:2px"
])
# Add concepts as nodes
concept_classes = {}
for concept_name, concept_data in ontology['concepts'].items():
concept_type = concept_data.get('type', 'concept')
if concept_type == 'class':
lines.append(f" {self._safe_name(concept_name)}[({concept_name})]")
concept_classes[concept_name] = 'class'
elif concept_type == 'interface':
lines.append(f" {self._safe_name(concept_name)}[{{interface}}{concept_name}]")
concept_classes[concept_name] = 'interface'
elif concept_type == 'function':
lines.append(f" {self._safe_name(concept_name)}[{concept_name}()]")
concept_classes[concept_name] = 'function'
else:
lines.append(f" {self._safe_name(concept_name)}[{concept_name}]")
concept_classes[concept_name] = 'concept'
# Add relationships
for rel_type, relationships in ontology['relationships'].items():
symbol = self.relationship_symbols.get(rel_type, '---')
for rel in relationships:
subject = self._safe_name(rel['subject'])
obj = self._safe_name(rel['object'])
label = rel.get('label', rel_type.replace('_', ' ').title())
lines.append(f" {subject} {symbol} {obj}")
# Apply classes
for concept_name, css_class in concept_classes.items():
lines.append(f" class {self._safe_name(concept_name)} {css_class}")
return "\n".join(lines)
def generate_plantuml(self, ontology: Dict[str, Any]) -> str:
"""Generate PlantUML diagram from ontology."""
lines = ["@startuml Ontology"]
lines.append("!theme plain")
lines.append("skinparam classAttributeIconSize 0")
# Add concepts as classes
for concept_name, concept_data in ontology['concepts'].items():
concept_type = concept_data.get('type', 'concept')
if concept_type == 'class':
lines.append(f"class {concept_name} {{}}")
elif concept_type == 'interface':
lines.append(f"interface {concept_name} {{}}")
elif concept_type == 'function':
lines.append(f"object {concept_name} {{}}")
else:
lines.append(f"abstract {concept_name} {{}}")
lines.append("") # Empty line for separation
# Add relationships
for rel_type, relationships in ontology['relationships'].items():
for rel in relationships:
subject = rel['subject']
obj = rel['object']
if rel_type == 'is_a':
lines.append(f"{subject} <|-- {obj}")
elif rel_type == 'part_of':
lines.append(f"{subject} *-- {obj}")
elif rel_type == 'depends_on':
lines.append(f"{subject} ..> {obj}")
else:
lines.append(f"{subject} -- {obj}")
lines.append("@enduml")
return "\n".join(lines)
def generate_dot(self, ontology: Dict[str, Any]) -> str:
"""Generate GraphViz DOT diagram from ontology."""
lines = ["digraph Ontology {"]
lines.append(' rankdir=TB;')
lines.append(' node [shape=box, style=filled];')
lines.append(' edge [fontsize=10];')
# Add concepts as nodes
for concept_name, concept_data in ontology['concepts'].items():
concept_type = concept_data.get('type', 'concept')
# Set colors based on type
if concept_type == 'class':
color = "lightpurple"
elif concept_type == 'interface':
color = "lightgreen"
elif concept_type == 'function':
color = "lightorange"
else:
color = "lightblue"
lines.append(f' "{concept_name}" [label="{concept_name}", fillcolor="{color}"];')
lines.append("") # Empty line for separation
# Add relationships
for rel_type, relationships in ontology['relationships'].items():
for rel in relationships:
subject = rel['subject']
obj = rel['object']
label = rel.get('label', rel_type.replace('_', ' ').title())
# Set arrow styles based on relationship type
if rel_type == 'is_a':
arrow = 'empty'
elif rel_type == 'part_of':
arrow = 'diamond'
elif rel_type == 'depends_on':
arrow = 'dashed'
else:
arrow = 'normal'
lines.append(f' "{subject}" -> "{obj}" [label="{label}", arrowhead={arrow}];')
lines.append("}")
return "\n".join(lines)
def generate_json_ld(self, ontology: Dict[str, Any]) -> Dict[str, Any]:
"""Generate JSON-LD representation of ontology."""
context = {
"@context": {
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"owl": "http://www.w3.org/2002/07/owl#",
"Concept": "rdfs:Class",
"subClassOf": {
"@id": "rdfs:subClassOf",
"@type": "@id"
},
"partOf": {
"@id": "http://example.org/ontology#partOf",
"@type": "@id"
},
"dependsOn": {
"@id": "http://example.org/ontology#dependsOn",
"@type": "@id"
}
},
"@graph": []
}
# Add concepts
for concept_name, concept_data in ontology['concepts'].items():
concept_entry = {
"@id": f"http://example.org/ontology#{concept_name}",
"@type": ["Concept"]
}
concept_type = concept_data.get('type', 'concept')
if concept_type == 'class':
concept_entry["@type"].append("owl:Class")
elif concept_type == 'interface':
concept_entry["@type"].append("owl:Class")
context["@graph"].append(concept_entry)
# Add relationships
for rel_type, relationships in ontology['relationships'].items():
for rel in relationships:
subject = rel['subject']
obj = rel['object']
if rel_type == 'is_a':
context["@graph"].append({
"@id": f"http://example.org/ontology#{subject}",
"subClassOf": f"http://example.org/ontology#{obj}"
})
elif rel_type == 'part_of':
context["@graph"].append({
"@id": f"http://example.org/ontology#{subject}",
"partOf": f"http://example.org/ontology#{obj}"
})
elif rel_type == 'depends_on':
context["@graph"].append({
"@id": f"http://example.org/ontology#{subject}",
"dependsOn": f"http://example.org/ontology#{obj}"
})
return context
def _safe_name(self, name: str) -> str:
"""Convert name to safe identifier for diagram formats."""
# Replace special characters and spaces with underscores
return re.sub(r'[^a-zA-Z0-9_]', '_', name)
def load_ontology(file_path: Path) -> Dict[str, Any]:
"""Load ontology from JSON file."""
with open(file_path, 'r', encoding='utf-8') as f:
return json.load(f)
def main():
"""Main function to generate diagrams."""
parser = argparse.ArgumentParser(description='Generate ontology diagrams')
parser.add_argument('ontology_file', help='Path to ontology JSON file')
parser.add_argument('--format', choices=['mermaid', 'plantuml', 'dot', 'json-ld', 'all'],
default='all', help='Diagram format to generate')
parser.add_argument('--output', help='Output directory (default: current directory)')
args = parser.parse_args()
ontology_path = Path(args.ontology_file)
if not ontology_path.exists():
print(f"Error: Ontology file '{ontology_path}' not found")
sys.exit(1)
ontology = load_ontology(ontology_path)
generator = OntologyDiagramGenerator()
output_dir = Path(args.output) if args.output else Path('.')
output_dir.mkdir(exist_ok=True)
formats_to_generate = ['mermaid', 'plantuml', 'dot', 'json-ld'] if args.format == 'all' else [args.format]
for format_type in formats_to_generate:
if format_type == 'mermaid':
diagram = generator.generate_mermaid(ontology)
output_file = output_dir / f"{ontology_path.stem}_mermaid.md"
with open(output_file, 'w', encoding='utf-8') as f:
f.write(f"# {ontology_path.stem} Ontology Diagram\n\n")
f.write("```mermaid\n")
f.write(diagram)
f.write("\n```")
print(f"Generated Mermaid diagram: {output_file}")
elif format_type == 'plantuml':
diagram = generator.generate_plantuml(ontology)
output_file = output_dir / f"{ontology_path.stem}_plantuml.puml"
with open(output_file, 'w', encoding='utf-8') as f:
f.write(diagram)
print(f"Generated PlantUML diagram: {output_file}")
elif format_type == 'dot':
diagram = generator.generate_dot(ontology)
output_file = output_dir / f"{ontology_path.stem}.dot"
with open(output_file, 'w', encoding='utf-8') as f:
f.write(diagram)
print(f"Generated GraphViz DOT diagram: {output_file}")
elif format_type == 'json-ld':
json_ld = generator.generate_json_ld(ontology)
output_file = output_dir / f"{ontology_path.stem}_jsonld.json"
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(json_ld, f, indent=2)
print(f"Generated JSON-LD: {output_file}")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,79 @@
# Assets
This directory contains examples and templates for ontological documentation.
## Directory Structure
```
assets/
├── examples/ # Real-world examples
│ └── ecommerce-ontology.md
└── ontology-templates/ # Reusable templates
└── domain-ontology.md
```
## Examples
### ecommerce-ontology.md
A complete example demonstrating ontological documentation for an e-commerce system.
**Includes:**
- Core concept hierarchy
- Entity relationships
- Business rules
- Implementation examples
- Documentation structure
**Use this example to:**
- Understand how to structure domain ontologies
- Learn relationship documentation patterns
- See practical implementation examples
- Get inspiration for your own domain models
## Templates
### domain-ontology.md
A ready-to-use template for documenting domain ontologies.
**Features:**
- Pre-structured sections
- Placeholder content
- Usage instructions
- Hierarchical concept organization
**How to use:**
1. Copy the template to your project
2. Replace placeholders with your domain information
3. Fill in the concept hierarchy
4. Document relationships
5. Add implementation details
## Creating Your Own Ontology
1. **Start with the template**: Copy `ontology-templates/domain-ontology.md`
2. **Review the example**: Study `examples/ecommerce-ontology.md` for structure
3. **Extract concepts**: Use `scripts/extract_concepts.py` on your codebase
4. **Document relationships**: Apply patterns from `references/ontology_patterns.md`
5. **Use standard templates**: Reference `references/documentation_templates.md`
6. **Generate diagrams**: Use `scripts/generate_ontology_diagram.py`
## Adding New Examples
When adding new examples:
1. Follow the structure shown in `ecommerce-ontology.md`
2. Include concept hierarchies
3. Document key relationships
4. Provide business rules
5. Add implementation examples
6. Link to related documentation
## Adding New Templates
When creating new templates:
1. Use placeholder syntax: `[Placeholder Name]`
2. Include usage instructions
3. Provide inline comments
4. Keep structure clear and minimal
5. Add to this README with description

View File

@@ -0,0 +1,35 @@
# Domain Ontology Template
## Overview
This template provides a structured approach to documenting domain ontologies for software systems.
## Domain: [Domain Name]
### Core Concepts
<!-- List the main domain concepts -->
```
[Domain Name]
├── Primary Entities
│ ├── Entity 1
│ ├── Entity 2
│ └── Entity 3
├── Value Objects
│ ├── Value Object 1
│ └── Value Object 2
├── Services
│ ├── Service 1
│ └── Service 2
└── Repositories
├── Repository 1
└── Repository 2
```
### Relationships
<!-- Document key relationships between concepts -->
## Usage Instructions
1. Replace [Domain Name] with your actual domain
2. Fill in the core concepts hierarchy
3. Document the relationships
4. Add specific concept details using the concept template