@staix/agent-research 0.3.1 → 0.5.0

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.
@@ -0,0 +1,97 @@
1
+ import { calculate, inputs, type CommitResult } from "./investigate.ts";
2
+ import { foldIdeas, readCategories, type Expectation, type Idea } from "./ideas.ts";
3
+ import { observedMetric, sampleMean } from "./selection.ts";
4
+ import type { Attempt, AttemptStatus } from "./attempts.ts";
5
+
6
+ export const DEFAULT_WINDOW = 5, MAX_WINDOW = 1000;
7
+ export type Outcome = "hit" | "miss" | "unmeasured";
8
+ export interface ReportCommit { commit: string; delta: number | null; pairedSeeds: number; measured: boolean; eligible: boolean; reason: string }
9
+ export interface ReportPrediction { metric: string; expect: Expectation; minDelta?: number; delta: number | null; outcome?: Outcome }
10
+ export interface ReportIdea {
11
+ id: string; category?: string; bundle: number; confounded: boolean; state: Idea["state"]; commits: ReportCommit[];
12
+ attempts: Record<AttemptStatus, number>; timing: "prospective" | "post-hoc"; measuredCommit: string | null; primaryDelta: number | null;
13
+ predictions: ReportPrediction[]; unpredictedRegressions: string[];
14
+ }
15
+ export interface ReportCategory { name: string; ideas: number; measured: number; hits: number; bestRecentDelta: number | null; noRecentGain: boolean }
16
+ export interface IdeaReport {
17
+ v: 1; advisory: true; run: string; metric: { name: string; unit: string; direction: "max" | "min" }; baseline: string; minSeeds: number; minDelta: number;
18
+ window: number; inputsSha256: string; ideas: ReportIdea[]; categories: ReportCategory[]; confounded: string[];
19
+ search: { measured: number; bestDelta: number | null; stalled: boolean; untried: string[] };
20
+ }
21
+
22
+ function bad(reason: string): never { throw new Error(`idea report: ${reason}`); }
23
+ const best = (values: (number | null)[]) => values.reduce<number | null>((top, v) => v === null ? top : top === null || v > top ? v : top, null);
24
+
25
+ /** Direction-adjusted paired mean delta for any declared metric over the investigation's own pairs. */
26
+ function metricDelta(row: CommitResult, metric: { name: string; unit: string; direction: "max" | "min" }, byId: Map<string, Attempt>): number | null {
27
+ if (!row.pairs.length) return null;
28
+ const values: number[] = [], reference: number[] = [];
29
+ for (const pair of row.pairs) {
30
+ const a = byId.get(pair.attempt), b = byId.get(pair.baselineAttempt);
31
+ const x = a && observedMetric(a, metric), y = b && observedMetric(b, metric);
32
+ if (x === undefined || y === undefined) return null;
33
+ values.push(x); reference.push(y);
34
+ }
35
+ const mean = sampleMean(values)!, ref = sampleMean(reference)!, delta = metric.direction === "max" ? mean - ref : ref - mean;
36
+ return Number.isFinite(delta) ? delta : null;
37
+ }
38
+
39
+ /** Read-only, advisory fold over the ledger and the investigation pairing; it writes nothing and gates nothing. */
40
+ export function ideaReport(dirArg: string, options: { run?: string; window?: number } = {}): IdeaReport {
41
+ const window = options.window ?? DEFAULT_WINDOW;
42
+ if (!Number.isSafeInteger(window) || window < 1 || window > MAX_WINDOW) bad(`window: integer in 1..${MAX_WINDOW} required; pass --window N`);
43
+ const input = inputs(dirArg), { rule, protocol, events, attempts, dir } = input;
44
+ if (options.run !== undefined && options.run !== rule.run) bad(`run ${options.run} is not the selection run ${rule.run}; pass --run ${rule.run} or set a selection for that run`);
45
+ const result = calculate(input), primary = result.metric, byId = new Map(attempts.map(a => [a.id, a]));
46
+ const rows = new Map([result.baseline, ...result.candidates].map(row => [row.commit, row]));
47
+ const baselineReady = result.baseline.eligible;
48
+ const firstStart = new Map<string, number>(), added = new Map<string, number>();
49
+ events.forEach((event, index) => {
50
+ if (event.type === "attempt.started" && typeof event.data.commit === "string" && !firstStart.has(event.data.commit)) firstStart.set(event.data.commit, index);
51
+ if (event.type === "idea.added" && event.data.idea && typeof (event.data.idea as { id?: unknown }).id === "string") added.set((event.data.idea as { id: string }).id, index);
52
+ });
53
+ const ideas = foldIdeas(events).map((idea): ReportIdea => {
54
+ const commits = idea.commits.map((commit): ReportCommit => {
55
+ const row = rows.get(commit), pairs = row?.pairs.length ?? 0, measured = !!row && commit !== rule.baseline.commit && baselineReady && pairs >= rule.minSeeds && row.delta !== null;
56
+ return { commit, delta: row && commit !== rule.baseline.commit ? row.delta : null, pairedSeeds: pairs, measured, eligible: !!row?.eligible && commit !== rule.baseline.commit, reason: row ? row.reason : "no-attempts" };
57
+ });
58
+ const totals = { running: 0, succeeded: 0, failed: 0, cancelled: 0, unknown: 0 };
59
+ for (const commit of idea.commits) { const row = rows.get(commit); if (row) for (const status of Object.keys(totals) as AttemptStatus[]) totals[status] += row.attempts[status].length; }
60
+ const starts = idea.commits.map(c => firstStart.get(c)).filter((i): i is number => i !== undefined);
61
+ const timing = starts.length && Math.min(...starts) < added.get(idea.id)! ? "post-hoc" : "prospective";
62
+ const latest = [...commits].reverse().find(c => c.measured), row = latest ? rows.get(latest.commit)! : undefined;
63
+ const deltaFor = (name: string): number | null => {
64
+ if (!row) return null;
65
+ const metric = protocol.metrics.find(m => m.name === name);
66
+ return !metric ? null : name === primary.name ? row.delta : metricDelta(row, metric, byId);
67
+ };
68
+ const predictions = (idea.predicts ?? []).map((p): ReportPrediction => {
69
+ const delta = deltaFor(p.metric), threshold = p.metric === primary.name && p.expect === "no-change" ? rule.minDelta : p.minDelta ?? 0;
70
+ const hit = delta === null ? undefined : p.expect === "improve" ? delta > 0 && delta >= threshold : p.expect === "regress" ? delta < 0 && -delta >= (p.minDelta ?? 0) : Math.abs(delta) < threshold;
71
+ const outcome: Outcome | undefined = timing === "post-hoc" ? undefined : hit === undefined ? "unmeasured" : hit ? "hit" : "miss";
72
+ return { metric: p.metric, expect: p.expect, ...(p.minDelta !== undefined ? { minDelta: p.minDelta } : {}), delta, ...(outcome ? { outcome } : {}) };
73
+ });
74
+ const regressAllowed = new Set((idea.predicts ?? []).filter(p => p.expect === "regress").map(p => p.metric));
75
+ const unpredictedRegressions = row ? protocol.metrics.filter(m => !regressAllowed.has(m.name)).filter(m => { const d = deltaFor(m.name); return d !== null && d < 0; }).map(m => m.name) : [];
76
+ const bundle = idea.bundle ?? 1;
77
+ return { id: idea.id, ...(idea.category !== undefined ? { category: idea.category } : {}), bundle, confounded: bundle > 1, state: idea.state, commits, attempts: totals, timing,
78
+ measuredCommit: latest?.commit ?? null, primaryDelta: row ? row.delta : null, predictions, unpredictedRegressions };
79
+ });
80
+ const clean = ideas.filter(i => !i.confounded), measured = clean.filter(i => i.measuredCommit !== null);
81
+ const names = [...new Set(clean.flatMap(i => i.category === undefined ? [] : [i.category]))].sort();
82
+ const categories = names.map((name): ReportCategory => {
83
+ const members = clean.filter(i => i.category === name), done = members.filter(i => i.measuredCommit !== null);
84
+ const recent = best(done.slice(-window).map(i => i.primaryDelta));
85
+ return { name, ideas: members.length, measured: done.length, hits: members.reduce((n, i) => n + i.predictions.filter(p => p.outcome === "hit").length, 0),
86
+ bestRecentDelta: recent, noRecentGain: done.length > 0 && recent !== null && recent <= 0 };
87
+ });
88
+ const eligibleDelta = (i: ReportIdea) => i.commits.find(c => c.commit === i.measuredCommit)?.eligible ? i.primaryDelta : null;
89
+ const before = best(measured.slice(0, -window).map(eligibleDelta)), last = best(measured.slice(-window).map(eligibleDelta));
90
+ const stalled = measured.length >= window && (last === null || last <= Math.max(before ?? 0, 0));
91
+ const declared = readCategories(dir), tried = new Set(measured.map(i => i.category));
92
+ return {
93
+ v: 1, advisory: true, run: rule.run, metric: primary, baseline: rule.baseline.commit, minSeeds: rule.minSeeds, minDelta: rule.minDelta, window,
94
+ inputsSha256: result.inputsSha256, ideas, categories, confounded: ideas.filter(i => i.confounded).map(i => i.id),
95
+ search: { measured: measured.length, bestDelta: best(measured.map(eligibleDelta)), stalled, untried: (declared ?? []).filter(c => !tried.has(c)) },
96
+ };
97
+ }
package/src/exp/ideas.ts CHANGED
@@ -1,10 +1,18 @@
1
- import { boundedText, commit, onlyKeys, openStudy, plain, readLedger, requireExperiment, type Actor, type LedgerEvent } from "../study.ts";
1
+ import { boundedText, commit, onlyKeys, openStudy, plain, readLedger, readTextBounded, requireExperiment, sha256, type Actor, type LedgerEvent } from "../study.ts";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
2
4
  import { listAttempts } from "./attempts.ts";
