OpenWriterControle/evals/framework/src/config.ts
Darren Hinde c8f7103cb6
refactor(evals): consolidate documentation and enhance test infrastructure (#56)
* feat(agents): implement category-based agent organization system

- Organize agents into domain categories (core, development, content, data, product, learning)
- Move 10 agents to category subdirectories with proper git rename tracking
- Update 13 subagents with category and type metadata in frontmatter
- Add category metadata files (0-category.json) documenting common patterns
- Implement local registry fallback in install script for offline development
- Add comprehensive validation suite with 15 automated tests (100% pass rate)
- Enhance registry validation with duplicate ID and consistency checks
- Update eval framework with intelligent path resolution (backward compatible)
- Archive legacy eval structure to _archive/ for reference
- Update all documentation to reflect category-based structure
- Bump version to 0.5.0 with accurate CHANGELOG

Technical Details:
- 23 agents organized (10 category agents, 13 subagents)
- 6 category directories created
- Path resolution supports both agent IDs and category paths
- Registry schema updated to v2.0.0
- 159 files changed, 872 insertions(+), 10738 deletions(-)

BREAKING CHANGE: Agent file paths now use category structure. Update references from .opencode/agent/openagent.md to .opencode/agent/core/openagent.md. Eval framework maintains backward compatibility via path resolution.

* refactor(evals): consolidate documentation and enhance test infrastructure

- Remove temporary project tracking files (PHASE_5_COMPLETE, PROJECT_COMPLETE, etc.)
- Consolidate evaluation framework docs into main README
- Enhance test execution with improved logging and multi-prompt support
- Move system-builder from core to meta category
- Add comprehensive test suites for openagent with organized structure
- Create evaluation test structure for all subagents
- Clean up archived workflows and redundant documentation
- Update registry to reflect new agent organization
- Add shared test templates and golden test patterns

* feat(ci): add manual trigger support for bot-created PRs in validate-registry workflow

- Add pr_number input to workflow_dispatch for manually triggering validation
- Fetch PR details dynamically when triggered manually
- Support both automatic (PR event) and manual (workflow_dispatch) triggers
- Enable validation of bot-created PRs like automated version bumps
- Update branch detection and push logic to handle both trigger types
- Add documentation explaining how to manually trigger for bot PRs

* feat(evals): add explicit context file validation to test framework

- Add expectedContextFiles field to test YAML schema for explicit context file specification
- Enhance context-loading-evaluator to support both auto-detect and explicit validation modes
- Update documentation with comprehensive guide and examples
- Clean up archived legacy test structure (90+ old test files)
- Add new example tests demonstrating explicit context validation
- Backward compatible with existing tests

* feat(evals): add multi-agent logging system and performance optimizations

Implement comprehensive multi-agent logging and performance improvements for the eval framework.

Task 01: Multi-Agent Logging System
- Add complete hierarchical logging module (evals/framework/src/logging/)
  - SessionTracker: tracks parent-child delegation hierarchies
  - MultiAgentLogger: pretty-prints logs with visual indentation
  - Formatters: box characters and emoji formatting
  - 37 passing unit tests (session-tracker, logger, integration)
- Integrate with SDK event stream handler
  - Hook into session.created, message.updated, message.part.updated events
  - Real-time child session detection via timestamp heuristics
  - Message deduplication for cleaner output
- Enable in debug mode only (<1% performance overhead)
- Add demo script and comprehensive documentation

Task 02: Performance Optimizations
- Reduce grace period from 5s to 2s (67% reduction, 10-20% faster tests)
- Add PerformanceMetricsEvaluator for bottleneck identification
  - Collects tool latencies, inference time, idle time
  - Provides full performance visibility
- Update smoke test to validate delegation (core feature)
  - Replace simple read test with multi-agent delegation test
  - Tests both parent and child agent functionality
  - Validates multi-agent logging system

Results:
- 37 unit tests passing
- Smoke test passing (95/100 score)
- Clean hierarchical logging output
- 10-20% faster test execution
- Full multi-agent visibility

Files changed: 16 files, +2678 lines
Time saved: ~6-8 days (completed in 6 hours vs 3-5 day estimate)

* feat(evals): show child agent execution in non-debug mode

- Enable MultiAgentLogger in both debug and non-debug modes
- Add verbose parameter to control output level
- Non-verbose mode shows concise child session lifecycle:
  - Child agent started message
  - Child agent completed with duration
- Verbose mode (--debug) shows full delegation hierarchy
- Update documentation to reflect new behavior

This provides visibility into delegation without overwhelming output,
giving confidence that child agents are actually running.

* feat(evals): improve delegation testing and behavior validation

Major improvements to eval framework:

Test Suite:
- Add 00-smoke-test.yaml (basic read operation)
- Rename 01-smoke-test.yaml → 02-delegation-test.yaml (delegation test)
- Add simple-responder test agent for delegation testing
- Add debug test: simple-subagent-call.yaml

Evaluators:
- Add agent-model-evaluator.ts for agent/model validation
- Enhance behavior-evaluator.ts with detailed task tool output
- Improve delegation-evaluator.ts with better evidence tracking

Schema & Execution:
- Add expectedAgent and expectedModel to test schema
- Improve test executor with better logging and error handling

Documentation:
- Update evals/README.md with new features and performance improvements
- Remove outdated MULTI_AGENT_LOGGING_COMPLETE.md

Registry:
- Add simple-responder test agent to registry

Fixes:
- Fix dashboard.sh path resolution

These changes provide better visibility into delegation, improved test
coverage, and clearer validation of agent behavior.

* chore: add GitHub Actions workflow and plugin documentation

- Add .github/workflows/evals/run-evaluations.yml for automated eval testing
- Add dev/ai-tools/opencode/plugins/Plugin-inspiration.md for plugin development reference
2025-12-18 09:52:11 +00:00

310 lines
9.8 KiB
TypeScript

/**
* Framework configuration
*
* Default configuration for the evaluation framework.
* Can be overridden by passing custom config to components.
*/
import { FrameworkConfig } from './types';
import * as path from 'path';
import * as os from 'os';
import * as crypto from 'crypto';
import * as fs from 'fs';
/**
* Find the git root directory by walking up from a given path
*
* OpenCode agents typically run from the git root directory.
* Sessions are stored based on the git root, not subdirectories.
*
* @param startPath - Path to start searching from (defaults to cwd)
* @returns Git root path or the start path if no git root found
*/
export const findGitRoot = (startPath: string = process.cwd()): string => {
let currentPath = path.resolve(startPath);
// Walk up the directory tree looking for .git
while (currentPath !== path.dirname(currentPath)) {
const gitPath = path.join(currentPath, '.git');
if (fs.existsSync(gitPath)) {
return currentPath;
}
currentPath = path.dirname(currentPath);
}
// No git root found, return the start path
return startPath;
};
/**
* Get default session storage path
* OpenCode stores sessions in ~/.local/share/opencode/
*/
const getDefaultSessionStoragePath = (): string => {
const homeDir = os.homedir();
return path.join(homeDir, '.local', 'share', 'opencode');
};
/**
* Default framework configuration
*
* IMPORTANT: Uses git root as projectPath, not process.cwd()
*
* Why? When testing agents like OpenAgent, the agent runs from the git root,
* but tests run from /evals/framework. Sessions are created in the git root's
* context, so we need to look there for session storage.
*
* Example:
* - Git root: /Users/user/opencode-agents
* - Test CWD: /Users/user/opencode-agents/evals/framework
* - Sessions stored under git root hash, not test framework hash
*/
export const defaultConfig: FrameworkConfig = {
projectPath: findGitRoot(process.cwd()), // Use git root, not cwd
sessionStoragePath: getDefaultSessionStoragePath(),
resultsPath: path.join(process.cwd(), 'evals', 'results'),
passThreshold: 75,
};
/**
* Create custom configuration by merging with defaults
*/
export const createConfig = (overrides: Partial<FrameworkConfig> = {}): FrameworkConfig => {
return {
...defaultConfig,
...overrides,
};
};
/**
* Encode project path for OpenCode storage (legacy format)
* OpenCode replaces slashes with dashes in project paths
* Example: /Users/user/project -> Users-user-project
*
* NOTE: This is the LEGACY format used by older OpenCode versions.
* The SDK now uses a hash-based format instead.
*/
export const encodeProjectPath = (projectPath: string): string => {
// Remove leading slash and replace remaining slashes with dashes
return projectPath.replace(/^\//, '').replace(/\//g, '-');
};
/**
* Calculate project hash (SHA-1) used by OpenCode SDK
* The SDK stores sessions using a hash of the project path instead of the encoded path.
* This matches the projectID field in session JSON files.
*
* NOTE: The exact hashing algorithm used by OpenCode is not documented.
* This function attempts to calculate it, but may not match in all cases.
* The SessionReader falls back to scanning all session directories if needed.
*
* Example: /Users/user/project -> 9b95828208165943d702402641ce831a3cda362e
*/
export const getProjectHash = (projectPath: string): string => {
// OpenCode uses SHA-1 hash of the absolute project path
// However, the exact implementation may vary (e.g., trailing slashes, normalization)
return crypto.createHash('sha1').update(projectPath).digest('hex');
};
/**
* Get session storage path for a specific project (SDK format)
*
* The OpenCode SDK uses a FLAT structure with project hash:
* ~/.local/share/opencode/storage/session/{projectHash}/
*
* This is different from the legacy nested structure:
* ~/.local/share/opencode/project/{encoded-path}/storage/session/
*
* @param projectPath - Absolute path to the project
* @param sessionStoragePath - Base storage path (defaults to ~/.local/share/opencode)
* @returns Path to session storage directory
*/
export const getProjectSessionPath = (
projectPath: string,
sessionStoragePath: string = getDefaultSessionStoragePath()
): string => {
// Use SDK's hash-based flat structure
const projectHash = getProjectHash(projectPath);
return path.join(sessionStoragePath, 'storage', 'session', projectHash);
};
/**
* Get legacy session storage path for a specific project
*
* This is the OLD format used before the SDK migration.
* We keep this for backward compatibility when reading old sessions.
*
* @param projectPath - Absolute path to the project
* @param sessionStoragePath - Base storage path
* @returns Path to legacy session storage directory
*/
export const getLegacyProjectSessionPath = (
projectPath: string,
sessionStoragePath: string = getDefaultSessionStoragePath()
): string => {
const encodedPath = encodeProjectPath(projectPath);
return path.join(sessionStoragePath, 'project', encodedPath, 'storage', 'session');
};
/**
* Get session info path (SDK format)
*
* SDK stores session info files directly in the project hash directory:
* ~/.local/share/opencode/storage/session/{projectHash}/{sessionId}.json
*
* NOT in a nested info/ subdirectory like the legacy format.
*/
export const getSessionInfoPath = (
projectPath: string,
sessionStoragePath?: string
): string => {
// SDK uses flat structure - session files are directly in the project hash directory
return getProjectSessionPath(projectPath, sessionStoragePath);
};
/**
* Get legacy session info path (for backward compatibility)
*
* Legacy format uses nested structure:
* ~/.local/share/opencode/project/{encoded-path}/storage/session/info/
*/
export const getLegacySessionInfoPath = (
projectPath: string,
sessionStoragePath?: string
): string => {
return path.join(getLegacyProjectSessionPath(projectPath, sessionStoragePath), 'info');
};
/**
* Get session message path (SDK format)
*
* NOTE: The SDK currently stores sessions as single JSON files.
* Message/part subdirectories may not exist for SDK-created sessions.
* This path is kept for compatibility with legacy sessions.
*/
export const getSessionMessagePath = (
projectPath: string,
sessionStoragePath?: string
): string => {
return path.join(getProjectSessionPath(projectPath, sessionStoragePath), 'message');
};
/**
* Get legacy session message path
*/
export const getLegacySessionMessagePath = (
projectPath: string,
sessionStoragePath?: string
): string => {
return path.join(getLegacyProjectSessionPath(projectPath, sessionStoragePath), 'message');
};
/**
* Get session part path (SDK format)
*
* NOTE: The SDK currently stores sessions as single JSON files.
* Message/part subdirectories may not exist for SDK-created sessions.
* This path is kept for compatibility with legacy sessions.
*/
export const getSessionPartPath = (
projectPath: string,
sessionStoragePath?: string
): string => {
return path.join(getProjectSessionPath(projectPath, sessionStoragePath), 'part');
};
/**
* Get legacy session part path
*/
export const getLegacySessionPartPath = (
projectPath: string,
sessionStoragePath?: string
): string => {
return path.join(getLegacyProjectSessionPath(projectPath, sessionStoragePath), 'part');
};
/**
* Resolve agent path to support both old and new formats
*
* Supports:
* - Old format: "openagent" → ".opencode/agent/openagent.md"
* - New format: "core/openagent" → ".opencode/agent/core/openagent.md"
* - Subagents: "subagents/code/tester" → ".opencode/agent/subagents/code/tester.md"
*
* @param agent - Agent identifier (e.g., "openagent" or "core/openagent")
* @param projectPath - Project root path (defaults to git root)
* @returns Absolute path to agent file
*/
export const resolveAgentPath = (agent: string, projectPath?: string): string => {
const root = projectPath || findGitRoot(process.cwd());
const agentDir = path.join(root, '.opencode', 'agent');
// If agent contains a slash, it's a category-based path
if (agent.includes('/')) {
return path.join(agentDir, `${agent}.md`);
}
// Old format - flat structure
return path.join(agentDir, `${agent}.md`);
};
/**
* Normalize agent identifier to category-based format
*
* Maps old agent names to new category-based paths:
* - "openagent" → "core/openagent"
* - "opencoder" → "core/opencoder"
* - "system-builder" → "meta/system-builder"
*
* Already category-based paths are returned as-is:
* - "core/openagent" → "core/openagent"
* - "development/frontend-specialist" → "development/frontend-specialist"
*
* @param agent - Agent identifier
* @returns Normalized agent identifier
*/
export const normalizeAgentId = (agent: string): string => {
// Already category-based
if (agent.includes('/')) {
return agent;
}
// Map old core agents to new paths
const coreAgents: Record<string, string> = {
'openagent': 'core/openagent',
'opencoder': 'core/opencoder',
'system-builder': 'meta/system-builder',
};
return coreAgents[agent] || agent;
};
/**
* Extract category from agent identifier
*
* Examples:
* - "core/openagent" → "core"
* - "development/frontend-specialist" → "development"
* - "subagents/code/tester" → "subagents/code"
* - "openagent" → undefined (flat structure)
*
* @param agent - Agent identifier
* @returns Category path or undefined
*/
export const extractAgentCategory = (agent: string): string | undefined => {
if (!agent.includes('/')) {
return undefined;
}
const parts = agent.split('/');
// For subagents, include both levels (e.g., "subagents/code")
if (parts[0] === 'subagents' && parts.length >= 2) {
return `${parts[0]}/${parts[1]}`;
}
// For regular categories, just the first part
return parts[0];
};