skillfit 0.10.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +10 -2
  2. package/README.zh-CN.md +10 -2
  3. package/dist/cli.js +19 -13
  4. package/dist/commands/bench.js +99 -91
  5. package/dist/commands/eval-component.js +8 -1
  6. package/dist/commands/eval-export.js +32 -6
  7. package/dist/commands/eval-export.test.js +165 -8
  8. package/dist/commands/eval-interruption.test.js +238 -0
  9. package/dist/commands/eval-preflight.js +61 -0
  10. package/dist/commands/eval-preflight.test.js +239 -0
  11. package/dist/commands/eval-report.js +44 -13
  12. package/dist/commands/eval-report.test.js +2 -2
  13. package/dist/commands/eval.js +81 -59
  14. package/dist/harness/eval-audit.js +3 -1
  15. package/dist/harness/eval-budget.test.js +4 -2
  16. package/dist/harness/eval-component.test.js +6 -6
  17. package/dist/harness/executors/api.js +10 -1
  18. package/dist/harness/executors/api.test.js +43 -0
  19. package/dist/harness/executors/cli.js +24 -3
  20. package/dist/harness/experiment-session.js +60 -9
  21. package/dist/harness/experiment-session.test.js +43 -1
  22. package/dist/harness/input-snapshot.js +150 -0
  23. package/dist/harness/interruption.js +48 -0
  24. package/dist/harness/interruption.test.js +31 -0
  25. package/dist/harness/runner.js +53 -15
  26. package/dist/harness/trigger.js +20 -4
  27. package/docs/bench-check-json.md +8 -1
  28. package/docs/eval-case-preflight.md +110 -0
  29. package/docs/eval-component.md +28 -0
  30. package/docs/eval-costs.md +9 -0
  31. package/docs/evaluation-input-snapshots.md +124 -0
  32. package/docs/evaluation-interruption.md +89 -0
  33. package/docs/evaluation-reports.md +49 -0
  34. package/docs/experiment-workflow.md +9 -2
  35. package/docs/first-real-eval.md +5 -2
  36. package/docs/growth-roadmap-2026-10.md +15 -10
  37. package/docs/metrics.md +31 -0
  38. package/docs/plans/2026-10-16-case-workflow-and-release.md +19 -0
  39. package/docs/releases/0.10.0-ci-registry-install.json +140 -0
  40. package/docs/releases/0.10.0-feature-smoke.json +22 -0
  41. package/docs/releases/0.10.0-feature-smoke.mjs +62 -0
  42. package/docs/releases/0.10.0-signatures.txt +7 -0
  43. package/docs/releases/0.10.0-verification.json +76 -0
  44. package/docs/releases/0.10.0.md +44 -8
  45. package/docs/releases/0.10.1-feature-smoke.mjs +95 -0
  46. package/docs/releases/0.10.1.md +38 -0
  47. package/docs/replay-packages.md +14 -5
  48. package/docs/schemas/eval-preflight.schema.json +57 -0
  49. package/docs/schemas/eval-result.schema.json +11 -0
  50. package/docs/sharing-results.md +5 -2
  51. package/package.json +1 -1
@@ -1,6 +1,8 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import { test } from 'node:test';
3
3
  import { ApiExecutor } from './api.js';
