Skip to content

Latest commit

 

History

History
562 lines (447 loc) · 16 KB

File metadata and controls

562 lines (447 loc) · 16 KB

Cognitio Project Conventions

Last Updated: 2026-02-16 Purpose: Define naming, coding, and organizational standards for consistent development


📁 Folder Naming Conventions

Root-Level Folders

Use numeric prefixes + PascalCase for organizational clarity:

00_Admin/              # Project management, licenses
01_Documentation/      # All markdown docs, research PDFs
02_Bewerbungen/       # Internship applications (German context)
03_Archive/           # Historical/legacy content
04_UnityProjects/     # All Unity projects
.planning/            # GSD workflow system

Unity Project Structure

Follow Unity's standard conventions:

Assets/
├── Scenes/           # Unity scene files (.unity)
├── Scripts/          # All C# code
│   ├── Core/        # Runtime systems
│   └── Editor/      # Editor extensions
├── ScriptableObjects/  # SO instances organized by type
├── Prefabs/         # Reusable game objects
├── GameObjects/     # Scene-specific objects
├── Materials/       # Shaders, materials
└── Resources/       # Runtime-loaded assets

Rule: Never place scripts outside Assets/Scripts/ to maintain discoverability.


📝 File Naming Conventions

Markdown Documentation

Type Convention Example
Core Docs UPPERCASE.md PROJECT.md, ROADMAP.md, STATE.md
Supporting Docs PascalCase.md CodebaseAnalysis.md, DesignFoundation.md
Phase Plans NN-NN-PLAN.md 01-01-PLAN.md, 02-03-PLAN.md
Phase Summaries NN-NN-SUMMARY.md 01-01-SUMMARY.md
Verification NN-VERIFICATION.md 01-VERIFICATION.md
Todos YYYY-MM-DD-description.md 2026-02-13-bug-add-trait-creates-all-under-social.md

C# Code Files

Type Convention Example
Classes PascalCase.cs TraitDefinition.cs, CharacterProfile.cs
Interfaces IPascalCase.cs IInteractionMatrix.cs
Enums PascalCase.cs TraitCategory.cs, MotivationType.cs
Editor Scripts ClassNameEditor.cs CharacterProfileEditor.cs
Property Drawers PropertyNameDrawer.cs TraitEntryDrawer.cs

Rule: One primary type per file, file name matches type name.

ScriptableObject Assets

Type Convention Example
Trait Definitions [Name]Trait.asset CompassionTrait.asset, CourageTrait.asset
Character Profiles [Name]Profile.asset TaoProfile.asset, HeroProfile.asset
Motivation Definitions [Name]Motivation.asset SurvivalMotivation.asset
Action Definitions [Name]Action.asset FleeAction.asset, ConsolidateAction.asset

Rule: Use descriptive names that indicate type and purpose.


🔤 Code Style Conventions

C# Naming

// Classes, structs, enums: PascalCase
public class CharacterProfile { }
public struct TraitEntry { }
public enum TraitCategory { }

// Public properties: PascalCase
public float Value { get; private set; }

// Private fields: camelCase with [SerializeField] for Unity inspector
[SerializeField] private TraitDefinition definition;
private float currentValue;

// Methods: PascalCase
public void UpdateTraitValue(float newValue) { }

// Constants: PascalCase
public const float MinValue = 0.0f;
public const float MaxValue = 1.0f;

// Parameters: camelCase
public ActionScore Evaluate(RuntimeCharacterData character, ContextParameters context) { }

Immutability Patterns

ScriptableObjects: Always immutable configuration

[CreateAssetMenu(fileName = "NewTrait", menuName = "Cognitio/Trait Definition")]
public class TraitDefinition : ScriptableObject
{
    [SerializeField] private string displayName;
    [SerializeField] private TraitCategory category;

    public string DisplayName => displayName; // Read-only property
    public TraitCategory Category => category;
}

Runtime Data: Mutable state in separate classes

public class RuntimeCharacterData
{
    private Dictionary<TraitDefinition, float> runtimeValues;

    public void SetTraitValue(TraitDefinition trait, float value)
    {
        // Mutable state modifications here
    }
}

Struct Immutability

