Convert gitgram/ and aitimemachine/ from embedded git repos (which showed as opaque submodule gitlinks on GitHub) into fully-tracked first-party content. AITM now merges its 7 vendored repos as first-party engines: - memory: beads (Go task DAG) + context7 (docs SDK), unified into saved_contexts - git: vendored C git (bundled binary) + gitnexus (in-process code intelligence) - agentic: a2a (@a2a-js/sdk) + pal (AITM-managed Python subprocess) Includes the full session's product build: Gitgram web/mobile/backend features, AITM website/CLI/MCP, the unified memory layer, engine build tooling (scripts/build-engines.sh, Dockerfile, CI), docs (README, ENGINES.md, ARCHITECTURE.md), and extensive test suites. Build artifacts, node_modules, external/, and gemini-cli are gitignored. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
27 KiB
Contributing to repo2txt
Thank you for your interest in contributing! This document provides comprehensive guidance on the project architecture, design patterns, and development workflow.
π Table of Contents
- Getting Started
- Architecture Overview
- Design Patterns
- Project Structure
- Development Workflow
- Testing Strategy
- Code Style
- Pull Request Process
π Getting Started
Prerequisites
- Node.js 20+ (LTS recommended)
- npm 10+
- Git
- A code editor (VS Code recommended)
Initial Setup
# Fork the repository on GitHub
# Clone your fork
git clone https://github.com/YOUR_USERNAME/repo2txt.git
cd repo2txt
# Add upstream remote
git remote add upstream https://github.com/abinthomasonline/repo2txt.git
# Install dependencies
npm install
# Copy test configuration template
cp tests/test-config.example.ts tests/test-config.ts
# Add your GitHub token to test-config.ts (optional, for E2E tests)
# Start development server
npm run dev
Development Commands
# Development
npm run dev # Start dev server (http://localhost:5173/repo2txt/)
npm run build # Production build
npm run preview # Preview production build
# Testing
npm run test:unit # Run unit tests
npm run test:e2e # Run E2E tests
npm run test:watch # Watch mode for unit tests
npm run test:coverage # Generate coverage report
# Code Quality
npm run typecheck # TypeScript type checking
npm run lint # Lint code
npm run lint:fix # Auto-fix linting issues
npm run format # Format code with Prettier
npm run format:check # Check formatting
# CI Pipeline (runs all checks)
npm run ci # typecheck + lint + test:unit
ποΈ Architecture Overview
Core Design Principles
- Provider Pattern - Unified interface for multiple data sources
- Separation of Concerns - Clear boundaries between UI, business logic, and data
- Type Safety - TypeScript everywhere with strict mode
- Performance First - Virtual scrolling, code splitting, Web Workers
- Privacy First - All processing happens in the browser
System Architecture
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β React App β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β βββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β UI β β Store β β Workers β β
β β Components ββββ€ (Zustand) ββββ€ (Tokenizer) β β
β βββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β² β² β
β β β β
β βΌ βΌ β
β βββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Provider Interface β β
β β (BaseProvider - Abstract Base Class) β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β² β² β² β² β
β β β β β β
β ββββββ΄ββββ¬βββββ΄βββββ¬ββββββ΄ββββββ¬βββββ΄βββββ β
β β GitHub β Local β GitLab β Azure β β
β βProviderβ Providerβ Provider βProvider β β
β ββββββββββ΄ββββββββββ΄ββββββββββββ΄ββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Data Flow
User Input β URL Parsing β Provider Selection β Tree Fetch
β
File Tree (Virtual Scrolling) β User Selection β Filters
β
Content Fetch β Formatting β Tokenization (Web Worker)
β
Output Display β Copy/Download
π¨ Design Patterns
1. Provider Pattern
Purpose: Abstract different data sources (GitHub, Local, GitLab, Azure) behind a unified interface.
Implementation:
// Base provider interface
abstract class BaseProvider {
abstract getType(): ProviderType;
abstract validateUrl(url: string): boolean;
abstract parseUrl(url: string): ParsedRepoInfo;
abstract fetchTree(url: string, options?: FetchOptions): Promise<FileNode[]>;
abstract fetchFile(node: FileNode): Promise<FileContent>;
// Shared utilities
async *fetchMultiple(nodes: FileNode[]): AsyncGenerator<FileContent> {
// Progressive loading implementation
}
}
// Concrete implementation
class GitHubProvider extends BaseProvider {
async fetchTree(url: string): Promise<FileNode[]> {
// GitHub-specific implementation
const parsed = this.parseUrl(url);
const tree = await this.fetchGitHubTree(parsed);
return this.normalizeTree(tree);
}
}
Benefits:
- Easy to add new providers (GitLab, Bitbucket, etc.)
- Consistent interface across all sources
- Shared functionality in base class (error handling, retries, caching)
- Type-safe provider switching
2. State Management with Zustand
Purpose: Centralized, reactive state management without Redux boilerplate.
Store Structure:
// Modular stores (slices pattern)
interface AppState {
// UI State
theme: ThemeMode;
isLoading: boolean;
error: ErrorState | null;
// Data State
currentProvider: ProviderType;
tree: FileNode[];
selectedPaths: Set<string>;
excludedPaths: Set<string>;
// Actions
setProvider: (provider: ProviderType) => void;
toggleSelection: (path: string) => void;
// ...more actions
}
// Store composition
const useStore = create<AppState>()(
devtools(
persist(
(set, get) => ({
// Initial state
theme: 'system',
// Actions
setTheme: (theme) => set({ theme }),
// Computed selectors
getSelectedNodes: () => {
const { tree, selectedPaths } = get();
return tree.filter(n => selectedPaths.has(n.path));
}
}),
{ name: 'repo2txt-store' }
)
)
);
Benefits:
- Simple API with hooks
- DevTools integration
- Persistence support
- Computed selectors
- Minimal re-renders
3. Virtual Scrolling
Purpose: Efficiently render large file trees (10,000+ files) without performance degradation.
Implementation:
// Using TanStack Virtual
import { useVirtualizer } from '@tanstack/react-virtual';
function FileTree({ nodes }: { nodes: TreeNode[] }) {
const parentRef = useRef<HTMLDivElement>(null);
// Flatten tree for virtual scrolling
const flatNodes = useMemo(() => flattenTree(nodes), [nodes]);
const virtualizer = useVirtualizer({
count: flatNodes.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 32, // Row height
overscan: 10, // Render extra rows outside viewport
});
return (
<div ref={parentRef} style={{ height: '600px', overflow: 'auto' }}>
<div style={{ height: virtualizer.getTotalSize() }}>
{virtualizer.getVirtualItems().map(virtualRow => (
<FileTreeNode
key={virtualRow.key}
node={flatNodes[virtualRow.index]}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
transform: `translateY(${virtualRow.start}px)`,
}}
/>
))}
</div>
</div>
);
}
Benefits:
- Constant memory usage regardless of tree size
- Smooth scrolling
- Only renders visible items + overscan
- Automatic height calculation
4. Code Splitting with Dynamic Imports
Purpose: Reduce initial bundle size by lazy-loading provider implementations.
Implementation:
// Provider registry with lazy loading
const PROVIDERS = {
github: () => import('@/features/github/GitHubProvider'),
local: () => import('@/features/local/LocalProvider'),
gitlab: () => import('@/features/gitlab/GitLabProvider'),
azure: () => import('@/features/azure/AzureDevOpsProvider'),
};
// Dynamic provider loading in ProviderSelector
const loadProvider = async (type: ProviderType) => {
const ProviderModule = await PROVIDERS[type]();
const ProviderClass = ProviderModule.default;
return new ProviderClass();
};
Bundle Impact:
- Main chunk: ~330KB
- GitHub provider: ~50KB (loaded on demand)
- Local provider: ~30KB (loaded on demand)
- Each provider only loads when selected
5. Web Worker for Tokenization
Purpose: Offload CPU-intensive tokenization to background thread.
Implementation:
// Worker wrapper
class TokenizerWorker {
private worker: Worker;
async tokenize(text: string): Promise<number> {
return new Promise((resolve) => {
this.worker.postMessage({ type: 'tokenize', text });
this.worker.onmessage = (e) => resolve(e.data.tokenCount);
});
}
async tokenizeBatch(
files: FileContent[],
onProgress?: (progress: number) => void
): Promise<{ totalTokens: number; files: FileWithStats[] }> {
// Progressive tokenization with progress callbacks
}
}
// Worker implementation (tokenizer.worker.ts)
self.onmessage = async (event) => {
const { type, text, files } = event.data;
if (type === 'tokenize') {
const tokenCount = encode(text).length;
self.postMessage({ tokenCount });
} else if (type === 'tokenize_batch') {
for (const file of files) {
const tokenCount = encode(file.content).length;
self.postMessage({
type: 'progress',
file: { ...file, tokenCount }
});
}
}
};
Benefits:
- Non-blocking UI during tokenization
- Progress updates for long operations
- Better perceived performance
- Utilizes multi-core CPUs
6. Error Handling Strategy
Layered error handling with custom error types:
// Custom error classes
class ProviderError extends Error {
constructor(
message: string,
public code: ErrorCode,
public userMessage: string,
public recovery?: () => void
) {
super(message);
}
}
// Error boundaries in React
class ErrorBoundary extends Component {
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
// Log to error tracking service
console.error('Caught error:', error, errorInfo);
}
}
// Error dialog for user-facing errors
{error && (
<ErrorDialog
title="Unable to Complete Request"
message={error.message}
onClose={() => setError(null)}
onAction={error.recovery}
actionLabel={error.recoveryLabel}
/>
)}
π Project Structure
repo2txt/
βββ .github/
β βββ workflows/
β βββ deploy.yml # GitHub Actions CI/CD
β
βββ src/
β βββ features/ # Feature modules (domain-driven)
β β βββ github/
β β β βββ GitHubProvider.ts # GitHub API implementation
β β β βββ components/ # GitHub-specific UI
β β β β βββ GitHubAuth.tsx # Token management
β β β β βββ GitHubForm.tsx # URL input form
β β β β βββ GitHubUrlInput.tsx
β β β βββ __tests__/ # Feature tests
β β β
β β βββ local/
β β β βββ LocalProvider.ts # File System API
β β β βββ components/
β β β βββ DirectoryPicker.tsx
β β β βββ ZipUploader.tsx
β β β βββ LocalForm.tsx
β β β
β β βββ gitlab/ # GitLab provider (beta)
β β βββ azure/ # Azure DevOps (beta)
β β
β βββ components/ # Shared UI components
β β βββ ui/ # Base components (buttons, dialogs)
β β β βββ Button.tsx
β β β βββ ErrorDialog.tsx
β β β βββ ThemeToggle.tsx
β β β
β β βββ file-tree/ # File tree components
β β β βββ FileTree.tsx # Virtual scrolling tree
β β β βββ FileTreeNode.tsx # Individual node
β β β
β β βββ filters/ # Filtering components
β β β βββ AdvancedFilters.tsx
β β β βββ ExtensionFilter.tsx
β β β βββ GitignoreEditor.tsx
β β β
β β βββ OutputPanel.tsx # Output display & actions
β β βββ FileStats.tsx # Token/line statistics
β β βββ ProviderSelector.tsx # Provider tabs
β β
β βββ lib/ # Core business logic
β β βββ providers/
β β β βββ BaseProvider.ts # Abstract base class
β β β βββ types.ts # Shared provider types
β β β
β β βββ formatter/
β β β βββ Formatter.ts # Output formatting
β β β βββ TokenizerWorker.ts # Web Worker wrapper
β β β βββ __tests__/
β β β
β β βββ gitignore/
β β β βββ GitignoreParser.ts # .gitignore parsing
β β β
β β βββ utils.ts # Shared utilities
β β
β βββ store/ # Zustand state management
β β βββ index.ts # Store composition
β β βββ slices/ # Store slices
β β βββ providerSlice.ts # Provider state
β β βββ fileTreeSlice.ts # File tree state
β β βββ filterSlice.ts # Filter state
β β βββ uiSlice.ts # UI state (theme, loading)
β β
β βββ hooks/ # Custom React hooks
β β βββ useFileTree.ts
β β βββ useProvider.ts
β β βββ useTheme.ts
β β
β βββ workers/ # Web Workers
β β βββ tokenizer.worker.ts # GPT tokenizer
β β
β βββ types/ # Shared TypeScript types
β β βββ index.ts
β β
β βββ App.tsx # Root component
β βββ main.tsx # Entry point
β βββ index.css # Global styles
β
βββ tests/
β βββ e2e/ # End-to-end tests (Playwright)
β β βββ dark-mode.spec.ts
β β βββ error-scenarios.spec.ts
β β βββ github-flow.spec.ts
β β βββ local-flow.spec.ts
β β
β βββ test-config.ts # Test configuration (git-ignored)
β βββ test-config.example.ts # Template
β
βββ public/ # Static assets
βββ dist/ # Build output (git-ignored)
β
βββ .eslintrc.cjs # ESLint configuration
βββ .prettierrc # Prettier configuration
βββ tsconfig.json # TypeScript configuration
βββ vite.config.ts # Vite configuration
βββ playwright.config.ts # Playwright configuration
βββ vitest.config.ts # Vitest configuration
βββ package.json # Dependencies & scripts
Key Directories Explained
features/ - Domain-driven feature modules. Each feature (GitHub, Local, etc.) is self-contained with its provider implementation, UI components, and tests.
components/ - Shared UI components used across features. Organized by functionality (ui, file-tree, filters).
lib/ - Core business logic independent of UI framework. Could be extracted to a separate package if needed.
store/ - Centralized state management using Zustand slices pattern. Each slice manages a specific concern.
workers/ - Web Workers for CPU-intensive tasks. Keeps UI thread responsive.
π§ͺ Testing Strategy
Testing Pyramid
/\
/ \ E2E (Playwright) - 25 tests
/____\ Critical user flows
/ \
/ \ Integration - Provider + UI
/__________\
/ \ Unit (Vitest) - 80%+ coverage
/______________\ Business logic, utilities, components
Unit Tests (Vitest + React Testing Library)
What to test:
- Pure functions (formatters, parsers, utilities)
- React components in isolation
- Provider methods
- Store actions and selectors
Example:
// lib/formatter/__tests__/Formatter.test.ts
describe('Formatter', () => {
it('should format directory tree', () => {
const tree = [
{ path: 'src', type: 'tree' },
{ path: 'src/index.ts', type: 'blob' },
];
const formatted = Formatter.formatTree(tree);
expect(formatted).toContain('βββ π src');
expect(formatted).toContain('βββ π index.ts');
});
it('should count tokens accurately', () => {
const text = 'Hello world';
const count = Formatter.countTokens(text);
expect(count).toBeGreaterThan(0);
});
});
Integration Tests
What to test:
- Provider + FileTree interactions
- Filter + FileTree updates
- Store + Component integration
Example:
describe('GitHub Provider Integration', () => {
it('should load and display file tree', async () => {
const provider = new GitHubProvider();
const tree = await provider.fetchTree('https://github.com/facebook/react');
render(<FileTree nodes={tree} />);
expect(screen.getByText('package.json')).toBeInTheDocument();
});
});
E2E Tests (Playwright)
What to test:
- Complete user workflows
- Cross-browser compatibility
- Real API interactions
Current Coverage:
- β Dark mode (5 tests)
- β Error scenarios (8 tests)
- β GitHub flow (6 tests)
- β Local flow (6 tests)
Example:
// tests/e2e/github-flow.spec.ts
test('should complete full GitHub public repo flow', async ({ page }) => {
await page.goto('/');
// Enter URL
const urlInput = page.getByPlaceholder('https://github.com/facebook/react');
await urlInput.fill('https://github.com/abinthomasonline/repo2txt');
// Load repo
const loadButton = page.getByRole('button', { name: /Load Repository/i });
await loadButton.click();
// Verify file tree
await expect(page.getByTestId('file-tree-heading')).toBeVisible({ timeout: 30000 });
// Generate output
const generateButton = page.getByTestId('generate-output-button');
await generateButton.click();
// Verify output
await expect(page.getByText('Directory Structure:')).toBeVisible();
// Download
const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: /Download/i }).click();
const download = await downloadPromise;
expect(download.suggestedFilename()).toMatch(/\.txt/);
});
Running Tests
# Unit tests
npm run test:unit # Run once
npm run test:watch # Watch mode
npm run test:coverage # With coverage
# E2E tests
npm run test:e2e # All browsers
npm run test:e2e -- --project=chromium # Single browser
npm run test:e2e:ui # Interactive UI
# Test specific file
npm run test:unit -- Formatter.test.ts
npm run test:e2e -- github-flow.spec.ts
Test Configuration
E2E Test Token Setup:
# Copy template
cp tests/test-config.example.ts tests/test-config.ts
# Add your token to test-config.ts
export const testConfig = {
githubToken: process.env.GITHUB_TOKEN || 'your_token_here',
};
CI Configuration:
Tests run automatically on PRs via GitHub Actions. Set GITHUB_TOKEN secret in repository settings for E2E tests.
π Code Style
TypeScript
- Strict mode enabled - No implicit any, strict null checks
- Explicit return types - For public functions and methods
- Interface over type - Prefer interfaces for object shapes
- Functional style - Prefer pure functions, immutability
Example:
// β
Good
interface FileNode {
path: string;
type: 'blob' | 'tree';
children?: FileNode[];
}
function filterNodes(nodes: FileNode[], predicate: (node: FileNode) => boolean): FileNode[] {
return nodes.filter(predicate).map(node => ({
...node,
children: node.children ? filterNodes(node.children, predicate) : undefined,
}));
}
// β Bad
function filterNodes(nodes: any, predicate): any {
return nodes.filter(predicate);
}
React Components
- Functional components - Use hooks, avoid class components
- Named exports - Except for default component export
- Props interfaces - Named after component:
ComponentNameProps - Early returns - Handle edge cases first
Example:
// β
Good
interface FileTreeNodeProps {
node: TreeNode;
depth: number;
onToggle: (path: string) => void;
}
export function FileTreeNode({ node, depth, onToggle }: FileTreeNodeProps) {
if (!node) return null;
const isDirectory = node.type === 'tree';
return (
<div style={{ paddingLeft: `${depth * 16}px` }}>
<button onClick={() => onToggle(node.path)}>
{isDirectory ? 'π' : 'π'} {node.name}
</button>
</div>
);
}
CSS/Tailwind
- Tailwind first - Use utility classes
- Component classes - For reusable patterns, define in component
- Dark mode - Always add dark: variants
- Responsive - Mobile-first with sm:, md:, lg: breakpoints
Example:
// β
Good
<div className="flex items-center gap-2 p-4 bg-white dark:bg-gray-900 rounded-lg">
<button className="px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white rounded-md transition-colors">
Click me
</button>
</div>
// β Bad
<div style={{ display: 'flex', padding: '16px', backgroundColor: '#fff' }}>
<button style={{ padding: '8px 16px', backgroundColor: '#3b82f6' }}>
Click me
</button>
</div>
File Naming
- Components: PascalCase (e.g.,
FileTree.tsx,ErrorDialog.tsx) - Utilities: camelCase (e.g.,
formatTree.ts,parseUrl.ts) - Types: PascalCase (e.g.,
FileNode,ProviderType) - Tests: Same as file +
.test.tsor.spec.ts
Code Organization
Import Order:
// 1. React/external libraries
import { useState, useEffect } from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
// 2. Internal imports (@/ aliases)
import { BaseProvider } from '@/lib/providers/BaseProvider';
import { FileTree } from '@/components/file-tree/FileTree';
// 3. Types
import type { FileNode, ProviderType } from '@/types';
// 4. Relative imports
import { formatTree } from './utils';
// 5. Styles (if any)
import './styles.css';
ESLint & Prettier
All code must pass linting and formatting:
npm run lint # Check for issues
npm run lint:fix # Auto-fix
npm run format # Format with Prettier
npm run format:check # Check formatting
π Development Workflow
Branch Strategy
master- Production-ready codev2-development- Main development branchfeature/*- New features (e.g.,feature/gitlab-support)fix/*- Bug fixes (e.g.,fix/token-storage)refactor/*- Code refactoring (e.g.,refactor/provider-interface)
Commit Messages
Follow Conventional Commits:
<type>(<scope>): <subject>
<body>
<footer>
Types:
feat: New featurefix: Bug fixrefactor: Code refactoringtest: Test changesdocs: Documentationstyle: Code style changes (formatting)perf: Performance improvementschore: Build process, dependencies
Examples:
git commit -m "feat(github): support branch names with slashes"
git commit -m "fix(ui): correct dark mode toggle sequence"
git commit -m "test(e2e): add error dialog tests"
git commit -m "docs: update architecture documentation"
Pull Request Process
-
Create Feature Branch
git checkout -b feature/your-feature -
Make Changes
- Write code
- Add tests
- Update documentation
- Run quality checks
-
Test Locally
npm run ci # Type check + lint + unit tests npm run test:e2e # E2E tests -
Commit Changes
git add . git commit -m "feat(scope): your feature description" -
Push to GitHub
git push origin feature/your-feature -
Create Pull Request
- Fill out PR template
- Link related issues
- Request reviews
-
Address Review Feedback
- Make requested changes
- Push additional commits
- Re-request review
-
Merge
- Squash merge for feature branches
- Merge commit for releases
PR Checklist
Before submitting a PR:
- Code follows style guide
- All tests pass locally
- Added tests for new features
- Updated documentation
- No TypeScript errors
- No ESLint warnings
- Formatted with Prettier
- Tested in multiple browsers (if UI change)
- Tested dark mode (if UI change)
- Added/updated comments for complex logic
- No console.logs or debugger statements
- Bundle size impact is acceptable
π Debugging Tips
React DevTools
Install React DevTools for component inspection and state debugging.
Zustand DevTools
DevTools integration is enabled in development:
// Inspect store in browser console
window.__ZUSTAND_STORE__
Vite Debug Mode
# Enable verbose logging
DEBUG=vite:* npm run dev
Common Issues
Issue: E2E tests failing with rate limit
- Add GitHub token to
tests/test-config.ts
Issue: Build fails with TypeScript errors
- Run
npm run typecheckto see all errors - Use
npm run build:checkfor strict type checking
Issue: Virtual scrolling not working
- Check parent container has fixed height
- Verify
flattenTreefunction is memoized
Issue: Web Worker not loading
- Check worker file path in Vite config
- Ensure worker is imported with
?workersuffix
π Additional Resources
- React Documentation
- TypeScript Handbook
- Vite Guide
- Zustand Documentation
- Tailwind CSS
- Playwright Documentation
π¬ Questions?
- GitHub Discussions: Ask questions
- Issues: Report bugs
- Email: abinthomasonline@gmail.com
Thank you for contributing to repo2txt! π