5
+ import { readProtocol } from "./protocol.ts";
6
+ import { readSelection } from "./selection.ts";
3
7
 
4
8
  export const MAX_IDEAS = 1000, MAX_DECISION_ATTEMPTS = 200;
5
- export interface IdeaInput { id: string; title: string; hypothesis: string; parent?: string; commit?: string }
9
+ export const MAX_PREDICTIONS = 4, MAX_BUNDLE = 16, MAX_CATEGORIES = 32, CATEGORIES_BYTES = 8192;
10
+ export type Expectation = "improve" | "no-change" | "regress";
11
+ export interface Prediction { metric: string; expect: Expectation; minDelta?: number }
12
+ export interface IdeaPlanning { category?: string; bundle?: number; predicts?: Prediction[] }
13
+ export interface IdeaInput extends IdeaPlanning { id: string; title: string; hypothesis: string; parent?: string; commit?: string }
6
14
  export interface IdeaDecision { decision: "refine" | "pivot"; reason: string; attempts: string[]; commit?: string; cause?: string; retryWhen?: string }
7
- export interface Idea { id: string; title: string; hypothesis: string; parent?: string; commits: string[]; state: "open" | "pivoted"; decisions: IdeaDecision[] }
15
+ export interface Idea extends IdeaPlanning { id: string; title: string; hypothesis: string; parent?: string; commits: string[]; state: "open" | "pivoted"; decisions: IdeaDecision[] }
8
16
  const recovery = "; correct the idea input and retry ares idea add or ares idea decide";