4
+ import { summarizeCosts } from '../costs.js';
5
+ import { spendingBudgetState } from '../eval-budget.js';
4
6
  function jsonResponse(body, status = 200) {
5
7
  return new Response(JSON.stringify(body), {
6
8
  status,
@@ -34,6 +36,47 @@ test('ApiExecutor throws on non-2xx responses', async () => {
34
36
  const executor = new ApiExecutor({ apiKey: 'k', fetchImpl });
35
37
  await assert.rejects(() => executor.run('hi', '/tmp'), /status 500/);
36
38
  });
39
+ test('API cache counts reach cost partitions and budget stop lines without double counting', async () => {
40
+ for (const cached of [0, 80, 100]) {
41
+ const fetchImpl = async () => jsonResponse({ choices: [{ message: { content: 'offline' } }],
42
+ usage: { prompt_tokens: 100, completion_tokens: 10, prompt_tokens_details: { cached_tokens: cached } } });
43
+ const result = await new ApiExecutor({ apiKey: 'offline-only', fetchImpl }).run('offline');
44
+ assert.deepEqual(result.tokens, { input: 100, output: 10, cachedInput: cached });
45
+ const record = { executorInvoked: true, passed: true, error: null, durationSeconds: 1, tokens: result.tokens, usageStatus: 'final' };
46
+ const costs = summarizeCosts({ baseline: [record], treatment: [] }, { baseline: [record], treatment: [] });
47
+ const metrics = costs.attempts.baseline.metrics;
48
+ assert.equal(metrics.input.knownTotal, 100);
49
+ assert.equal(metrics.cachedInput.knownTotal, cached);
50
+ assert.equal(metrics.uncachedInput.knownTotal, 100 - cached);
51
+ assert.equal(metrics.cachedInput.coverage.final, 1);
52
+ const state = spendingBudgetState({ input: 100, cachedInput: 1000, uncachedInput: 1000, output: 1000, durationSeconds: 1000 }, [record]);
53
+ assert.equal(state.incomplete.length, 0);
54
+ assert.ok(state.reached.includes('input'));
55
+ }
56
+ });
57
+ test('missing, malformed and incompatible API cache counts stay unknown rather than becoming zero', async () => {
58
+ const cases = [undefined, null, false, 'cache', [], {}, { cached_tokens: null }, { cached_tokens: '0' },
59
+ { cached_tokens: -1 }, { cached_tokens: 101 }, { cached_tokens: 0.5 }, { cached_tokens: Number.MAX_SAFE_INTEGER + 1 }];
60
+ for (const details of cases) {
61
+ const fetchImpl = async () => jsonResponse({ choices: [{ message: { content: 'offline' } }],
62
+ usage: { prompt_tokens: 100, completion_tokens: 10, prompt_tokens_details: details } });
63
+ const tokens = (await new ApiExecutor({ apiKey: 'offline-only', fetchImpl }).run('offline')).tokens;
64
+ assert.deepEqual(tokens, { input: 100, output: 10 });
65
+ const state = spendingBudgetState({ input: 1000, cachedInput: 1000, uncachedInput: 1000, output: 1000, durationSeconds: 1000 }, [{ executorInvoked: true, passed: true, error: null, durationSeconds: 1, tokens, usageStatus: 'final' }]);
66
+ assert.equal(state.reason, 'FINAL_USAGE_MISSING');
67
+ assert.ok(state.incomplete.includes('cachedInput'));
68
+ assert.equal(state.metrics.uncachedInput.coverage.unknown, 1);
69
+ }
70
+ });
71
+ test('cache counts without a valid input total cannot establish an API input partition', async () => {
72
+ for (const input of [undefined, null, '100', -1, 0.5]) {
73
+ const fetchImpl = async () => jsonResponse({ choices: [{ message: { content: 'offline' } }],
74
+ usage: { prompt_tokens: input, completion_tokens: 10, prompt_tokens_details: { cached_tokens: 0 } } });
75
+ const tokens = (await new ApiExecutor({ apiKey: 'offline-only', fetchImpl }).run('offline')).tokens;
76
+ assert.equal(tokens.cachedInput, undefined);
77
+ assert.equal(tokens.output, 10);
78
+ }
79
+ });
37
80
  test('ApiExecutor ignores usage objects that do not contain finite token counts', async () => {
38
81
  const fetchImpl = (async () => jsonResponse({
39
82
  choices: [{ message: { content: 'answer' } }],
@@ -7,6 +7,7 @@ import { probeKimiSessionUsage } from '../kimi-usage.js';
7
7
  import { probeCodexPartialUsage } from '../codex-usage.js';
8
8
  import { ExecutorFailure } from '../types.js';
9
9
  import { ExecutionDeadline } from '../execution-timing.js';
10
+ import { evaluationSignal } from '../interruption.js';
10
11
  export const DEFAULT_CLI_TIMEOUT_MS = 10 * 60 * 1000;
11
12
  const MAX_AGENT_OUTPUT_BYTES = 32 * 1024 * 1024;
12
13
  const DEFAULT_PROMPT_FILE = '_prompt.txt';
@@ -137,6 +138,9 @@ export class CliExecutor {
137
138
  };
138
139
  }
139
140
  run(prompt, workdir) {
141
+ const signal = evaluationSignal();
142
+ if (signal?.aborted)
143
+ return Promise.reject(new ExecutorFailure(String(signal.reason), { output: '' }, false));
140
144
  const startedAtMs = Date.now();
141
145
  let argv = this.argv;
142
146
  if (this.projectTrustConfigArg) {
@@ -195,7 +199,7 @@ export class CliExecutor {
195
199
  }
196
200
  return new ExecutorFailure(message, { ...result, usageStatus: 'partial' });
197
201
  };
198
- const stopMessage = () => overflow
202
+ const stopMessage = () => signal?.aborted ? signal.reason.message : overflow
199
203
  ? `"${command}" produced more than ${MAX_AGENT_OUTPUT_BYTES} bytes of output`
200
204
  : deadline.timingError ? `"${command}" execution timing anomaly: ${deadline.timingError}`
201
205
  : `"${command}" timed out after ${this.timeoutMs}ms`;
@@ -229,7 +233,13 @@ export class CliExecutor {
229
233
  checkDeadline();
230
234
  }, this.timeoutMs);
231
235
  const heartbeat = setInterval(() => checkDeadline(), deadline.heartbeatMs);
232
- const clearTimers = () => { clearTimeout(timer); clearInterval(heartbeat); clearTimeout(drainTimer); };
236
+ const onAbort = () => stopChild();
237
+ const clearTimers = () => {
238
+ clearTimeout(timer);
239
+ clearInterval(heartbeat);
240
+ clearTimeout(drainTimer);
241
+ signal?.removeEventListener('abort', onAbort);
242
+ };
233
243
  const take = (chunk, sink) => {
234
244
  checkDeadline();
235
245
  bytes += chunk.length;
@@ -253,6 +263,10 @@ export class CliExecutor {
253
263
  child.on('close', (code) => {
254
264
  checkDeadline(false);
255
265
  clearTimers();
266
+ if (signal?.aborted) {
267
+ rejectPromise(failure(stopMessage()));
268
+ return;
269
+ }
256
270
  if (overflow) {
257
271
  rejectPromise(failure(`"${command}" produced more than ${MAX_AGENT_OUTPUT_BYTES} bytes of output`));
258
272
  return;
@@ -287,12 +301,19 @@ export class CliExecutor {
287
301
  }
288
302
  resolvePromise(result);
289
303
  });
290
- if (this.promptVia === 'stdin') {
304
+ signal?.addEventListener('abort', onAbort, { once: true });
305
+ if (signal?.aborted)
306
+ onAbort();
307
+ if (this.promptVia === 'stdin' && !signal?.aborted) {
291
308
  // A child that exits before draining stdin makes the write fail (EPIPE on POSIX, EOF on
292
309
  // Windows). With no listener that surfaces as an uncaught exception rather than a rejection,
293
310
  // so the caller's catch never runs and the process dies mid-trial leaving a half-populated
294
311
  // run group behind. Reject instead, and kill the child so it cannot outlive the failure.
295
312
  child.stdin.on('error', (error) => {
313
+ // Killing the tree can close stdin too. Let close/the bounded drain
314
+ // retain parsed usage instead of replacing cancellation with EPIPE.
315
+ if (stopping)
316
+ return;
296
317
  clearTimers();
297
318
  deadline.observe();
298
319
  killTree(child);
@@ -1,5 +1,5 @@
1
1
  import { execFileSync } from 'node:child_process';
2
- import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, readdirSync, realpathSync, writeFileSync } from 'node:fs';
2
+ import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
@@ -8,6 +8,9 @@ import { parseFrontmatter } from '../frontmatter.js';
8
8
  import { hashFileSet, sha256File, sha256Text } from './hash.js';
9
9
  import { assertNativeDiffFile, assertNativeDiffWorkspace, NATIVE_DIFF_SNAPSHOT } from './native-diff.js';
10
10
  import { ExecutorFailure } from './types.js';
11
+ import { EvaluationInterrupted, evaluationSignal, throwIfEvaluationInterrupted } from './interruption.js';
12
+ import { freezeInputSnapshot, verifyInputSnapshot } from './input-snapshot.js';
13
+ import { loadBench } from './bench.js';
11
14
  function skillInventory(root) {
12
15
  if (!existsSync(root))
13
16
  return { root, entries: ['missing'] };
@@ -163,6 +166,7 @@ export class ExperimentSession {
163
166
  finished = false;
164
167
  guardFiles;
165
168
  nativeDiffTool;
169
+ inputSnapshot;
166
170
  constructor(options) {
167
171
  this.nativeDiffTool = options.details.nativeDiffTool !== undefined;
168
172
  this.guardFiles = (options.guardFiles ?? []).map(file => ({ ...file, path: resolve(file.path) }));
@@ -256,17 +260,37 @@ export class ExperimentSession {
256
260
  agent: options.agent ?? null, cliVersion, configuredSettings: configured, servedModel: 'unrecorded',
257
261
  plannedCalls: this.plannedCalls, maxCalls: this.maxCalls, workspaces: this.workspaces, workspaceAliases: this.workspaceAliases,
258
262
  inputs: this.inputs, guardFiles: this.guardFiles, configurations: this.configs, skillInventories: this.inventories, warnings, details: options.details };
259
- const bytes = JSON.stringify(plan, null, 2) + '\n';
260
- this.planSha256 = sha256Text(bytes);
261
- mkdirSync(this.groupDir, { recursive: true });
262
- writeFileSync(join(this.groupDir, '_plan.json'), bytes, { flag: 'wx' });
263
- if (sha256File(join(this.groupDir, '_plan.json')) !== this.planSha256)
264
- throw new Error('Frozen plan write verification failed.');
263
+ mkdirSync(dirname(this.groupDir), { recursive: true });
264
+ // Claim exclusively; a failed setup removes only the fresh directory we own.
265
+ mkdirSync(this.groupDir);
266
+ try {
267
+ this.inputSnapshot = freezeInputSnapshot(this.groupDir, this.inputs, this.guardFiles);
268
+ if (loadBench(join(this.groupDir, '_inputs/bench')).contentSha256 !== options.bench.contentSha256)
269
+ throw new Error('Sealed bench does not match the planned content hash; keep Git metadata and run outputs outside bench inputs.');
270
+ for (const input of this.inputs)
271
+ if (pin(input.label, input.root, input.exclude).sha256 !== input.sha256)
272
+ throw new Error(`Frozen ${input.label} input changed while sealing snapshots.`);
273
+ for (const file of this.guardFiles)
274
+ if (sha256File(file.path) !== file.sha256)
275
+ throw new Error(`Frozen ${file.label} changed while sealing snapshots.`);
276
+ throwIfEvaluationInterrupted();
277
+ const bytes = JSON.stringify({ ...plan, inputSnapshot: this.inputSnapshot }, null, 2) + '\n';
278
+ this.planSha256 = sha256Text(bytes);
279
+ writeFileSync(join(this.groupDir, '_plan.json'), bytes, { flag: 'wx' });
280
+ if (sha256File(join(this.groupDir, '_plan.json')) !== this.planSha256)
281
+ throw new Error('Frozen plan write verification failed.');
282
+ }
283
+ catch (error) {
284
+ rmSync(this.groupDir, { recursive: true, force: true });
285
+ throw error;
286
+ }
265
287
  }
266
288
  check() {
267
289
  if (this.stopReason)
268
290
  throw new Error(this.stopReason);
269
291
  try {
292
+ throwIfEvaluationInterrupted();
293
+ verifyInputSnapshot(this.groupDir, { inputs: this.inputs, guardFiles: this.guardFiles, inputSnapshot: this.inputSnapshot });
270
294
  if (this.nativeDiffTool) {
271
295
  assertNativeDiffFile(join(this.groupDir, NATIVE_DIFF_SNAPSHOT));
272
296
  for (const workdir of this.workspaces)
@@ -299,6 +323,15 @@ export class ExperimentSession {
299
323
  throw error;
300
324
  }
301
325
  }
326
+ /** Only this fresh session may hand its prepared directory to an engine. */
327
+ assertPrepared() {
328
+ if (this.finished || this.callsStarted !== 0 ||
329
+ readdirSync(this.groupDir).sort().join() !== '_inputs,_inputs.json,_plan.json' ||
330
+ sha256File(join(this.groupDir, '_plan.json')) !== this.planSha256) {
331
+ throw new Error(`Run group directory already exists or preparation changed: ${this.groupDir}`);
332
+ }
333
+ verifyInputSnapshot(this.groupDir, { inputs: this.inputs, guardFiles: this.guardFiles, inputSnapshot: this.inputSnapshot });
334
+ }
302
335
  wrap(executor, role) {
303
336
  return { describe: () => executor.describe(), run: async (prompt, workdir) => {
304
337
  try {
@@ -323,14 +356,23 @@ export class ExperimentSession {
323
356
  }
324
357
  catch {
325
358
  if (role === 'judge')
326
- throw new Error(this.stopReason);
359
+ throw new ExecutorFailure(this.stopReason, result);
327
360
  return { ...result, guardError: this.stopReason };
328
361
  }
329
362
  return result;
330
363
  }
331
364
  catch (error) {
332
365
  if (!this.stopReason)
333
- this.stopReason = `${role} executor failed; inspect the per-trial error receipt. No further calls.`;
366
+ this.stopReason = evaluationSignal()?.aborted
367
+ ? evaluationSignal().reason.message
368
+ : `${role} executor failed; inspect the per-trial error receipt. No further calls.`;
369
+ if (role === 'judge' && evaluationSignal()?.aborted) {
370
+ const result = error instanceof ExecutorFailure ? error.result : null;
371
+ writeFileSync(join(this.groupDir, `_interrupted-judge-${call}.json`), JSON.stringify({
372
+ schemaVersion: 1, call, role, error: error.message, result,
373
+ scope: 'Interrupted judge output and available usage only; separate judge spending is not a complete primary-agent cost total.',
374
+ }, null, 2) + '\n', { flag: 'wx' });
375
+ }
334
376
  if (this.callsFinished < call) {
335
377
  this.callsFinished++;
336
378
  appendFileSync(ledger, JSON.stringify({ event: 'failed', call, at: new Date().toISOString() }) + '\n');
@@ -354,6 +396,15 @@ export class ExperimentSession {
354
396
  if (this.finished)
355
397
  return;
356
398
  this.finished = true;
399
+ const interruption = evaluationSignal()?.reason;
400
+ if (interruption instanceof EvaluationInterrupted) {
401
+ if (!this.stopReason)
402
+ this.stopReason = interruption.message;
403
+ writeFileSync(join(this.groupDir, '_interruption.json'), JSON.stringify({
404
+ schemaVersion: 1, signal: interruption.signalName, receivedAt: interruption.receivedAt,
405
+ exitCode: interruption.exitCode, automaticRetry: false,
406
+ }, null, 2) + '\n', { flag: 'wx' });
407
+ }
357
408
  if (error && !this.stopReason)
358
409
  this.stopReason = 'Experiment setup or execution stopped; inspect the command error and retained receipts.';
359
410
  this.settle();
@@ -9,6 +9,7 @@ import { ExperimentSession, normalizeProjectTrust, validateCallBudget } from './
9
9
  import { sha256File } from './hash.js';
10
10
  import { runEval } from '../commands/eval.js';
11
11
  import { runBenchCheck } from '../commands/bench.js';
12
+ import { packageFiles } from './replay-package.js';
12
13
  function setup(t) {
13
14
  const root = mkdtempSync(join(tmpdir(), 'skillfit-session-'));
14
15
  t.after(() => rmSync(root, { recursive: true, force: true }));
@@ -19,7 +20,7 @@ function setup(t) {
19
20
  writeFileSync(join(skill, 'SKILL.md'), '---\nname: candidate\ndescription: offline fixture\n---\nInspect boundaries.\n');
20
21
  writeFileSync(join(benchDir, 'fixture', 'index.js'), 'module.exports = 1;\n');
21
22
  writeFileSync(join(benchDir, 'prompt.md'), 'Fix the cache.\n');
22
- writeFileSync(join(benchDir, 'verify.mjs'), 'process.exit(0);\n');
23
+ writeFileSync(join(benchDir, 'verify.mjs'), "import{existsSync,readFileSync}from'node:fs';import{join}from'node:path';const output=join(process.argv[2],'_output.md');process.exit(existsSync(output)&&readFileSync(output,'utf8').trim()?0:1);\n");
23
24
  writeFileSync(join(benchDir, 'bench.json'), JSON.stringify({ schemaVersion: 1, name: 'session-test', tasks: [
24
25
  { id: 'one', fixture: 'fixture', prompt: 'prompt.md', verifier: 'node verify.mjs', shouldTrigger: true },
25
26
  ] }));
@@ -88,6 +89,45 @@ test('a changed frozen input retains returned output but blocks subsequent calls
88
89
  assert.equal(calls, 1);
89
90
  assert.equal(session.summary().status, 'stopped');
90
91
  });
92
+ test('input snapshots exist and are bound before dispatch; modifying one stops further calls with usage retained', async (t) => {
93
+ const s = setup(t), session = new ExperimentSession(s.options);
94
+ const plan = JSON.parse(readFileSync(join(s.groupDir, '_plan.json'), 'utf8'));
95
+ const snapshot = JSON.parse(readFileSync(join(s.groupDir, '_inputs.json'), 'utf8'));
96
+ assert.equal(plan.inputSnapshot.sha256, sha256File(join(s.groupDir, '_inputs.json')));
97
+ assert.deepEqual(snapshot.entries.map((entry) => entry.label).sort(), ['bench', 'implementation', 'target']);
98
+ const files = packageFiles(join(s.groupDir, '_inputs'));
99
+ assert.equal(plan.inputSnapshot.cost.files, files.length + 1);
100
+ assert.equal(plan.inputSnapshot.cost.bytes, files.reduce((sum, file) => sum + readFileSync(join(s.groupDir, '_inputs', file)).length, 0) + readFileSync(join(s.groupDir, '_inputs.json')).length);
101
+ assert.equal(plan.inputSnapshot.cost.modelCalls, 0);
102
+ assert.ok(plan.inputSnapshot.cost.durationMs >= 0);
103
+ let calls = 0;
104
+ const guarded = session.wrap({ ...s.executor, run: async () => {
105
+ calls++;
106
+ assert.equal(readFileSync(join(s.groupDir, '_inputs/target/SKILL.md'), 'utf8'), readFileSync(join(s.skill, 'SKILL.md'), 'utf8'));
107
+ writeFileSync(join(s.groupDir, '_inputs/target/SKILL.md'), 'changed snapshot');
108
+ return { output: 'retained', tokens: { input: 12, output: 3 } };
109
+ } }, 'agent');
110
+ const result = await guarded.run('first', s.root);
111
+ assert.match(result.guardError, /snapshot hash mismatch/);
112
+ assert.deepEqual(result.tokens, { input: 12, output: 3 });
113
+ await assert.rejects(guarded.run('partner', s.root), /snapshot hash mismatch/);
114
+ assert.equal(calls, 1);
115
+ session.finish();
116
+ assert.equal(session.summary().status, 'stopped');
117
+ });
118
+ test('source drift during snapshot setup fails before dispatch and removes only its fresh output', async (t) => {
119
+ const s = setup(t);
120
+ let calls = 0;
121
+ const runsRoot = join(s.root, 'drift'), group = join(runsRoot, 'saved');
122
+ mkdirSync(runsRoot);
123
+ writeFileSync(join(runsRoot, 'kept'), 'existing sibling');
124
+ await assert.rejects(runEval({ skillPath: s.skill, bench: s.benchDir, executor: { ...s.executor, run: async () => { calls++; return { output: 'done' }; } },
125
+ judgeExecutor: null, agent: 'codex', trials: 1, dryRun: false, yes: true, runsRoot, runGroup: 'saved', log: () => { },
126
+ sessionOptions: { homeDir: s.root, env: {}, versionProbe: () => { writeFileSync(join(s.benchDir, 'prompt.md'), 'changed after fingerprinting'); return 'fake 1.0'; } } }), /changed.*snapshot|snapshot.*changed/i);
127
+ assert.equal(calls, 0);
128
+ assert.ok(!existsSync(group));
129
+ assert.equal(readFileSync(join(runsRoot, 'kept'), 'utf8'), 'existing sibling');
130
+ });
91
131
  test('executor failure stops further actual calls and keeps a failure receipt without secrets', async (t) => {
92
132
  const s = setup(t);
93
133
  let calls = 0;
@@ -121,6 +161,8 @@ test('temporary profile config is pinned, planned trust additions are allowed, m
121
161
  const plan = readFileSync(join(s.groupDir, '_plan.json'), 'utf8');
122
162
  assert.equal(plan.includes('PRIVATE_SECRET'), false);
123
163
  assert.match(plan, /"model_reasoning_effort": "high"/);
164
+ const snapshot = JSON.parse(readFileSync(join(s.groupDir, '_inputs.json'), 'utf8'));
165
+ assert.deepEqual(snapshot.entries.map((entry) => entry.label).sort(), ['bench', 'implementation', 'target'], 'private agent configuration remains fingerprint-only');
124
166
  writeFileSync(config, readFileSync(config, 'utf8') + `\n[projects.${JSON.stringify(s.options.workspaces[0])}]\ntrust_level = "trusted"\n`);
125
167
  session.check();
126
168
  writeFileSync(config, readFileSync(config, 'utf8').replace('"offline"', '"changed"'));
@@ -0,0 +1,150 @@
1
+ import assert from 'node:assert/strict';
2
+ import { chmodSync, lstatSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
3
+ import { isAbsolute, join, relative, sep } from 'node:path';
4
+ import { hashFileSet, sha256File } from './hash.js';
5
+ import { packageFiles, packageMember } from './replay-package.js';
6
+ const ALIASES = new Map([['bench', 'bench'], ['target', 'target'], ['implementation', 'implementation'], ['baseline Skill', 'baseline-skill']]);
7
+ export const INPUT_SNAPSHOT_POLICY = { schemaVersion: 1, required: true, status: 'pending' };
8
+ /** Includes empty directories; excludes Git metadata and the current native run. */
9
+ export function inputDirectories(root, exclude) {
10
+ const result = [];
11
+ const walk = (prefix) => {
12
+ for (const entry of readdirSync(join(root, prefix), { withFileTypes: true })) {
13
+ const path = prefix ? `${prefix}/${entry.name}` : entry.name;
14
+ const rel = exclude ? relative(exclude, join(root, path)) : '..';
15
+ if (entry.name === '.git' || (exclude && !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`)))
16
+ continue;
17
+ if (entry.isSymbolicLink())
18
+ throw new Error(`Unpinned symbolic link in input snapshot: ${path}`);
19
+ if (entry.isDirectory()) {
20
+ result.push(path);
21
+ walk(path);
22
+ }
23
+ else if (!entry.isFile())
24
+ throw new Error(`Unsupported input snapshot entry: ${path}`);
25
+ }
26
+ };
27
+ walk('');
28
+ return result.sort();
29
+ }
30
+ function selectedInputs(inputs) {
31
+ assert.ok(Array.isArray(inputs), 'Native input fingerprints are missing.');
32
+ const selected = inputs.filter(input => input && ALIASES.has(input.label));
33
+ for (const label of ['bench', 'target', 'implementation'])
34
+ assert.equal(selected.filter(input => input.label === label).length, 1, `Missing or repeated snapshot input: ${label}`);
35
+ assert.equal(new Set(selected.map(input => input.label)).size, selected.length, 'Repeated snapshot input.');
36
+ for (const input of selected) {
37
+ assert.ok(typeof input.root === 'string' && Array.isArray(input.files) && input.files.every(path => typeof path === 'string'));
38
+ assert.deepEqual([...new Set(input.files)].sort(), input.files, 'Snapshot file list must be sorted and unique.');
39
+ assert.match(input.sha256, /^[a-f0-9]{64}$/);
40
+ }
41
+ return selected;
42
+ }
43
+ function requestInput(guards) {
44
+ if (guards === undefined)
45
+ return undefined;
46
+ assert.ok(Array.isArray(guards), 'Invalid native request guards.');
47
+ const requests = guards.filter(file => file?.label === 'component request');
48
+ assert.ok(requests.length <= 1, 'Repeated component request guard.');
49
+ if (requests[0]) {
50
+ assert.equal(typeof requests[0].path, 'string');
51
+ assert.match(requests[0].sha256, /^[a-f0-9]{64}$/);
52
+ }
53
+ return requests[0];
54
+ }
55
+ /** Called only in an exclusively claimed fresh run, before publishing _plan.json. */
56
+ export function freezeInputSnapshot(run, inputs, guards) {
57
+ const started = performance.now(), entries = [];
58
+ let bytes = 0, files = 0;
59
+ const copy = (source, target) => {
60
+ const content = readFileSync(source);
61
+ writeFileSync(target, content, { flag: 'wx' });
62
+ chmodSync(target, lstatSync(source).mode & 0o777);
63
+ bytes += content.length;
64
+ files++;
65
+ };
66
+ mkdirSync(join(run, '_inputs'));
67
+ for (const input of selectedInputs(inputs)) {
68
+ const label = ALIASES.get(input.label), path = `_inputs/${label}`, root = join(run, path);
69
+ const directories = inputDirectories(input.root, input.exclude);
70
+ mkdirSync(root);
71
+ for (const dir of directories)
72
+ mkdirSync(join(root, dir), { recursive: true });
73
+ for (const file of input.files) {
74
+ const source = packageMember(input.root, file);
75
+ copy(source, join(root, file));
76
+ }
77
+ if (hashFileSet(root, input.files) !== input.sha256)
78
+ throw new Error(`Input changed while sealing snapshot: ${label}`);
79
+ assert.deepEqual(inputDirectories(input.root, input.exclude), directories, `Input directories changed while sealing snapshot: ${label}`);
80
+ const executableFiles = input.files.filter(file => (lstatSync(join(root, file)).mode & 0o111) !== 0);
81
+ entries.push({ label, path, files: [...input.files], directories, executableFiles, sha256: input.sha256 });
82
+ }
83
+ const request = requestInput(guards);
84
+ if (request) {
85
+ const path = '_inputs/request.json';
86
+ if (!lstatSync(request.path).isFile())
87
+ throw new Error('Input request must be a regular file.');
88
+ copy(request.path, join(run, path));
89
+ if (sha256File(join(run, path)) !== request.sha256)
90
+ throw new Error('Request changed while sealing snapshot.');
91
+ entries.push({ label: 'request', path, files: [], directories: [], executableFiles: [], sha256: request.sha256 });
92
+ }
93
+ writeFileSync(join(run, '_inputs.json'), JSON.stringify({ schemaVersion: 1, kind: 'skillfit.eval-inputs', entries }, null, 2) + '\n', { flag: 'wx' });
94
+ bytes += lstatSync(join(run, '_inputs.json')).size;
95
+ files++;
96
+ const snapshot = { schemaVersion: 1, indexPath: '_inputs.json', sha256: sha256File(join(run, '_inputs.json')),
97
+ cost: { modelCalls: 0, durationMs: Math.round(performance.now() - started), bytes, files } };
98
+ verifyInputSnapshot(run, { inputs, guardFiles: guards, inputSnapshot: snapshot });
99
+ snapshot.cost.durationMs = Math.round(performance.now() - started);
100
+ return snapshot;
101
+ }
102
+ /** A declared snapshot never falls back to mutable originals when damaged. */
103
+ export function verifyInputSnapshot(run, plan) {
104
+ if (plan.inputSnapshot === undefined)
105
+ return null; // Historical run: retain the old recovery path.
106
+ const descriptor = plan.inputSnapshot;
107
+ assert.ok(descriptor && descriptor.schemaVersion === 1 && descriptor.indexPath === '_inputs.json', 'Invalid input snapshot descriptor.');
108
+ const indexPath = packageMember(run, '_inputs.json');
109
+ assert.equal(sha256File(indexPath), descriptor.sha256, 'Input snapshot index changed.');
110
+ const index = JSON.parse(readFileSync(indexPath, 'utf8'));
111
+ assert.ok(index.schemaVersion === 1 && index.kind === 'skillfit.eval-inputs' && Array.isArray(index.entries), 'Invalid input snapshot index.');
112
+ const inputs = selectedInputs(plan.inputs), request = requestInput(plan.guardFiles);
113
+ const expectedLabels = [...inputs.map(input => ALIASES.get(input.label)), ...(request ? ['request'] : [])].sort();
114
+ assert.deepEqual(index.entries.map(entry => entry.label).sort(), expectedLabels, 'Input snapshot coverage changed.');
115
+ assert.ok(lstatSync(join(run, '_inputs')).isDirectory(), 'Input snapshot root must be a regular directory.');
116
+ const expectedFiles = [], expectedDirectories = [], roots = new Map();
117
+ for (const entry of index.entries) {
118
+ const path = entry.label === 'request' ? '_inputs/request.json' : `_inputs/${entry.label}`;
119
+ assert.equal(entry.path, path, 'Unsafe input snapshot root.');
120
+ if (entry.label === 'request') {
121
+ assert.equal(entry.sha256, request.sha256);
122
+ assert.equal(sha256File(packageMember(run, path)), request.sha256, 'Input request snapshot changed.');
123
+ assert.deepEqual(entry.files, []);
124
+ assert.deepEqual(entry.directories, []);
125
+ assert.deepEqual(entry.executableFiles, []);
126
+ expectedFiles.push('request.json');
127
+ roots.set(entry.label, join(run, path));
128
+ continue;
129
+ }
130
+ const input = inputs.find(input => ALIASES.get(input.label) === entry.label);
131
+ assert.deepEqual(entry.files, input.files, 'Input snapshot file coverage changed.');
132
+ assert.equal(entry.sha256, input.sha256);
133
+ const root = join(run, path);
134
+ assert.ok(lstatSync(root).isDirectory(), 'Input snapshot root must be a regular directory.');
135
+ for (const file of entry.files)
136
+ packageMember(root, file);
137
+ assert.deepEqual(packageFiles(root), entry.files, 'Input snapshot inventory changed.');
138
+ assert.deepEqual(inputDirectories(root), entry.directories, 'Input snapshot directories changed.');
139
+ assert.ok(Array.isArray(entry.executableFiles) && entry.executableFiles.every(file => entry.files.includes(file)), 'Invalid snapshot executable file list.');
140
+ if (process.platform !== 'win32')
141
+ assert.deepEqual(entry.files.filter(file => (lstatSync(join(root, file)).mode & 0o111) !== 0), entry.executableFiles, 'Input snapshot executable modes changed.');
142
+ assert.equal(hashFileSet(root, entry.files), input.sha256, `Input snapshot hash mismatch: ${entry.label}`);
143
+ expectedFiles.push(...entry.files.map(file => `${entry.label}/${file}`));
144
+ roots.set(entry.label, root);
145
+ expectedDirectories.push(entry.label, ...entry.directories.map(dir => `${entry.label}/${dir}`));
146
+ }
147
+ assert.deepEqual(packageFiles(join(run, '_inputs')), expectedFiles.sort(), 'Input snapshot inventory changed.');
148
+ assert.deepEqual(inputDirectories(join(run, '_inputs')), expectedDirectories.sort(), 'Input snapshot directories changed.');
149
+ return { entries: index.entries, roots };
150
+ }
@@ -0,0 +1,48 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ export class EvaluationInterrupted extends Error {
3
+ signalName;
4
+ receivedAt = new Date().toISOString();
5
+ exitCode;
6
+ constructor(signalName) {
7
+ super(`Evaluation interrupted by ${signalName}; no further calls. Retained receipts must not be retried or replaced automatically.`);
8
+ this.signalName = signalName;
9
+ this.name = 'EvaluationInterrupted';
10
+ this.exitCode = signalName === 'SIGINT' ? 130 : 143;
11
+ }
12
+ }
13
+ // The cancellation belongs to this asynchronous evaluation, including its git,
14
+ // verifier and judge work. Imports, previews and unrelated commands install no handlers.
15
+ const evaluations = new AsyncLocalStorage();
16
+ export function evaluationSignal() {
17
+ return evaluations.getStore();
18
+ }
19
+ export function throwIfEvaluationInterrupted() {
20
+ evaluationSignal()?.throwIfAborted();
21
+ }
22
+ export async function withEvaluationInterrupts(operation) {
23
+ if (evaluationSignal())
24
+ return operation();
25
+ const controller = new AbortController();
26
+ const interrupt = (signal) => {
27
+ if (controller.signal.aborted)
28
+ return;
29
+ const reason = new EvaluationInterrupted(signal);
30
+ process.exitCode = reason.exitCode;
31
+ process.stderr.write(`${signal}: stopping evaluation processes and sealing retained records…\n`);
32
+ controller.abort(reason);
33
+ };
34
+ const onInt = () => interrupt('SIGINT'), onTerm = () => interrupt('SIGTERM');
35
+ process.on('SIGINT', onInt);
36
+ process.on('SIGTERM', onTerm);
37
+ try {
38
+ return await evaluations.run(controller.signal, async () => {
39
+ const result = await operation();
40
+ throwIfEvaluationInterrupted();
41
+ return result;
42
+ });
43
+ }
44
+ finally {
45
+ process.removeListener('SIGINT', onInt);
46
+ process.removeListener('SIGTERM', onTerm);
47
+ }
48
+ }
@@ -0,0 +1,31 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import { evaluationSignal, withEvaluationInterrupts } from './interruption.js';
4
+ const counts = () => [process.listenerCount('SIGINT'), process.listenerCount('SIGTERM')];
5
+ test('normal and failed operations restore signal handlers and asynchronous context', async () => {
6
+ const before = counts();
7
+ assert.equal(evaluationSignal(), undefined);
8
+ assert.equal(await withEvaluationInterrupts(async () => {
9
+ assert.ok(evaluationSignal());
10
+ await Promise.resolve();
11
+ assert.ok(evaluationSignal());
12
+ return 'done';
13
+ }), 'done');
14
+ assert.deepEqual(counts(), before);
15
+ assert.equal(evaluationSignal(), undefined);
16
+ await assert.rejects(withEvaluationInterrupts(async () => { throw new Error('offline setup failed'); }), /offline setup failed/);
17
+ assert.deepEqual(counts(), before);
18
+ assert.equal(evaluationSignal(), undefined);
19
+ });
20
+ test('concurrent operations keep distinct cancellation contexts and clean up all handlers', async () => {
21
+ const before = counts();
22
+ const signals = await Promise.all([1, 2].map(() => withEvaluationInterrupts(async () => {
23
+ const signal = evaluationSignal();
24
+ await new Promise(resolve => setImmediate(resolve));
25
+ assert.equal(evaluationSignal(), signal);
26
+ return signal;
27
+ })));
28
+ assert.notEqual(signals[0], signals[1]);
29
+ assert.deepEqual(counts(), before);
30
+ assert.equal(evaluationSignal(), undefined);
31
+ });