OpenWriterControle/evals/framework
Darren Hinde 699b2d7769
ci(security): phase-1 CI hardening — affected-area tests, least privilege, action pinning, dependency governance (#336)
* ci(security): run deterministic eval tests in affected-area CI (Task 04)

The build-check job validated build + suite structure but never ran the
tests, and its summary referenced a `test:ci` script that did not exist.
Make affected-area CI meaningful:

- Add `test:ci` to evals/framework running the offline, deterministic
  Vitest allowlist (7 files / 112 tests) — no model, network, or paid
  execution.
- Add a required "Run deterministic tests" step to build-check; a failure
  fails the job and the existing PR summary gate (which keys on
  build-check.result) fails closed.
- Correct the summary note to state test:ci runs the deterministic
  allowlist and that model/network agent suites are excluded on PRs.

The broader deterministic suite has 3 pre-existing failing files
(framework-confidence, logger, test-runner; confirmed failing before this
work) which are intentionally out of the allowlist and tracked separately.

Validated locally: build, validate:suites:all, and test:ci all exit 0.

* ci(security): least privilege permissions + pin actions to SHAs (Task 05)

Harden all 9 GitHub Actions workflows:

Least privilege:
- Add explicit top-level `permissions: contents: read` to installer-checks,
  validate-test-suites, and opencode (opencode's job keeps the writes it
  needs; the top level now defaults to read).
- Every workflow now declares an explicit top-level permissions block.
- Write scopes retained only where justified (releases, doc/registry
  commits, follow-up PRs, and sync-docs' issues.create).

Immutable action pinning:
- Pin every `uses:` to a full 40-char commit SHA with a version comment,
  including first-party actions/* (checkout, github-script, setup-node,
  upload-artifact) and third-party (oven-sh/setup-bun).
- Replace the two mutable refs that could change under us at any push:
  ludeeus/action-shellcheck@master and sst/opencode/github@latest.

Record all SHAs, versions, and permission justifications in
docs/maintenance/repository-recovery/action-pin-inventory.md.

Verified: all 9 workflows parse as valid YAML; no floating tag/branch refs
remain; every workflow has a top-level permissions block.

* docs(security): add SECURITY.md and private-reporting checklist (Task 06)

- Add root SECURITY.md: supported versions (0.7.x), private reporting via
  GitHub's "Report a vulnerability", best-effort response expectations,
  coordinated disclosure, and no-secret guidance.
- Add private-vulnerability-reporting checklist that separates repository
  file work (this PR) from GitHub settings changes that require their own
  approval (Task 07: enabling private vulnerability reporting).

No external links to validate; the reporting path uses the repo Security
tab. SECURITY.md documents the private reporting path ahead of Task 07
enabling it.

* ci(security): add dependency governance and ownership controls (Task 08)

- .github/dependabot.yml: weekly grouped github-actions updates (keeps the
  Task 05 SHA pins current). Scoped to actions only — the primary lockfile
  is bun.lock and Dependabot's npm ecosystem would desync it; npm
  dependency risk is covered by dependency-review below.
- .github/workflows/dependency-review.yml: runs on PRs with contents: read,
  SHA-pinned actions, fail-on-severity: high to block newly introduced
  high-severity vulnerabilities (exceptions documented inline).
- .github/CODEOWNERS: default owner @darrenhinde with explicit ownership of
  security-sensitive paths (workflows, dependabot, CODEOWNERS, SECURITY.md,
  scripts/validation).

Verified: dependabot.yml and dependency-review.yml are valid YAML;
dependency-review actions are SHA-pinned with contents: read; CODEOWNERS
owner is the repository owner.

* docs(security): record GitHub security settings evidence (Task 07)

Enable private vulnerability reporting and record read-back evidence.

Settings changed (each approved immediately before, verified by read-back):
- Private vulnerability reporting: enabled=false -> enabled=true. The
  Security tab now offers "Report a vulnerability", making the path
  documented in SECURITY.md live.
- Dependency Graph / Dependabot alerts: 404 -> 204. This was an
  undocumented prerequisite of Task 08's dependency-review.yml, which
  failed with "Dependency graph is not enabled"; the Dependency Review
  check on PR #336 went fail -> pass after enabling it.

No other repository setting was modified; secret scanning and push
protection are unchanged, and dependabot_security_updates remains disabled
(out of scope, would need its own approval). Both changes are reversible
via the corresponding DELETE calls.

Marks Part B of the private-vulnerability-reporting checklist complete.
2026-07-15 00:19:28 +01:00
..
scripts fix: resolve installer failures and add comprehensive validation (#189) 2026-02-06 17:07:42 +00:00
src fix(evals): repair deterministic eval baseline (behavioral regressions + tsc build) (#334) 2026-07-14 23:22:27 +01:00
.eval-config.example.json feat: implement SDK-based evaluation framework with real agent testing 2025-11-22 14:30:11 +00:00
.gitignore Add evaluation framework structure and OpenCode logging documentation 2025-11-21 14:50:44 +00:00
demo-enhanced-features.sh Add Production-Ready Eval Framework for OpenAgent (#25) 2025-11-28 11:48:13 +00:00
INTEGRATION_TESTS.md fix(registry): add missing agents to installation profiles - v0.5.1 (#64) (#67) 2025-12-30 00:03:48 +00:00
LLM_INTEGRATION_VALIDATION.md feat: repository review and MVI context system implementation (#85) 2026-01-09 14:02:15 +00:00
package-lock.json fix(evals): repair deterministic eval baseline (behavioral regressions + tsc build) (#334) 2026-07-14 23:22:27 +01:00
package.json ci(security): phase-1 CI hardening — affected-area tests, least privilege, action pinning, dependency governance (#336) 2026-07-15 00:19:28 +01:00
README.md refactor(evals): consolidate documentation and enhance test infrastructure (#56) 2025-12-18 09:52:11 +00:00
test-path-resolution.mjs refactor(evals): consolidate documentation and enhance test infrastructure (#56) 2025-12-18 09:52:11 +00:00
tsconfig.json feat: implement SDK-based evaluation framework with real agent testing 2025-11-22 14:30:11 +00:00

Evaluation Framework (Technical)

Core framework for evaluating agent behavior. For user documentation, see ../README.md.

Architecture

framework/
├── src/
│   ├── sdk/                 # Test execution
│   │   ├── test-runner.ts   # Main orchestrator
│   │   ├── test-executor.ts # Executes individual tests
│   │   ├── client-manager.ts
│   │   └── event-stream-handler.ts
│   ├── evaluators/          # Rule validators
│   │   ├── base-evaluator.ts
│   │   ├── approval-gate-evaluator.ts
│   │   ├── context-loading-evaluator.ts
│   │   ├── execution-balance-evaluator.ts
│   │   ├── tool-usage-evaluator.ts
│   │   ├── behavior-evaluator.ts
│   │   ├── delegation-evaluator.ts
│   │   ├── stop-on-failure-evaluator.ts
│   │   └── performance-metrics-evaluator.ts  # NEW
│   ├── logging/             # Multi-agent logging (NEW)
│   │   ├── types.ts
│   │   ├── session-tracker.ts
│   │   ├── logger.ts
│   │   ├── formatters.ts
│   │   ├── index.ts
│   │   └── __tests__/       # 37 unit tests
│   ├── collector/           # Session data
│   │   ├── session-reader.ts
│   │   └── timeline-builder.ts
│   └── types/
│       └── index.ts
└── package.json

Evaluators

approval-gate

Checks that approval is requested before risky operations (bash, write, edit, task).

context-loading

Verifies context files are loaded before acting on tasks.

NEW: Supports explicit context file specification via expectedContextFiles in test YAML.

  • Auto-detect mode: Infers expected files from user message keywords
  • Explicit mode: Uses files specified in behavior.expectedContextFiles

execution-balance

Ensures read operations happen before write operations.

tool-usage

Validates dedicated tools are used instead of bash antipatterns.

behavior

Checks expected tools are used and forbidden tools are avoided.

delegation

Validates complex tasks are delegated to subagents.

stop-on-failure

Ensures agent stops on errors instead of auto-fixing.

performance-metrics (NEW)

Collects performance data for analysis:

  • Total test duration
  • Tool latencies (avg, min, max per tool)
  • LLM inference time estimation
  • Idle time between events
  • Event distribution

Always passes - used for metrics collection only.

Multi-Agent Logging (NEW)

The framework now includes comprehensive multi-agent logging that tracks delegation hierarchies in real-time.

Features

  • Visual hierarchy - Box characters and indentation show parent-child relationships (debug mode)
  • Session tracking - Tracks all sessions (parent, child, grandchild, etc.)
  • Real-time capture - Hooks into SDK event stream for live updates
  • Non-verbose mode - Shows child agent execution in normal mode without full debug output
  • Verbose mode - Full delegation hierarchy with --debug flag

Usage

# Non-verbose mode (default) - shows child agent completion
npm run eval:sdk -- --agent=openagent --pattern="**/test.yaml"

# Verbose mode (debug) - shows full delegation hierarchy
npm run eval:sdk -- --agent=openagent --pattern="**/test.yaml" --debug

Example Output (Non-Verbose Mode)

Running tests...

   ✓ Child agent completed (OpenAgent, 2.9s)

Running evaluator: approval-gate...

Example Output (Verbose Mode - Debug)

┌────────────────────────────────────────────────────────────┐
│ 🎯 PARENT: OpenAgent (ses_xxx...)                          │
└────────────────────────────────────────────────────────────┘
  🔧 TOOL: task
     ├─ subagent: simple-responder
     └─ Creating child session...

  ┌────────────────────────────────────────────────────────────┐
  │ 🎯 CHILD: simple-responder (ses_yyy...)                    │
  │    Parent: ses_xxx...                                      │
  │    Depth: 1                                                │
  └────────────────────────────────────────────────────────────┘
    🤖 Agent: AWESOME TESTING
  ✅ CHILD COMPLETE (2.9s)

✅ PARENT COMPLETE (20.9s)

See src/logging/README.md for API documentation.

Adding an Evaluator

  1. Create src/evaluators/my-evaluator.ts:
import { BaseEvaluator } from './base-evaluator.js';
import { TimelineEvent, SessionInfo, EvaluationResult } from '../types/index.js';

export class MyEvaluator extends BaseEvaluator {
  name = 'my-evaluator';
  description = 'What this evaluator checks';

  async evaluate(timeline: TimelineEvent[], sessionInfo: SessionInfo): Promise<EvaluationResult> {
    const checks = [];
    const violations = [];
    const evidence = [];

    // Your evaluation logic here
    const toolCalls = this.getToolCalls(timeline);
    
    // Example check
    const passed = toolCalls.length > 0;
    checks.push({
      name: 'has-tool-calls',
      passed,
      weight: 100,
      evidence: [this.createEvidence('tool-count', `Found ${toolCalls.length} tool calls`, {})]
    });

    if (!passed) {
      violations.push(this.createViolation(
        'no-tool-calls',
        'error',
        'No tool calls found',
        Date.now(),
        {}
      ));
    }

    return this.buildResult(this.name, checks, violations, evidence, {});
  }
}
  1. Register in test-runner.ts:
import { MyEvaluator } from '../evaluators/my-evaluator.js';

// In setupEvaluators():
this.evaluatorRunner = new EvaluatorRunner({
  evaluators: [
    // ... existing evaluators
    new MyEvaluator(),
  ],
});
  1. Add to test schema in test-case-schema.ts:
export const ExpectedViolationSchema = z.object({
  rule: z.enum([
    // ... existing rules
    'my-evaluator',
  ]),
  // ...
});

Development

# Install
npm install

# Build
npm run build

# Run tests
npm test

# Run SDK tests
npm run eval:sdk -- --agent=openagent --pattern="**/golden/*.yaml"

Key Types

interface TimelineEvent {
  timestamp: number;
  type: 'user_message' | 'assistant_message' | 'tool_call' | 'text';
  data: any;
}

interface EvaluationResult {
  evaluator: string;
  passed: boolean;
  score: number;
  violations: Violation[];
  evidence: Evidence[];
  checks: Check[];
}

interface Violation {
  type: string;
  severity: 'error' | 'warning' | 'info';
  message: string;
  timestamp: number;
  evidence?: any;
}

Base Evaluator Helpers

// Get all tool calls
const toolCalls = this.getToolCalls(timeline);

// Get specific tool calls
const bashCalls = this.getToolCallsByName(timeline, 'bash');

// Get assistant messages
const messages = this.getAssistantMessages(timeline);

// Get read tools (read, glob, grep, list)
const reads = this.getReadTools(timeline);

// Get execution tools (bash, write, edit, task)
const executions = this.getExecutionTools(timeline);

// Create violation
this.createViolation(type, severity, message, timestamp, evidence);

// Create evidence
this.createEvidence(type, description, data, timestamp?);

// Build result
this.buildResult(name, checks, violations, evidence, metadata);