9
17
  function bad(reason: string): never { throw new Error(`idea: ${reason}${recovery}`); }
10
18
  function name(raw: unknown, field: string): string {
@@ -15,11 +23,84 @@ function commitId(raw: unknown): string {
15
23
  if (typeof raw !== "string" || !/^[a-fA-F0-9]{40}$/.test(raw)) bad("commit: full 40-hex SHA required");
16
24
  return raw.toLowerCase();
17
25
  }
26
+ function prediction(raw: unknown, strict: boolean): Prediction {
27
+ if (!plain(raw)) bad("predicts: objects with metric and expect required");
28
+ if (strict) onlyKeys(raw, ["metric", "expect", "minDelta"], "idea prediction");
29
+ const metric = boundedText(raw.metric, "idea prediction metric", 128);
30
+ if (raw.expect !== "improve" && raw.expect !== "no-change" && raw.expect !== "regress") bad("predicts.expect: use improve, no-change or regress");
31
+ if (raw.minDelta !== undefined && (typeof raw.minDelta !== "number" || !Number.isFinite(raw.minDelta) || raw.minDelta < 0)) bad("predicts.minDelta: finite number >= 0 required in the metric's unit");
32
+ return { metric, expect: raw.expect, ...(raw.minDelta !== undefined ? { minDelta: raw.minDelta as number } : {}) };
33
+ }
34
+ /** Optional planning fields; absent fields are omitted so older ideas fold to identical objects. */
35
+ function planning(raw: Record<string, unknown>, strict: boolean): IdeaPlanning {
36
+ const out: IdeaPlanning = {};
37
+ if (raw.category !== undefined) out.category = name(raw.category, "category");
38
+ if (raw.bundle !== undefined) {
39
+ if (!Number.isSafeInteger(raw.bundle) || (raw.bundle as number) < 1 || (raw.bundle as number) > MAX_BUNDLE) bad(`bundle: integer in 1..${MAX_BUNDLE} required (independent changes in the commit)`);
40
+ out.bundle = raw.bundle as number;
41
+ }
42
+ if (raw.predicts !== undefined) {
43
+ if (!Array.isArray(raw.predicts) || !raw.predicts.length || raw.predicts.length > MAX_PREDICTIONS) bad(`predicts: 1..${MAX_PREDICTIONS} predictions required`);
44
+ const predicts = raw.predicts.map(p => prediction(p, strict));
45
+ if (new Set(predicts.map(p => p.metric)).size !== predicts.length) bad("predicts: one prediction per metric");
46
+ out.predicts = predicts;
47
+ }
48
+ return out;
49
+ }
18
50
  function validateIdea(raw: unknown, strict: boolean): IdeaInput {
19
51
  if (!plain(raw)) bad("JSON object required");
20
- if (strict) onlyKeys(raw, ["id", "title", "hypothesis", "parent", "commit"], "idea");
52
+ if (strict) onlyKeys(raw, ["id", "title", "hypothesis", "parent", "commit", "category", "bundle", "predicts"], "idea");
21
53
  return { id: name(raw.id, "id"), title: boundedText(raw.title, "idea.title", 500), hypothesis: boundedText(raw.hypothesis, "idea.hypothesis", 4000),
22
- ...(raw.parent !== undefined ? { parent: name(raw.parent, "parent") } : {}), ...(raw.commit !== undefined ? { commit: commitId(raw.commit) } : {}) };
54
+ ...(raw.parent !== undefined ? { parent: name(raw.parent, "parent") } : {}), ...(raw.commit !== undefined ? { commit: commitId(raw.commit) } : {}), ...planning(raw, strict) };
55
+ }
56
+ export function categoriesPath(dir: string): string { return join(dir, "design", "idea-categories.json"); }
57
+ function validateCategories(raw: unknown): { v: 1; categories: string[] } {
58
+ if (!plain(raw)) bad("categories: JSON object {v:1,categories:[...]} required");
59
+ onlyKeys(raw, ["v", "categories"], "idea categories");
60
+ if (raw.v !== 1) bad("categories.v: 1 required");
61
+ if (!Array.isArray(raw.categories) || !raw.categories.length || raw.categories.length > MAX_CATEGORIES) bad(`categories: 1..${MAX_CATEGORIES} names required`);
62
+ const categories = raw.categories.map(c => name(c, "category"));
63
+ if (new Set(categories).size !== categories.length) bad("categories: duplicate name; list each category once");
64
+ return { v: 1, categories };
65
+ }
66
+ /** The study-local vocabulary, or undefined when none is declared. It is a planning aid outside the design seal. */
67
+ export function readCategories(dir: string): string[] | undefined {
68
+ const file = categoriesPath(dir);
69
+ if (!existsSync(file)) return undefined;
70
+ let text: string;
71
+ try { text = readTextBounded(file, CATEGORIES_BYTES); }
72
+ catch { bad(`design/idea-categories.json: unreadable, non-regular, invalid UTF-8 or larger than ${CATEGORIES_BYTES} bytes; restore a valid file within that bound`); }
73
+ let raw: unknown;
74
+ try { raw = JSON.parse(text); } catch { bad("design/idea-categories.json: invalid JSON; restore the last valid vocabulary"); }
75
+ return validateCategories(raw).categories;
76
+ }
77
+ /** Caller holds the study lock; identical bytes record nothing. */
78
+ export function setCategories(dir: string, raw: unknown, actor: Actor): { categories: string[]; sha256: string; changed: boolean } {
79
+ return safe(() => {
80
+ requireExperiment(openStudy(dir).study);
81
+ const value = validateCategories(raw), text = JSON.stringify(value, null, 2) + "\n", hash = sha256(text), file = categoriesPath(dir);
82
+ let previous: string | undefined;
83
+ // A valid new vocabulary may replace an unreadable or invalid one.
84
+ if (existsSync(file)) { try { previous = readTextBounded(file, CATEGORIES_BYTES); } catch { previous = undefined; } }
85
+ const changed = previous !== text;
86
+ if (changed) commit(dir, [[file, text, CATEGORIES_BYTES]], [{ actor, type: "idea.categories.set", data: { sha256: hash, count: value.categories.length } }]);
87
+ return { categories: value.categories, sha256: hash, changed };
88
+ });
89
+ }
90
+ function checkPlanning(dir: string, input: IdeaInput): void {
91
+ if (input.category !== undefined) {
92
+ const declared = readCategories(dir);
93
+ if (declared && !declared.includes(input.category)) bad(`category ${input.category} is not declared; use one of ${declared.join(", ")}`);
94
+ }
95
+ if (input.predicts) {
96
+ const protocol = readProtocol(dir);
97
+ if (!protocol) bad("predicts: protocol missing; run ares protocol before predicting metrics, or omit predicts");
98
+ const names = protocol.metrics.map(m => m.name);
99
+ for (const p of input.predicts) if (!names.includes(p.metric)) bad(`predicts.metric ${p.metric} is not declared; use one of ${names.join(", ")}`);
100
+ // Only the primary metric has a selection margin; elsewhere no-change needs its own tolerance or it can never hit.
101
+ const primary = readSelection(dir, protocol)?.metric;
102
+ for (const p of input.predicts) if (p.expect === "no-change" && p.minDelta === undefined && p.metric !== primary) bad(`predicts ${p.metric}: no-change on a non-primary metric needs minDelta; add minDelta in that metric's unit`);
103
+ }
23
104
  }