Use with expressions (C# 10) or factory methods:

public readonly struct TraitEntry
{
    public TraitDefinition Definition { get; init; }
    public float Value { get; init; }

    public TraitEntry WithValue(float newValue) => new TraitEntry
    {
        Definition = this.Definition,
        Value = Mathf.Clamp01(newValue)
    };
}

⚡ Performance Conventions

Zero-Allocation Patterns

Avoid:

// LINQ allocates enumerators
var result = actions.Where(a => a.IsValid).OrderBy(a => a.Score).First();

// List.Add() can trigger resizing allocations
var scores = new List<ActionScore>();
foreach (var action in actions) scores.Add(EvaluateAction(action));

Prefer:

// Pre-allocated arrays, manual loops
ActionScore[] scores = new ActionScore[actions.Length];
for (int i = 0; i < actions.Length; i++)
{
    scores[i] = EvaluateAction(actions[i]);
}

// Pooled result containers
DecisionResult result = DecisionResult.GetPooled();
result.Clear();
result.AddScores(scores);

Hot Path Rules

  1. No LINQ in Update/FixedUpdate - Use for loops
  2. No string concatenation in loops - Use StringBuilder or log batch
  3. Cache component references - Don't call GetComponent<T>() every frame
  4. Use structs for small data - Avoid class overhead (<16 bytes)
  5. Pool reusable objects - Especially DecisionResult, log entries

🧪 Testing Conventions

Test Naming

// Pattern: MethodName_Scenario_ExpectedBehavior
[Test]
public void GetTraitValue_WhenTraitExists_ReturnsCorrectValue() { }

[Test]
public void SetTraitValue_WhenValueOutOfRange_ClampsToValidRange() { }

[Test]
public void EvaluateAction_WithHighMoralAlignment_PrioritizesMoralAction() { }

Test Organization

Assets/
└── Scripts/
    └── Tests/
        ├── EditMode/     # Edit mode tests (no Play mode required)
        │   ├── TraitSystemTests.cs
        │   └── DecisionEngineTests.cs
        └── PlayMode/     # Play mode tests (require Unity runtime)
            ├── CharacterIntegrationTests.cs
            └── PerformanceTests.cs

📐 Editor UI Conventions

Spacing & Layout

Use CognitionEditorConstants for consistent spacing:

// 4px base grid
EditorGUILayout.Space(CognitionEditorConstants.SpacingXS);  // 4px
EditorGUILayout.Space(CognitionEditorConstants.SpacingS);   // 8px
EditorGUILayout.Space(CognitionEditorConstants.SpacingM);   // 12px
EditorGUILayout.Space(CognitionEditorConstants.SpacingL);   // 16px
EditorGUILayout.Space(CognitionEditorConstants.SpacingXL);  // 24px
EditorGUILayout.Space(CognitionEditorConstants.SpacingXXL); // 32px

Theme-Aware Colors

// Always check theme before using colors
Color backgroundColor = EditorGUIUtility.isProSkin
    ? CognitionEditorConstants.DarkTheme.Background
    : CognitionEditorConstants.LightTheme.Background;

Progressive Disclosure Hierarchy

  1. Level 1: Category foldouts (Emotional, Social, Cognitive, Moral)
  2. Level 2: Individual trait rows (Compassion, Courage, etc.)
  3. Level 3: Trait details on hover (tooltips)
  4. Level 4: Advanced settings (only if > 3 traits in category)

🗂️ Git Workflow Conventions

Branch Strategy

Main Branch Only (solo developer)

  • All work committed directly to main
  • Feature branches optional for experimental work
  • Use semantic commits for clarity

Commit Message Format

<type>(<scope>): <subject>

<optional body>

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

Types:

  • feat - New feature (Phase work, new system)
  • fix - Bug fix (BUG-001, BUG-002 fixes)
  • docs - Documentation only (README, markdown updates)
  • refactor - Code restructuring (no behavior change)
  • test - Adding/updating tests
  • chore - Maintenance (dependencies, config)
  • perf - Performance improvement

Examples:

feat(02-01): create decision engine type foundation

Implemented MotivationDefinition, MotivationEntry, GoalDefinition,
ContextParameters, ActionDefinition, ActionScore, and DecisionResult.

All types use zero-allocation patterns and immutable ScriptableObjects
for configuration.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
fix(trait-editor): add trait creates all under social category

Fixed bug where TraitCategory dropdown was not being saved correctly.
Now properly assigns selected category to new TraitDefinition.

Resolves: BUG-001

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

When to Commit

Atomic Commits: Each commit should represent one logical change

  • ✅ Complete Phase plan implementation (e.g., 01-01 complete)
  • ✅ Bug fix (one bug per commit)
  • ✅ Documentation update (one topic per commit)
  • ❌ "Work in progress" commits
  • ❌ Mixing multiple unrelated changes

What NOT to Commit

  • Unity Library/ folder (1.1GB+ generated files)
  • Temp/, Logs/, obj/, Builds/ folders
  • IDE files (.vs/, .idea/, *.csproj, *.sln)
  • OS files (.DS_Store, Thumbs.db)
  • Credentials, API keys, .env files

All exclusions managed via .gitignore


📚 Documentation Conventions

Markdown Formatting

Headers:

# H1: Document Title (one per file)
## H2: Major Sections
### H3: Subsections
#### H4: Detailed Topics

Code Blocks:

```csharp
// Always specify language for syntax highlighting
public class Example { }

**Tables:**
```markdown
| Column 1 | Column 2 | Column 3 |
|----------|----------|----------|
| Data     | Data     | Data     |

Links:

[Relative link](../path/to/file.md)
[Absolute link](https://example.com)

Documentation Structure

Every major document should include:

  1. Title + metadata (date, status)
  2. Quick summary (2-3 sentences)
  3. Table of contents (if > 500 lines)
  4. Sections with clear headers
  5. Examples (code snippets, ASCII diagrams)
  6. Version history (if updated multiple times)

ASCII Wireframes (Phase 1.1 Standard)

┌────────────────────────────────────┐
│  Category: Emotional          [▼]  │
├────────────────────────────────────┤
│  ⚫ Compassion         [====·····]  │
│  ⚫ Anxiety            [··====···]  │
│                                     │
│  [+ Add Trait]  [- Remove Trait]   │
└────────────────────────────────────┘

Benefits:

  • Version-control friendly (text diff)
  • Platform-independent (no design tools)
  • Fast iteration (text editor)
  • Inclusive (ASCII readable by screen readers)

🔍 Research Citation Conventions

Neuroscience References

When citing research in code comments or documentation:

// OCC Appraisal Model (Ortony, Clore, Collins, 1988)
// - Desirability: Does this event/action align with goals?
// - Praiseworthiness: Does it align with moral standards?
// - Appealingness: Does it satisfy motivations?
public struct EmotionalAppraisal
{
    public float Desirability;      // Goal alignment (-1 to 1)
    public float Praiseworthiness;  // Moral alignment (-1 to 1)
    public float Appealingness;     // Motivation fulfillment (0 to 1)
}

Research Document Structure

Located in .planning/research/neuroscience/:

  1. Theory Introduction - Foundational concepts
  2. Neural Mechanisms - Brain regions, pathways
  3. Computational Models - How to implement in code
  4. References - Academic papers cited
  5. Implementation Notes - Cognitio-specific decisions

🎯 Architectural Principles

Separation of Concerns

Configuration (Immutable)
    ↓
ScriptableObjects (TraitDefinition, ActionDefinition, etc.)
    ↓
Runtime State (Mutable)
    ↓
C# Classes (RuntimeCharacterData, DecisionResult, etc.)

Rule: ScriptableObjects = designer-friendly data, never runtime mutation.

Dependency Flow

Core Systems (Traits, Motivations)
    ↓
Decision Engine (Appraisal, Evaluation, Scoring)
    ↓
Personality Integration (Emotions, Relationships)
    ↓
Unity Integration (GameObjects, Prefabs, Scenes)

Rule: Higher layers depend on lower layers, never reverse.

Interface Contracts

// Define abstract behavior, allow multiple implementations
public interface IInteractionMatrix
{
    void Evaluate(
        RuntimeCharacterData character,
        ActionDefinition[] actions,
        ContextParameters context,
        DecisionResult result
    );
}

// Implementations:
// - WeightedSumMatrix (Phase 2)
// - UtilityMatrix (Phase 3)
// - NeuralNetworkMatrix (Phase 7 - future)

Rule: Program to interfaces for future extensibility.


⚙️ Configuration Conventions

ScriptableObject Menu Paths

[CreateAssetMenu(
    fileName = "NewTrait",
    menuName = "Cognitio/Trait Definition",
    order = 1
)]

Hierarchy:

Cognitio/
├── Trait Definition          (order 1)
├── Character Profile         (order 2)
├── Motivation Definition     (order 10)
├── Goal Definition           (order 11)
├── Action Definition         (order 20)
└── Interaction Matrix Config (order 30)

Rule: Use numeric order to control menu grouping.

Inspector Tooltips

[Tooltip("The base priority for this motivation (0-10). Higher values are evaluated first.")]
[Range(0, 10)]
public int DefaultPriority = 5;

Rule: Every [SerializeField] should have a [Tooltip] explaining its purpose.


🧹 Maintenance Conventions

Updating This Document

  1. When to update:

    • New file type introduced (e.g., .prefab naming)
    • Architectural pattern changed (e.g., pooling strategy)
    • Coding standard clarified (e.g., null-check policy)
  2. How to update:

    • Add new section or update existing section
    • Include examples (code snippets, before/after)
    • Update "Last Updated" date at top
    • Commit with message: docs(conventions): add section on [topic]
  3. Who updates:

    • Primary developer (you)
    • Claude Code (when suggesting new patterns)

Referencing This Document

In code comments:

// See CONVENTIONS.md: "Zero-Allocation Patterns"
ActionScore[] scores = ArrayPool<ActionScore>.Rent(maxActions);

In pull request descriptions (future):

This PR follows the conventions in CONVENTIONS.md:
- Zero-allocation loops (Performance section)
- ScriptableObject immutability (Immutability Patterns section)

📋 Quick Reference

Most Common Patterns

Creating a new ScriptableObject type:

  1. Create C# class inheriting ScriptableObject
  2. Add [CreateAssetMenu] attribute
  3. Use [SerializeField] private fields + public properties
  4. Add [Tooltip] to all fields
  5. Test in Unity Inspector

Creating a new runtime system:

  1. Define interface (e.g., IEmotionalState)
  2. Implement concrete class (e.g., EmotionalStateSystem)
  3. Use zero-allocation patterns (pre-allocated arrays)
  4. Add unit tests (EditMode tests first)
  5. Document in .planning/research/

Adding a new Phase plan:

  1. Create NN-0M-PLAN.md in .planning/phases/[phase-name]/
  2. Implement code changes
  3. Verify all deliverables (checklist in plan)
  4. Create NN-0M-SUMMARY.md with commit SHAs
  5. Update STATE.md and ROADMAP.md

🔗 Related Documents


This document is a living standard. Update it as conventions evolve.