summaryrefslogtreecommitdiff
path: root/scripts/lib/behavioral-record.js
blob: 70784bd079aa4108f1acffa73e64dfb9f3cc3040 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
'use strict';

const fs = require('fs');
const path = require('path');
const { createHash, randomUUID } = require('crypto');
const { isDeepStrictEqual } = require('util');
const { execFileSync } = require('child_process');

function digest(value) {
  return createHash('sha256').update(JSON.stringify(value)).digest('hex');
}

function writeJson(file, value) {
  // Never overwrite evidence or another attempt, even in concurrent runs.
  fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
}

function claudeVersion() {
  try {
    return execFileSync('claude', ['--version'], { encoding: 'utf8', timeout: 10000 }).trim();
  } catch {
    return null;
  }
}

function sha256(bytes) {
  return createHash('sha256').update(bytes).digest('hex');
}

// Every file staged for the executor, by its path under the staged root, with its digest.
function listStaged(root) {
  const files = [];
  const walk = (dir) => {
    for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
      const file = path.join(dir, entry.name);
      if (entry.isDirectory()) walk(file);
      else files.push({ path: path.relative(root, file).split(path.sep).join('/'), sha256: sha256(fs.readFileSync(file)) });
    }
  };
  walk(root);
  return files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
}

// The staged list holds the skill's SKILL.md, matching skill_text, and only files under
// the skill's directory or the root references/, each once.
function validStaged(staged, skillName, skillText) {
  if (!Array.isArray(staged)) return false;
  const prefix = `skills/${skillName}/`;
  const paths = staged.map((f) => f?.path);
  return staged.every((f) => f && typeof f.path === 'string' && /^[0-9a-f]{64}$/.test(f.sha256) &&
      (f.path.startsWith(prefix) || f.path.startsWith('references/')) && !f.path.split('/').includes('..')) &&
    new Set(paths).size === paths.length &&
    staged.find((f) => f.path === `${prefix}SKILL.md`)?.sha256 === sha256(skillText);
}

function saveRecord(base, evidence) {
  const file = `${base}.${randomUUID()}.record.json`;
  const record = { version: 1, sha256: digest(evidence), evidence };
  writeJson(file, record);
  return { file, record };
}

function validateEval(ev) {
  if (!ev || !Number.isInteger(ev.id) || typeof ev.prompt !== 'string' ||
      typeof ev.expected_output !== 'string' ||
      !['execution', 'dialogue'].includes(ev.kind || 'execution') ||
      (ev.files !== undefined && (!Array.isArray(ev.files) || ev.files.some(f => typeof f !== 'string'))) ||
      !Array.isArray(ev.expectations) || !ev.expectations.length ||
      ev.expectations.some(e => typeof e !== 'string' || !e.trim())) {
    throw new Error('Invalid behavioral eval in record or rubric');
  }
}

function task(ev) {
  const { expectations, expected_output, ...rest } = ev;
  return { ...rest, kind: ev.kind || 'execution', files: ev.files || [] };
}

function loadReplay(file, rubricFile) {
  const record = JSON.parse(fs.readFileSync(file, 'utf8'));
  if (record.version !== 1) throw new Error('Unsupported behavioral record version');
  const evidence = record.evidence;
  if (!evidence || digest(evidence) !== record.sha256) throw new Error('Record integrity check failed');
  validateEval(evidence.eval);
  if (typeof evidence.trace !== 'string' || typeof evidence.skill_text !== 'string' ||
      typeof evidence.skill_name !== 'string' || !evidence.run ||
      !validStaged(evidence.staged, evidence.skill_name, evidence.skill_text)) {
    throw new Error('Invalid behavioral record evidence');
  }
  const rubric = JSON.parse(fs.readFileSync(rubricFile, 'utf8'));
  const matches = Array.isArray(rubric.evals) ? rubric.evals.filter(e => e?.id === evidence.eval.id) : [];
  if (rubric.skill_name !== evidence.skill_name || matches.length !== 1) {
    throw new Error('Rubric must contain the recorded skill and exactly one matching eval ID');
  }
  const ev = matches[0];
  validateEval(ev);
  if (!isDeepStrictEqual(task(ev), task(evidence.eval))) {
    throw new Error('Regrade cannot change the recorded task; only expectations and expected_output may change');
  }
  return { record, ev };
}

function gradeRecorded(file, record, ev, model, historical, grade) {
  const attempt = {
    record_sha256: record.sha256,
    historical,
    rubric: ev,
    requested_model: model || null,
    grader_model: 'unknown',
    claude_version: claudeVersion(),
    timestamp: new Date().toISOString(),
  };
  let outcome;
  try {
    outcome = grade(record.evidence.trace, ev, model);
    Object.assign(attempt, { status: outcome.grading ? 'graded' : 'invalid', ...outcome });
  } catch (error) {
    attempt.status = 'error';
    attempt.error = error.message;
    if (error.stdout) attempt.raw = String(error.stdout);
    throw error;
  } finally {
    writeJson(`${file}.attempt-${randomUUID()}.json`, attempt);
  }
  return outcome;
}

function runRegrade(file, rubricFile, { dryRun, model }, grade) {
  const { record, ev } = loadReplay(file, rubricFile);
  console.log(`Historical regrade: ${record.evidence.skill_name} eval ${ev.id}; no executor run.`);
  console.log(`Grading the saved trace; the original run staged ${record.evidence.staged.length} file(s), listed in the record. This is not a fresh skill test.`);
  if (dryRun) return 0;
  const { grading, gradingError } = gradeRecorded(file, record, ev, model, true, grade);
  if (!grading) {
    console.error(`${gradingError}; raw output saved in the grading attempt.`);
    return 1;
  }
  console.log(`${grading.summary.passed}/${grading.summary.total} expectations passed; attempt saved beside ${file}`);
  return grading.summary.failed ? 1 : 0;
}

module.exports = { saveRecord, gradeRecorded, runRegrade, claudeVersion, validateEval, listStaged };