24
105
  function pivotContext(raw: Record<string, unknown>, strict: boolean): Pick<IdeaDecision, "cause" | "retryWhen"> {
25
106
  if (strict && raw.decision !== "pivot" && (raw.cause !== undefined || raw.retryWhen !== undefined)) bad("cause and retryWhen are pivot-only; omit --cause and --retry-when for refine");
@@ -66,7 +147,9 @@ export function foldIdeas(events: LedgerEvent[]): Idea[] {
66
147
  if (ideas.size >= MAX_IDEAS) bad(`limit ${MAX_IDEAS} reached; start a new study for more ideas`);
67
148
  if (input.parent !== undefined && !ideas.has(input.parent)) bad(`parent ${input.parent} does not exist; add its parent idea first`);
68
149
  claim(ideas.values(), input.id, input.commit);
69
- ideas.set(input.id, { id: input.id, title: input.title, hypothesis: input.hypothesis, ...(input.parent !== undefined ? { parent: input.parent } : {}), commits: input.commit ? [input.commit] : [], state: "open", decisions: [] });
150
+ const { category, bundle, predicts } = input;
151
+ ideas.set(input.id, { id: input.id, title: input.title, hypothesis: input.hypothesis, ...(input.parent !== undefined ? { parent: input.parent } : {}), commits: input.commit ? [input.commit] : [], state: "open", decisions: [],
152
+ ...(category !== undefined ? { category } : {}), ...(bundle !== undefined ? { bundle } : {}), ...(predicts !== undefined ? { predicts } : {}) });
70
153
  } else if (event.type === "idea.decided") {
71
154
  const id = name(event.data.id, "id"), input = validateDecision(event.data, false), target = ideas.get(id);
72
155
  if (!target) bad(`unknown id ${id}; add the idea before deciding`);
@@ -90,6 +173,7 @@ export function addIdea(dir: string, raw: unknown, actor: Actor): Idea {
90
173
  if (ideas.length >= MAX_IDEAS) bad(`limit ${MAX_IDEAS} reached; start a new study for more ideas`);
91
174
  if (input.parent !== undefined && !ideas.some(i => i.id === input.parent)) bad(`parent ${input.parent} does not exist; add its parent idea first`);
92
175
  claim(ideas, input.id, input.commit);
176
+ checkPlanning(dir, input);
93
177
  const added = commit(dir, [], [{ actor, type: "idea.added", data: { idea: input } }]);
94
178
  return foldIdeas([...events, ...added]).find(i => i.id === input.id)!;
95
179
  });
@@ -6,13 +6,14 @@ import { join } from "node:path";
6
6
  import { assertWritable, commit, openStudy, plain, readLedger, readTextBounded, requireExperiment, sha256, type Actor, type LedgerEvent } from "../study.ts";
7
7
  import { listAttempts, type Attempt, type AttemptStatus } from "./attempts.ts";
8
8
  import { protocolHash, readProtocol } from "./protocol.ts";
9
- import { readSelection, selectionHash } from "./selection.ts";
9
+ import { evaluateSelectionConstraints, observedMetric, readSelection, sampleMean, selectionHash, type ConstraintResult } from "./selection.ts";
10
+ import { readBoundCalibration } from "./calibrate.ts";
10
11
 
11
12
  export const INVESTIGATE_BYTES = 1_048_576;
12
- export type NoWinner = "no-baseline" | "baseline-seeds" | "no-candidate" | "below-margin" | "tie";
13
+ export type NoWinner = "no-baseline" | "baseline-seeds" | "no-candidate" | "below-margin" | "tie" | "constraints";
13
14
  type Exclusion = "other-protocol" | "before-selection" | "missing-start-event" | "undeclared-seed" | "later-success" | "reserved-seed";
14
15
  export interface Sample { seed: number; attempt: string; value: number }
15
- export interface CommitResult {
16
+ export interface CommitResult extends Omit<ConstraintResult, "reason"> {
16
17
  commit: string; idea?: string; attempts: Record<AttemptStatus, string[]>; perSeed: Sample[];
17
18
  pairedSeeds: number[]; pairs: { seed: number; attempt: string; baselineAttempt: string; value: number; baselineValue: number }[];
18
19
  mean: number | null; baselineMean: number | null; delta: number | null; eligible: boolean; reason: string;
@@ -23,6 +24,7 @@ export interface InvestigateResult {
23
24
  baseline: CommitResult; candidates: CommitResult[];
24
25
  totals: { attempts: number; byStatus: Record<AttemptStatus, number>; countedSuccesses: number; excluded: number };
25
26
  excluded: { id: string; commit: string; seed: number; status: AttemptStatus; reasons: Exclusion[] }[];
27
+ calibration?: { recommendedMinDelta: number; minDelta: number; belowNoise: boolean };
26
28
  winner: { commit: string; idea?: string; attempts: string[]; mean: number; delta: number } | null; reason?: NoWinner;
27
29
  }
28
30
  const recover = "; inspect ares attempt show and restore the last valid study inputs before ares investigate show";
@@ -32,21 +34,11 @@ function canonical(raw: unknown): string {
32
34
  if (plain(raw)) return `{${Object.keys(raw).sort().map(k => `${JSON.stringify(k)}:${canonical(raw[k])}`).join(",")}}`;
33
35
  return JSON.stringify(raw) ?? "null";
34
36
  }
35
- function mean(values: number[]): number | null {
36
- if (!values.length) return null;
37
- const total = values.reduce((sum, value) => sum + value, 0);
38
- if (Number.isFinite(total)) return total / values.length;
39
- const scale = Math.max(...values.map(Math.abs));
40
- if (!scale) return 0;
41
- // Normalize before summing so finite evaluator values never overflow their mean.
42
- return Math.max(-1, Math.min(1, values.reduce((sum, v) => sum + v / scale / values.length, 0))) * scale;
43
- }
44
37
  export function metricValue(attempt: Attempt, metric: InvestigateResult["metric"]): number {
45
38
  if (!Array.isArray(attempt.metrics)) bad(`attempt ${attempt.id}: primary metrics missing`);
46
- const values = attempt.metrics.filter(m => m?.name === metric.name);
47
- const value = values[0];
48
- if (values.length !== 1 || !value || value.unit !== metric.unit || value.provenance !== "ares-observed" || typeof value.value !== "number" || !Number.isFinite(value.value)) bad(`attempt ${attempt.id}: primary metric missing, duplicate, non-finite or unvalidated`);
49
- return value.value;
39
+ const value = observedMetric(attempt, metric);
40
+ if (value === undefined) bad(`attempt ${attempt.id}: primary metric missing, duplicate, non-finite or unvalidated`);
41
+ return value;
50
42
  }
51
43
  export interface PairedSamples {
52
44
  pairedSeeds: number[]; pairs: { seed: number; attempt: string; referenceAttempt: string; value: number; referenceValue: number }[];
@@ -58,7 +50,7 @@ export function pairSamples(samples: Sample[], reference: Sample[], direction: "
58
50
  const base = reference.find(b => b.seed === sample.seed);
59
51
  return base ? [{ seed: sample.seed, attempt: sample.attempt, referenceAttempt: base.attempt, value: sample.value, referenceValue: base.value }] : [];
60
52
  });
61
- const candidateMean = mean(pairs.map(p => p.value)), referenceMean = mean(pairs.map(p => p.referenceValue));
53
+ const candidateMean = sampleMean(pairs.map(p => p.value)), referenceMean = sampleMean(pairs.map(p => p.referenceValue));
62
54
  const delta = candidateMean === null || referenceMean === null ? null : direction === "max" ? candidateMean - referenceMean : referenceMean - candidateMean;
63
55
  if (delta !== null && !Number.isFinite(delta)) bad(`commit ${commit}: primary metric delta overflows; rescale the metric's unit in a new protocol and rerun attempts`);
64
56
  return { pairedSeeds: pairs.map(p => p.seed), pairs, mean: candidateMean, referenceMean, delta };
@@ -66,7 +58,9 @@ export function pairSamples(samples: Sample[], reference: Sample[], direction: "
66
58
  function empty(commit: string): CommitResult {
67
59
  return { commit, attempts: { running: [], succeeded: [], failed: [], cancelled: [], unknown: [] }, perSeed: [], pairedSeeds: [], pairs: [], mean: null, baselineMean: null, delta: null, eligible: false, reason: "no-counted-success" };
68
60
  }
69
- function inputs(dirArg: string) {
61
+ export type InvestigationInputs = ReturnType<typeof inputs>;
62
+ /** Shared by investigate and the read-only idea report so both see the same pairs. */
63
+ export function inputs(dirArg: string) {
70
64
  const { dir, study } = openStudy(dirArg); requireExperiment(study);
71
65
  const protocol = readProtocol(dir);
72
66
  if (!protocol) throw new Error("investigate: protocol missing; run ares protocol before selecting an investigation rule");
@@ -82,7 +76,7 @@ function inputs(dirArg: string) {
82
76
  const reserved = readFinalSeeds(dir, protocol)?.seeds ?? [], reservedSha = finalSeedsHash(dir, protocol);
83
77
  return { dir, protocol, rule, ruleSha, events, cutoff, hash, metric, attempts, reserved, reservedSha };
84
78
  }
85
- function calculate(input: ReturnType<typeof inputs>): InvestigateResult {
79
+ export function calculate(input: InvestigationInputs): InvestigateResult {
86
80
  const { rule, ruleSha, events, cutoff, hash, metric, attempts, protocol, reserved, reservedSha } = input;
87
81
  const ideas = foldIdeas(events), owners = new Map<string, string>();
88
82
  // The journal enforces exactly one idea owner for any associated commit.
@@ -118,16 +112,24 @@ function calculate(input: ReturnType<typeof inputs>): InvestigateResult {
118
112
  for (const row of rows.values()) { const idea = owners.get(row.commit); if (idea !== undefined) row.idea = idea; }
119
113
  const baseline = rows.get(rule.baseline.commit)!;
120
114
  for (const row of rows.values()) row.perSeed.sort((a, b) => a.seed - b.seed);
121
- baseline.mean = mean(baseline.perSeed.map(s => s.value)); baseline.baselineMean = baseline.mean;
115
+ baseline.mean = sampleMean(baseline.perSeed.map(s => s.value)); baseline.baselineMean = baseline.mean;
122
116
  baseline.pairedSeeds = baseline.perSeed.map(s => s.seed); baseline.delta = baseline.mean === null ? null : 0;
123
117
  baseline.eligible = baseline.perSeed.length >= rule.minSeeds;
124
118
  baseline.reason = !baseline.perSeed.length ? "no-baseline" : baseline.eligible ? "baseline" : "baseline-seeds";
119
+ const attemptsById = new Map(attempts.map(attempt => [attempt.id, attempt]));
125
120
  const candidates = [...rows.values()].filter(row => row !== baseline).sort((a, b) => a.commit.localeCompare(b.commit));
126
121
  for (const row of candidates) {
127
122
  const paired = pairSamples(row.perSeed, baseline.perSeed, metric.direction, row.commit);
128
123
  row.pairedSeeds = paired.pairedSeeds; row.mean = paired.mean; row.baselineMean = paired.referenceMean; row.delta = paired.delta;
129
124
  row.pairs = paired.pairs.map(p => ({ seed: p.seed, attempt: p.attempt, baselineAttempt: p.referenceAttempt, value: p.value, baselineValue: p.referenceValue }));
130
125
  row.reason = !baseline.perSeed.length ? "no-baseline" : !baseline.eligible ? "baseline-seeds" : !row.perSeed.length ? "no-counted-success" : row.pairs.length < rule.minSeeds ? "candidate-seeds" : row.delta! <= 0 || row.delta! < rule.minDelta ? "below-margin" : "eligible";
126
+ if (baseline.eligible && paired.pairs.length >= rule.minSeeds && paired.delta !== null && rule.v === 2 && (rule.guards?.length || rule.cost)) {
127
+ const { reason, ...details } = evaluateSelectionConstraints(rule, protocol, paired.pairs.map(pair => ({
128
+ attempt: attemptsById.get(pair.attempt)!, baseline: attemptsById.get(pair.referenceAttempt)!,
129
+ })), paired.delta);
130
+ Object.assign(row, details);
131
+ if (reason) row.reason = reason;
132
+ }
131
133
  row.eligible = row.reason === "eligible";
132
134
  }
133
135
  const eligible = candidates.filter(row => row.eligible).sort((a, b) => b.delta! - a.delta!);
@@ -135,14 +137,15 @@ function calculate(input: ReturnType<typeof inputs>): InvestigateResult {
135
137
  if (!baseline.perSeed.length) reason = "no-baseline";
136
138
  else if (!baseline.eligible) reason = "baseline-seeds";
137
139
  else if (!candidates.some(row => row.pairedSeeds.length >= rule.minSeeds)) reason = "no-candidate";
138
- else if (!eligible.length) reason = "below-margin";
140
+ else if (!eligible.length) reason = candidates.some(row => /^(?:guard[-:]|cost-)/.test(row.reason)) ? "constraints" : "below-margin";
139
141
  else if (eligible.length > 1 && eligible[0]!.delta === eligible[1]!.delta) reason = "tie";
140
142
  else { const row = eligible[0]!; winner = { commit: row.commit, ...(row.idea !== undefined ? { idea: row.idea } : {}), attempts: row.pairs.map(p => p.attempt), mean: row.mean!, delta: row.delta! }; }
143
+ const calibration = rule.v === 2 ? readBoundCalibration(input.dir, rule, protocol) : undefined;
141
144
  const result: InvestigateResult = {
142
145
  v: 1, run: rule.run, ruleSha256: ruleSha, protocolHash: hash,
143
146
  inputsSha256: sha256(canonical({ ruleSha, protocolHash: hash, ...(reservedSha !== undefined ? { finalSeedsSha256: reservedSha } : {}), cutoff, ideas: sha256(canonical(ideas)), attempts: ordered.map(a => ({ record: sha256(canonical(a)), start: starts.get(a.id)?.index ?? null })) })),
144
147
  metric, baseline, candidates, totals: { attempts: attempts.length, byStatus, countedSuccesses: [...rows.values()].reduce((n, r) => n + r.perSeed.length, 0), excluded: excluded.length }, excluded,
145
- winner, ...(reason ? { reason } : {}),
148
+ winner, ...(reason ? { reason } : {}), ...(calibration === undefined ? {} : { calibration }),
146
149
  };
147
150
  assertWritable(JSON.stringify(result, null, 2) + "\n", INVESTIGATE_BYTES, "investigate result; archive this study and use a new bounded run");
148
151
  return result;
@@ -8,8 +8,11 @@ import { commit, openStudy, plain, readBytesBounded, readJsonFile, readTextBound
8
8
 
9
9
  export interface Limits { cpus: number; memoryMb: number; pidsLimit: number; wallSeconds: number; gpus: number }
10
10
  export interface ProtocolInput { path?: string; sha256: string; mount: { candidate?: string; evaluator?: string } }
11
+ /** Deterministic only: exact evaluator-only input copies and declared literals, never a model decision. */
12
+ export interface ProtocolScreen { evaluatorInputs?: true; literals?: string[] }
11
13
  export interface Protocol {
12
14
  v: 1; method: string; inputs?: Record<string, ProtocolInput>;
15
+ screen?: ProtocolScreen;
13
16
  candidate: { image: string; command: string[]; env?: Record<string, string> };
14
17
  evaluator: { image: string; command: string[] };
15
18
  metrics: { name: string; unit: string; direction: "max" | "min" }[];
@@ -23,6 +26,7 @@ export function validateProtocolDefinition(raw: unknown): ProtocolDefinition {
23
26
  return validateProtocol(raw);
24
27
  }
25
28
  export const METRIC_LIMIT = 100;
29
+ export const SCREEN_LITERALS = 64, SCREEN_LITERAL_MIN_BYTES = 8, SCREEN_LITERAL_BYTES = 200;
26
30
  export const PROTOCOL_BYTES = 65_536, TASK_FILES = 500, TASK_BYTES = 64 * 1024 * 1024, TASK_DIRECTORIES = 1000;
27
31
  export const LIMIT_BOUNDS = { cpus: [0.1, 256], memoryMb: [16, 1_048_576], pidsLimit: [1, 65_536], wallSeconds: [1, 604_800], gpus: [0, 64] } as const;
28
32
  function object(raw: unknown, keys: string[], what: string): Record<string, unknown> {
@@ -95,12 +99,32 @@ function protocolInputs(raw: unknown, stored: boolean): Record<string, ProtocolI
95
99
  }
96
100
  return Object.fromEntries(result);
97
101
  }
102
+ /** A declared screen is closed and deterministic: no warning mode, no inferred material. */
103
+ function screenField(raw: unknown): ProtocolScreen {
104
+ const value = object(raw, ["evaluatorInputs", "literals"], "protocol.screen"), result: ProtocolScreen = {};
105
+ if (value.evaluatorInputs !== undefined) {
106
+ if (value.evaluatorInputs !== true) throw new Error("protocol.screen.evaluatorInputs: true or omitted required; the screen has no warning mode, so omit the field instead of disabling it");
107
+ result.evaluatorInputs = true;
108
+ }
109
+ if (value.literals !== undefined) {
110
+ const literals = array(value.literals, "protocol.screen.literals", SCREEN_LITERALS).map((item, index) => {
111
+ const text = literal(item, `protocol.screen.literals[${index}]`, SCREEN_LITERAL_BYTES), bytes = Buffer.byteLength(text);
112
+ if (bytes < SCREEN_LITERAL_MIN_BYTES) throw new Error(`protocol.screen.literals[${index}]: at least ${SCREEN_LITERAL_MIN_BYTES} UTF-8 bytes required; declare a longer fixed string`);
113
+ if (bytes > SCREEN_LITERAL_BYTES) throw new Error(`protocol.screen.literals[${index}]: at most ${SCREEN_LITERAL_BYTES} UTF-8 bytes allowed; shorten that fixed string`);
114
+ return text;
115
+ });
116
+ if (new Set(literals).size !== literals.length) throw new Error("protocol.screen.literals: duplicate string; declare each fixed string once");
117
+ result.literals = literals;
118
+ }
119
+ if (!Object.keys(result).length) throw new Error("protocol.screen: empty screen; declare evaluatorInputs, a literals list, or omit protocol.screen");
120
+ return result;
121
+ }
98
122
  /** Public configuration always requires executor-local locators for declared inputs. */
99
123
  export function validateProtocol(raw: unknown): Protocol { return protocolShape(raw, false); }
100
124
  /** Frozen attempt records carry identities only, never executor-host locators. */
101
125
  export function validateStoredProtocol(raw: unknown): Protocol { return protocolShape(raw, true); }
102
126
  function protocolShape(raw: unknown, stored: boolean): Protocol {
103
- const p = object(raw, ["v", "method", "candidate", "evaluator", "metrics", "seeds", "limits", "network", "budget", "inputs"], "protocol");
127
+ const p = object(raw, ["v", "method", "candidate", "evaluator", "metrics", "seeds", "limits", "network", "budget", "inputs", "screen"], "protocol");
104
128
  if (p.v !== 1) throw new Error("protocol.v: unsupported version; this executor supports v1 only; use a compatible ares release for stage protocols, keeping the original definition unchanged");
105
129
  if (p.network !== "none") throw new Error('protocol.network: network access is unsupported; set protocol.network to "none"');
106
130
  const limitsRaw = object(p.limits, Object.keys(LIMIT_BOUNDS), "protocol.limits");
@@ -120,6 +144,7 @@ function protocolShape(raw: unknown, stored: boolean): Protocol {
120
144
  maxGpuHours: number(budget.maxGpuHours, "budget.maxGpuHours", 0, 64_000_000, false),
121
145
  } };
122
146
  if (p.inputs !== undefined) protocol.inputs = protocolInputs(p.inputs, stored);
147
+ if (p.screen !== undefined) protocol.screen = screenField(p.screen);
123
148
  if (Buffer.byteLength(JSON.stringify(protocol, null, 2) + "\n") > PROTOCOL_BYTES) throw new Error(`protocol: too large; reduce the formatted protocol to at most ${PROTOCOL_BYTES} bytes`);
124
149
  return protocol;
125
150
  }
@@ -0,0 +1,83 @@
1
+ import { hashExecutorInputBlobs, spawnRunner, type Executor, type ProcessRunner, type ProcessResult } from "./executor.ts";
2
+ import { canonical, type ProtocolInput, type ProtocolScreen } from "./protocol.ts";
3
+ import { sha256 } from "../study.ts";
4
+
5
+ export interface ScreenHit { rule: string; path: string; line?: number }
6
+ export interface ScreenSummary { rules: string[]; sha256: string }
7
+ /** Directory inputs are screened file by file; above this count the screen refuses instead of vouching partially. */
8
+ export const SCREEN_FILES = 20_000, SCREEN_OUTPUT_BYTES = 1_048_576, SCREEN_HITS = 16;
9
+
10
+ function passed(result: ProcessResult): boolean { return result.exitCode === 0 && !result.timedOut && !result.truncated; }
11
+ function git(repo: string, args: string[], runner: ProcessRunner): Promise<ProcessResult> {
12
+ return runner({ command: "git", args: ["-C", repo, ...args], timeoutMs: 300_000, maxOutputBytes: SCREEN_OUTPUT_BYTES });
13
+ }
14
+ function gitFailure(step: string): Error {
15
+ return new Error(`attempt screen: Git ${step} failed; check --repo and that --commit names an existing commit, then retry ares attempt run`);
16
+ }
17
+ /** Object ids only: the commit's file bytes are never read on this host. */
18
+ async function treeBlobs(repo: string, commit: string, runner: ProcessRunner): Promise<Map<string, string[]>> {
19
+ const format = await git(repo, ["rev-parse", "--show-object-format"], runner);
20
+ if (!passed(format)) throw gitFailure("object format");
21
+ // A sha-256 repository issues 64-hex blob ids, so an input's sha-1 blob id could never match.
22
+ if (format.stdout.trim() !== "sha1") throw new Error("attempt screen: evaluator inputs cannot be compared in a repository whose object format is not sha-1; screen the declared literals only, or use a sha-1 candidate repository");
23
+ const listing = await git(repo, ["ls-tree", "-r", "-z", "--full-tree", commit], runner);
24
+ if (listing.truncated) throw new Error(`attempt screen: candidate commit lists more files than the screen reads (${SCREEN_OUTPUT_BYTES} bytes of git ls-tree); screen the declared literals only, or screen a smaller commit`);
25
+ if (!passed(listing)) throw gitFailure("tree listing");
26
+ const blobs = new Map<string, string[]>();
27
+ for (const entry of listing.stdout.split("\0")) {
28
+ const tab = entry.indexOf("\t");
29
+ if (tab < 0) continue;
30
+ const [, type, oid] = entry.slice(0, tab).split(" ");
31
+ if (type !== "blob" || oid === undefined || !/^[a-f0-9]{40}$/.test(oid)) continue;
32
+ const paths = blobs.get(oid) ?? [];
33
+ paths.push(entry.slice(tab + 1)); blobs.set(oid, paths);
34
+ }
35
+ return blobs;
36
+ }
37
+ /** Verbatim search only: every hit is a fixed string, so transformed material passes unguarded. */
38
+ async function literalPaths(repo: string, commit: string, value: string, runner: ProcessRunner): Promise<string[]> {
39
+ const result = await git(repo, ["grep", "--no-color", "-a", "-F", "-l", "-z", "-e", value, commit, "--"], runner);
40
+ if (result.exitCode === 1 && !result.truncated && !result.timedOut) return [];
41
+ if (!passed(result)) throw gitFailure("literal search");
42
+ const prefix = `${commit}:`;
43
+ return result.stdout.split("\0").filter(Boolean).map(entry => entry.startsWith(prefix) ? entry.slice(prefix.length) : entry).sort();
44
+ }
45
+ async function literalLine(repo: string, commit: string, path: string, value: string, runner: ProcessRunner): Promise<number | undefined> {
46
+ const result = await git(repo, ["grep", "--no-color", "-a", "-F", "-n", "-z", "-e", value, commit, "--", path], runner);
47
+ if (!passed(result)) return undefined;
48
+ // With -z git terminates both the tree-qualified name and the line number with NUL: name\0line\0text.
49
+ const nul = result.stdout.indexOf("\0");
50
+ if (nul < 0 || result.stdout.slice(0, nul) !== `${commit}:${path}`) return undefined;
51
+ const line = /^(\p{Nd}+)\u0000/u.exec(result.stdout.slice(nul + 1))?.[1];
52
+ return line === undefined ? undefined : Number(line);
53
+ }
54
+ /** Runs before the executor is asked to execute anything: no attempt record and no budget exist yet. */
55
+ export async function screenCandidate(repo: string, commit: string, screen: ProtocolScreen, inputs: Record<string, ProtocolInput>, executor: Executor, runner: ProcessRunner = spawnRunner): Promise<{ hits: ScreenHit[]; summary: ScreenSummary }> {
56
+ const hits: ScreenHit[] = [], rules: string[] = [];
57
+ if (screen.evaluatorInputs) {
58
+ rules.push("evaluatorInputs");
59
+ const tree = await treeBlobs(repo, commit, runner);
60
+ for (const [name, input] of Object.entries(inputs)) {
61
+ // Only an evaluator-only mount is invisible to the candidate at run time, so only that leak matters.
62
+ if (!input.mount.evaluator || input.mount.candidate) continue;
63
+ if (input.path === undefined) throw new Error(`attempt screen: evaluator input ${name} has no executor locator; restore its path in design/protocol.json before attempt run`);
64
+ let blobs: { blobs: string[] };
65
+ try { blobs = await hashExecutorInputBlobs(executor, input.path, SCREEN_FILES, runner); }
66
+ catch (error) { throw new Error(`attempt screen: evaluator input ${name}: ${error instanceof Error ? error.message : "blob list could not be read"}`); }
67
+ for (const blob of blobs.blobs) {
68
+ for (const path of tree.get(blob) ?? []) if (hits.length < SCREEN_HITS) hits.push({ rule: `evaluator-input:${name}`, path });
69
+ }
70
+ }
71
+ }
72
+ if (screen.literals) {
73
+ rules.push("literals");
74
+ for (const [index, value] of screen.literals.entries()) {
75
+ for (const path of await literalPaths(repo, commit, value, runner)) {
76
+ if (hits.length >= SCREEN_HITS) break;
77
+ const line = await literalLine(repo, commit, path, value, runner);
78
+ hits.push({ rule: `literal:${index}`, path, ...(line === undefined ? {} : { line }) });
79
+ }
80
+ }
81
+ }
82
+ return { hits, summary: { rules, sha256: sha256(canonical({ commit, screen })) } };
83
+ }