references/architecture_decision_record.md
# Architecture Decision Record (ADR) Template
## Title
[Short noun phrase, e.g., "Use Zod for Runtime Validation"]
## Status
[Proposed | Accepted | Deprecated | Superseded]
## Context
What is the issue that we're seeing that is motivating this decision or change?
* Problem statement...
* Constraints...
* Existing solution shortcomings...
## Decision
What is the change that we're proposing and/or doing?
* We will use [Technology/Pattern]...
* Because [Justification]...
## Consequences
What becomes easier or more difficult to do because of this change?
* **Positive:** [e.g., Improved type safety, automatic docs]
* **Negative:** [e.g., Runtime performance cost, bundle size increase]
* **Risks:** [e.g., Learning curve]
## Compliance
How will we ensure this decision is followed?
* [e.g., Lint rule, CI check, Code Review Checklist]
references/code_review_checklist.md
# 20-Point Code Review Checklist
Usage: Run through this list before marking any task as "Done".
## I. Correctness & Reliability
1. [ ] **Logic:** Does the code actually do what the requirements say?
2. [ ] **Edge Cases:** Are `null`, `undefined`, empty arrays, and negative numbers handled?
3. [ ] **Error Handling:** Are errors caught? Are they meaningful? (No `console.log(error)`)
4. [ ] **Concurrency:** Are `await` calls necessary? Are there race conditions?
5. [ ] ** Determinism:** Is GenAI output validated by a Zod schema?
## II. Type Safety (TypeScript)
6. [ ] **No `any`:** Are there any `any` types? (Strictly forbidden).
7. [ ] **Return Types:** Do exported functions have explicit return types?
8. [ ] **Strictness:** Are optional parameters (`?`) actually handled?
9. [ ] **Generics:** Are generics used appropriately to avoid repetition?
## III. Security
10. [ ] **Inputs:** Is user input validated/sanitized?
11. [ ] **Secrets:** Are there any hardcoded keys/passwords? (Check `.env` usage).
12. [ ] **Authorization:** Does the user have permission to perform this action?
## IV. Performance
13. [ ] **loops:** Are there O(n^2) nested loops on potentially large datasets?
14. [ ] **Re-renders:** (React) Are `useMemo` / `useCallback` used where props change often?
15. [ ] **I/O:** Are database/API calls batched where possible?
## V. Maintainability
16. [ ] **Naming:** Do variables reveal intent? (`isLoading` vs `flag`)
17. [ ] **Complexity:** Is any single function > 50 lines?
18. [ ] **DRY:** Is code duplicated?
19. [ ] **Comments:** Do comments explain *why*, not *what*?
20. [ ] **Tests:** Is there a corresponding unit test or manual verification step?
references/testing_strategy.md
# Testing Strategy Guide
## Philosophy: The Testing Pyramid
We strictly adhere to the Pyramid model. We do not write E2E tests for everything.
### 1. Unit Tests (70%)
* **What:** Test individual functions, classes, and logic blocks in isolation.
* **Where:** `src/tests/unit/` or co-located `__tests__`.
* **Mocking:** Heavy mocking of external dependencies (Databases, APIs, GenAI).
* **Speed:** Must run in < 10ms per test.
### 2. Integration Tests (20%)
* **What:** Test the interaction between two modules (e.g., Service Layer + Database).
* **Where:** `src/tests/integration/`.
* **Mocking:** Minimal. Use Test Containers or local emulators.
* **Speed:** < 500ms per test.
### 3. E2E / AI Flow Tests (10%)
* **What:** Test the full user journey or full AI pipeline.
* **Where:** `src/tests/e2e/`.
* **Mocking:** None. Use real (sandbox) environment.
* **Cost:** Expensive. Run only on pre-push or CI.
## Testing GenAI Code
Testing probabilistic code requires specific strategies:
1. **Deterministic Scaffolding:**
* Test the *logic around* the AI, not the AI itself.
* Mock the AI response to test:
* Schema validation success.
* Schema validation failure (malformed JSON).
* Network timeout.
2. **Golden Datasets:**
* Maintain a set of "Correct" inputs and "Acceptable" outputs.
* Use cosine similarity checks (if available) or keyword presence matching.
3. **Snapshot Testing:**
* Use snapshots for prompt templates to ensure no accidental prompt drift.
scripts/complexity_check.py
#!/usr/bin/env python3
"""
Complexity Check Script
A simple analyzer to warn about overly complex functions/files.
Usage: python scripts/complexity_check.py path/to/source_file.ts
"""
import sys
import os
import re
THRESHOLD_LINES = 50
THRESHOLD_IFS = 5
def analyze_file(filepath):
with open(filepath, 'r') as f:
lines = f.readlines()
total_lines = len(lines)
# Simple heuristics
if_count = sum(1 for line in lines if "if (" in line or "if(" in line)
loop_count = sum(1 for line in lines if "for (" in line or "while (" in line)
print(f"📊 Analysis for: {filepath}")
print(f" Total Lines: {total_lines}")
print(f" 'if' statements: {if_count}")
print(f" Loops: {loop_count}")
issues = []
if total_lines > 200:
issues.append(f"❌ File is too long ({total_lines} lines). Consider splitting.")
if if_count > THRESHOLD_IFS * 2:
issues.append(f"⚠️ High branching complexity ({if_count} conditionals).")
# Check for functions > 50 lines (Rough heuristic: indent level 0 or 1 function start to end)
# This is hard to do accurately with regex, so we'll just check max indentation depth
max_indent = 0
for line in lines:
stripped = line.lstrip()
# Ignore comments
if not stripped or stripped.startswith('//') or stripped.startswith('*'):
continue
# REACT/JSX EXCEPTION: Ignore lines starting with < or ending with > or />
# (Layout nesting is not Logic nesting)
if stripped.startswith('<') or stripped.endswith('>') or stripped.endswith('/>'):
continue
# Ignore closing syntax lines like " )} " or " ]" or " });"
if all(c in ")}];), " for c in stripped):
continue
if stripped.startswith(')') or stripped.startswith('}') or stripped.startswith(']'):
continue
indent = len(line) - len(stripped)
if indent > max_indent:
max_indent = indent
# React often has deep visual nesting (Provider > Layout > Component > Map > Div)
# So we allow 12 levels (24 spaces) for .tsx, vs 8 levels (16 spaces) for logic.
limit = 24 if filepath.endswith('.tsx') else 16
if max_indent > limit:
issues.append(f"❌ Excessive nesting detected (> {limit//2} levels). Refactor immediately.")
if not issues:
print("\n✅ Code Hygiene Check Passed.")
else:
print("\n🚨 Issues Found:")
for issue in issues:
print(issue)
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python scripts/complexity_check.py <file>")
sys.exit(1)
analyze_file(sys.argv[1])
scripts/scaffold_test.py
#!/usr/bin/env python3
"""
Scaffold Test Script
Generates a basic test file for a given input file.
Usage: python scripts/scaffold_test.py path/to/source_file.ts
"""
import sys
import os
from pathlib import Path
def generate_test_content(filename, name):
return f"""import {{ describe, it, expect }} from 'vitest';
import {{ {name} }} from '../{filename}';
describe('{name}', () => {{
it('should be defined', () => {{
expect({name}).toBeDefined();
}});
it('should handle null inputs gracefully', () => {{
// TODO: Implement null check test
// expect({name}(null)).toBe(...);
}});
it('should return valid output schema', () => {{
// TODO: Implement schema validation test
}});
}});
"""
def main():
if len(sys.argv) < 2:
print("Usage: python scripts/scaffold_test.py <source_file>")
sys.exit(1)
source_path = Path(sys.argv[1])
if not source_path.exists():
print(f"Error: File {source_path} not found.")
sys.exit(1)
# Simple heuristic to guess the main export name based on filename
# e.g., "lesson-plan-generator.ts" -> "lessonPlanGenerator"
name_parts = source_path.stem.split('-')
func_name = name_parts[0] + ''.join(x.title() for x in name_parts[1:])
# Determine test path
# src/ai/flows/foo.ts -> src/ai/flows/__tests__/foo.test.ts
test_dir = source_path.parent / "__tests__"
test_path = test_dir / f"{source_path.stem}.test.ts"
if test_path.exists():
print(f"Warning: Test file {test_path} already exists. Skipping.")
sys.exit(0)
# Create directory if needed
test_dir.mkdir(exist_ok=True)
# Write file
content = generate_test_content(source_path.name, func_name)
with open(test_path, 'w') as f:
f.write(content)
print(f"✅ Created test scaffold: {test_path}")
print(f" Target Function: {func_name}")
if __name__ == "__main__":
main()
SKILL.md
---
name: senior-software-engineer
description: Acts as a Senior Staff Engineer to enforce high-quality software development standards. Use this skill when the user asks for code implementation, architectural review, debugging, or technical design. It ensures all code is production-ready, typed, and architecturally sound.
license: Private - SahayakAI Internal
---
# Senior Software Engineer Skill (Expert Level)
This skill transforms the agent into a "Senior Staff Engineer" who prioritizes **Architecture, Reliability, and Maintainability** over speed or shortcuts. It enforces a rigorous, phased engineering workflow.
## Core Philosophy: The "Business Serious" Standard
> "We do not write code that 'just works'. We write code that endures, scales, and is easily understood by the next engineer."
### 1. Architecture Before Code (The Golden Rule)
* **Never** start coding without a mental or written blueprint.
* **Identify Boundaries:** Clearly separate Logic (Business Rules), Data (Schema), and Presentation (UI).
* **Check Dependencies:** Verifying existing patterns before inventing new ones.
### 2. The Implementation Standard
When writing code (TypeScript/Python/etc.), you MANDATORY follow these rules:
#### A. Type Safety is Non-Negotiable
* **No `any`**: Explicitly define interfaces and types (e.g., Zod schemas).
* **Strict Null Checks**: Always handle `null` and `undefined` explicitly. DO NOT assume data exists.
* **Return Types**: Explicitly type function returns.
#### B. Deterministic Reliability
* **Wrap the Probability**: When using LLMs (GenAI), always wrap the call in a `try/catch` block with fallback logic.
* **Validate Inputs/Outputs**: Use Zod or similar libraries to validate API inputs and GenAI outputs at runtime.
* **Error Handling**: Throw specific, descriptive errors (e.g., `LessonPlanGenerationError`) rather than generic ones.
## Phased Engineering Workflow
Follow this strict cycle for any major implementation task:
### Phase 1: Design & Plan
Before writing a single line of logic:
1. **Check References**: Are there existing patterns?
* *See `/Users/sargupta/SahayakAIV2/sahayakai/sahayakai-main/.agent/skills/senior-software-engineer/references/architecture_decision_record.md`* if making a major structural choice.
2. **Define Schema**: What does the data look like? (Interface/Zod)
3. **Plan the Test**: How will we know it works? (Unit vs E2E)
* *See `/Users/sargupta/SahayakAIV2/sahayakai/sahayakai-main/.agent/skills/senior-software-engineer/references/testing_strategy.md`* for guidance.
### Phase 2: Implementation
1. **Scaffold**: Create the file structure.
* *Tip:* Use `/Users/sargupta/SahayakAIV2/sahayakai/sahayakai-main/.agent/skills/senior-software-engineer/scripts/scaffold_test.py` to auto-generate a matching test file.
2. **Logic Separation**: Keep business logic out of UI components.
3. **Cyclomatic Check**: Keep complexity low.
* *Tip:* Run `/Users/sargupta/SahayakAIV2/sahayakai/sahayakai-main/.agent/skills/senior-software-engineer/scripts/complexity_check.py` on your new file.
### Phase 3: Review & Refine
Before declaring "Done":
1. **Audit**: Run against the 20-point checklist.
* *See `/Users/sargupta/SahayakAIV2/sahayakai/sahayakai-main/.agent/skills/senior-software-engineer/references/code_review_checklist.md`*.
2. **Type Check**: Ensure no red squiggles.
## Bundled Resources
### References (`/Users/sargupta/SahayakAIV2/sahayakai/sahayakai-main/.agent/skills/senior-software-engineer/references/`)
* **`architecture_decision_record.md`**: Template for logging strict architectural choices (ADR).
* **`code_review_checklist.md`**: 20-point audit for Security, Perf, and Types.
* **`testing_strategy.md`**: Guide on Unit vs E2E testing hierarchies.
### Scripts (`/Users/sargupta/SahayakAIV2/sahayakai/sahayakai-main/.agent/skills/senior-software-engineer/scripts/`)
* **`scaffold_test.py`**: Auto-generates a basic test file for a given input file.
* **`complexity_check.py`**: Simple cyclomatic complexity analyzer to prevent spaghetti code.
## When to use this Skill
Trigger this skill for:
* "Write a function to..."
* "Refactor this component..."
* "Debug this error..."
* "Review my code for..."
* Any request involving editing `src/` files.