@staix/agent-research 0.3.1 → 0.4.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.
- package/CHANGELOG.md +48 -0
- package/README.md +84 -19
- package/package.json +4 -1
- package/src/cli-output.ts +446 -0
- package/src/cli.ts +208 -66
- package/src/commands-table.ts +213 -93
- package/src/commands.ts +75 -13
- package/src/exp/attempts.ts +13 -1
- package/src/exp/calibrate.ts +125 -0
- package/src/exp/executor.ts +98 -13
- package/src/exp/final.ts +12 -3
- package/src/exp/idea-report.ts +97 -0
- package/src/exp/ideas.ts +90 -6
- package/src/exp/investigate.ts +25 -22
- package/src/exp/protocol.ts +26 -1
- package/src/exp/screen.ts +83 -0
- package/src/exp/selection.ts +110 -4
- package/src/exp/stages.ts +3 -1
- package/src/harness/transitions.ts +37 -5
- package/src/manifest.ts +13 -5
- package/src/mcp-tools.ts +67 -14
- package/src/memory/archive.ts +8 -3
- package/src/paper/build.ts +39 -25
- package/src/paper/check.ts +46 -15
- package/src/paper/dependencies.ts +47 -0
- package/src/paper/document.ts +19 -0
- package/src/paper/figures.ts +152 -0
- package/src/paper/hygiene.ts +16 -5
- package/src/paper/plan.ts +71 -29
- package/src/paper/point-evidence.ts +27 -12
- package/src/paper/render.ts +113 -0
- package/src/paper/renderer.ts +128 -0
- package/src/paper/review.ts +41 -5
- package/src/plan/definition.ts +6 -1
- package/src/playbook.ts +20 -10
- package/src/provenance.ts +4 -3
- package/src/study-export.ts +7 -4
- package/src/study.ts +9 -4
- package/src/ui/plugin.ts +3 -1
package/src/exp/investigate.ts
CHANGED
|
@@ -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
|
|
47
|
-
|
|
48
|
-
|
|
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 =
|
|
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
|
-
|
|
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:
|
|
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 =
|
|
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;
|
package/src/exp/protocol.ts
CHANGED
|
@@ -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
|
+
}
|
package/src/exp/selection.ts
CHANGED
|
@@ -2,16 +2,60 @@ import { existsSync } from "node:fs";
|
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { boundedText, commit, onlyKeys, openStudy, plain, readTextBounded, requireExperiment, sha256, type Actor } from "../study.ts";
|
|
4
4
|
import type { ProtocolDefinition as Protocol } from "./protocol.ts";
|
|
5
|
+
import type { Attempt } from "./attempts.ts";
|
|
6
|
+
import { readBoundCalibration } from "./calibrate.ts";
|
|
5
7
|
|
|
6
|
-
|
|
8
|
+
interface SelectionFields { run: string; metric: string; baseline: { commit: string }; minSeeds: number; minDelta: number }
|
|
9
|
+
interface Guard { metric: string; maxRegression: number }
|
|
10
|
+
interface CostRule { metric: string; free: number; perUnit: number }
|
|
11
|
+
export type Selection = SelectionFields & (
|
|
12
|
+
{ v: 1 } | { v: 2; guards?: Guard[]; cost?: CostRule; calibration?: { sha256: string } }
|
|
13
|
+
);
|
|
14
|
+
const V1_FIELDS = ["v", "run", "metric", "baseline", "minSeeds", "minDelta"];
|
|
15
|
+
const V2_FIELDS = [...V1_FIELDS, "guards", "cost", "calibration"];
|
|
16
|
+
|
|
17
|
+
function nonnegative(value: unknown, field: string): number {
|
|
18
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error(`${field}: finite number >= 0 required`);
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function v2Fields(raw: Record<string, unknown>, protocol: Protocol, primary: string) {
|
|
23
|
+
const fields: Pick<Extract<Selection, { v: 2 }>, "guards" | "cost" | "calibration"> = {};
|
|
24
|
+
if (Object.hasOwn(raw, "guards")) {
|
|
25
|
+
if (!Array.isArray(raw.guards) || raw.guards.length > 8) throw new Error("selection.guards: array of at most eight guards required");
|
|
26
|
+
const seen = new Set<string>([primary]);
|
|
27
|
+
fields.guards = raw.guards.map(guard => {
|
|
28
|
+
if (!plain(guard)) throw new Error("selection.guards: each guard must be an object");
|
|
29
|
+
onlyKeys(guard, ["metric", "maxRegression"], "selection.guard");
|
|
30
|
+
const metric = boundedText(guard.metric, "selection.guard.metric", 128);
|
|
31
|
+
if (seen.has(metric) || !protocol.metrics.some(m => m.name === metric)) throw new Error("selection.guard.metric: select a distinct declared metric other than the primary");
|
|
32
|
+
seen.add(metric);
|
|
33
|
+
return { metric, maxRegression: nonnegative(guard.maxRegression, "selection.guard.maxRegression") };
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
if (Object.hasOwn(raw, "cost")) {
|
|
37
|
+
if (!plain(raw.cost)) throw new Error("selection.cost: object required");
|
|
38
|
+
onlyKeys(raw.cost, ["metric", "free", "perUnit"], "selection.cost");
|
|
39
|
+
const metric = boundedText(raw.cost.metric, "selection.cost.metric", 128);
|
|
40
|
+
if (!protocol.metrics.some(m => m.name === metric && m.direction === "min")) throw new Error("selection.cost.metric: select a declared min metric");
|
|
41
|
+
fields.cost = { metric, free: nonnegative(raw.cost.free, "selection.cost.free"), perUnit: nonnegative(raw.cost.perUnit, "selection.cost.perUnit") };
|
|
42
|
+
}
|
|
43
|
+
if (Object.hasOwn(raw, "calibration")) {
|
|
44
|
+
if (!plain(raw.calibration)) throw new Error("selection.calibration: object required");
|
|
45
|
+
onlyKeys(raw.calibration, ["sha256"], "selection.calibration");
|
|
46
|
+
if (typeof raw.calibration.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(raw.calibration.sha256)) throw new Error("selection.calibration.sha256: lowercase SHA-256 required");
|
|
47
|
+
fields.calibration = { sha256: raw.calibration.sha256 };
|
|
48
|
+
}
|
|
49
|
+
return fields;
|
|
50
|
+
}
|
|
7
51
|
export const SELECTION_BYTES = 65_536;
|
|
8
52
|
const compatible = "use an ares version that supports this selection, keeping design/selection.json unchanged";
|
|
9
53
|
export function selectionPath(dir: string): string { return join(dir, "design", "selection.json"); }
|
|
10
54
|
export function validateSelection(raw: unknown, protocol: Protocol): Selection {
|
|
11
55
|
try {
|
|
12
56
|
if (!plain(raw)) throw new Error("selection: JSON object required");
|
|
13
|
-
if (raw.v !== 1) throw new Error(`selection.v: unsupported version; ${compatible}`);
|
|
14
|
-
onlyKeys(raw,
|
|
57
|
+
if (raw.v !== 1 && raw.v !== 2) throw new Error(`selection.v: unsupported version; ${compatible}`);
|
|
58
|
+
onlyKeys(raw, raw.v === 1 ? V1_FIELDS : V2_FIELDS, "selection");
|
|
15
59
|
if (typeof raw.run !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(raw.run)) throw new Error("selection.run: use 1..64 letters, digits, underscores or hyphens, starting with a letter or digit");
|
|
16
60
|
if (["ablate", "final", "posthoc"].includes(raw.run)) throw new Error(`selection.run: ${raw.run} is a reserved phase run; choose another run such as investigate`);
|
|
17
61
|
const metric = boundedText(raw.metric, "selection.metric", 128);
|
|
@@ -21,7 +65,8 @@ export function validateSelection(raw: unknown, protocol: Protocol): Selection {
|
|
|
21
65
|
if (typeof raw.baseline.commit !== "string" || !/^[a-fA-F0-9]{40}$/.test(raw.baseline.commit)) throw new Error("selection.baseline.commit: full 40-hex commit required");
|
|
22
66
|
if (!Number.isSafeInteger(raw.minSeeds) || (raw.minSeeds as number) < 1 || (raw.minSeeds as number) > protocol.seeds.length) throw new Error(`selection.minSeeds: integer in 1..${protocol.seeds.length} required (declared protocol seed count)`);
|
|
23
67
|
if (typeof raw.minDelta !== "number" || !Number.isFinite(raw.minDelta) || raw.minDelta < 0) throw new Error("selection.minDelta: finite number >= 0 required in the metric's unit");
|
|
24
|
-
|
|
68
|
+
const fields = { run: raw.run, metric, baseline: { commit: raw.baseline.commit.toLowerCase() }, minSeeds: raw.minSeeds as number, minDelta: raw.minDelta };
|
|
69
|
+
return raw.v === 1 ? { v: 1, ...fields } : { v: 2, ...fields, ...v2Fields(raw, protocol, metric) };
|
|
25
70
|
} catch (error) {
|
|
26
71
|
const message = error instanceof Error ? error.message : "selection: invalid rule";
|
|
27
72
|
throw new Error(message.includes(compatible) ? message : `${message}; correct the rule and run ares selection <dir> --file PATH again`);
|
|
@@ -47,7 +92,68 @@ export function selectionHash(dir: string, protocol: Protocol): string | undefin
|
|
|
47
92
|
export function setSelection(dir: string, raw: unknown, protocol: Protocol, actor: Actor) {
|
|
48
93
|
requireExperiment(openStudy(dir).study);
|
|
49
94
|
const selection = validateSelection(raw, protocol), previous = record(dir, protocol);
|
|
95
|
+
if (selection.v === 2 && selection.calibration) readBoundCalibration(dir, selection, protocol);
|
|
50
96
|
const text = JSON.stringify(selection, null, 2) + "\n", hash = sha256(text), changed = previous?.text !== text;
|
|
51
97
|
if (changed) commit(dir, [[selectionPath(dir), text, SELECTION_BYTES]], [{ actor, type: "selection.set", data: { sha256: hash, run: selection.run, metric: selection.metric } }]);
|
|
52
98
|
return { selection, sha256: hash, changed };
|
|
53
99
|
}
|
|
100
|
+
|
|
101
|
+
export function observedMetric(attempt: Attempt, metric: Protocol["metrics"][number]): number | undefined {
|
|
102
|
+
const values = Array.isArray(attempt.metrics) ? attempt.metrics.filter(m => m?.name === metric.name) : [];
|
|
103
|
+
const measurement = values[0];
|
|
104
|
+
return values.length === 1 && measurement?.unit === metric.unit && measurement.provenance === "ares-observed"
|
|
105
|
+
&& typeof measurement.value === "number" && Number.isFinite(measurement.value) ? measurement.value : undefined;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function sampleMean(values: number[]): number | null {
|
|
109
|
+
if (!values.length) return null;
|
|
110
|
+
const total = values.reduce((sum, value) => sum + value, 0);
|
|
111
|
+
if (Number.isFinite(total)) return total / values.length;
|
|
112
|
+
const scale = Math.max(...values.map(Math.abs));
|
|
113
|
+
if (!scale) return 0;
|
|
114
|
+
return Math.max(-1, Math.min(1, values.reduce((sum, value) => sum + value / scale / values.length, 0))) * scale;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface SelectionPair { attempt: Attempt; baseline: Attempt }
|
|
118
|
+
export interface ConstraintResult {
|
|
119
|
+
guardDeltas?: Record<string, number | null>;
|
|
120
|
+
cost?: { growth: number; allowedGrowth: number };
|
|
121
|
+
reason?: string;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Both phases apply the same independent rules to their actual paired attempts. */
|
|
125
|
+
export function evaluateSelectionConstraints(
|
|
126
|
+
rule: Selection, protocol: Protocol, pairs: readonly SelectionPair[], delta: number,
|
|
127
|
+
): ConstraintResult {
|
|
128
|
+
if (rule.v === 1 || !pairs.length) return {};
|
|
129
|
+
const result: ConstraintResult = {};
|
|
130
|
+
const values = (name: string) => {
|
|
131
|
+
const metric = protocol.metrics.find(entry => entry.name === name)!;
|
|
132
|
+
const candidate = pairs.map(pair => observedMetric(pair.attempt, metric));
|
|
133
|
+
const baseline = pairs.map(pair => observedMetric(pair.baseline, metric));
|
|
134
|
+
return { metric, candidate, baseline };
|
|
135
|
+
};
|
|
136
|
+
const complete = (sample: (number | undefined)[]): sample is number[] => sample.every(value => value !== undefined);
|
|
137
|
+
for (const guard of rule.guards ?? []) {
|
|
138
|
+
const { metric, candidate, baseline } = values(guard.metric);
|
|
139
|
+
const measured = complete(candidate) && complete(baseline);
|
|
140
|
+
const difference = measured ? sampleMean(candidate)! - sampleMean(baseline)! : null;
|
|
141
|
+
const adjusted = difference === null ? null : metric.direction === "max" ? difference : -difference;
|
|
142
|
+
if (adjusted !== null && !Number.isFinite(adjusted)) throw new Error(`selection guard ${guard.metric}: delta overflows; rescale the metric in a new protocol and rerun attempts`);
|
|
143
|
+
(result.guardDeltas ??= Object.create(null) as Record<string, number | null>)[guard.metric] = adjusted;
|
|
144
|
+
if (adjusted === null) result.reason ??= `guard-missing:${guard.metric}`;
|
|
145
|
+
else if (adjusted < -guard.maxRegression) result.reason ??= `guard:${guard.metric}`;
|
|
146
|
+
}
|
|
147
|
+
if (rule.cost) {
|
|
148
|
+
const { candidate, baseline } = values(rule.cost.metric);
|
|
149
|
+
const base = complete(baseline) ? sampleMean(baseline) : null;
|
|
150
|
+
if (base !== null && base <= 0) throw new Error(`selection cost ${rule.cost.metric}: baseline mean must be positive; correct the cost metric and rerun the baseline attempts`);
|
|
151
|
+
if (base === null || !complete(candidate)) { result.reason ??= "cost-missing"; return result; }
|
|
152
|
+
const average = sampleMean(candidate)!;
|
|
153
|
+
const growth = (average - base) / base, allowedGrowth = rule.cost.free + rule.cost.perUnit * delta;
|
|
154
|
+
if (!Number.isFinite(growth) || !Number.isFinite(allowedGrowth)) throw new Error(`selection cost ${rule.cost.metric}: cost rule overflows; rescale the metrics or revise the rule and rerun investigation`);
|
|
155
|
+
result.cost = { growth, allowedGrowth };
|
|
156
|
+
if (growth > 0 && growth > allowedGrowth) result.reason ??= "cost-rule";
|
|
157
|
+
}
|
|
158
|
+
return result;
|
|
159
|
+
}
|
package/src/exp/stages.ts
CHANGED
|
@@ -96,10 +96,12 @@ function candidateStages(raw: unknown, common: Protocol): CandidateStage[] {
|
|
|
96
96
|
|
|
97
97
|
/** Pure preflight: no study writes, process calls, mounts or artifact availability claims. */
|
|
98
98
|
export function validateStageProtocol(raw: unknown): ProtocolV2 {
|
|
99
|
-
const p = object(raw, ["v", "method", "candidate", "evaluator", "metrics", "seeds", "limits", "network", "budget"], "protocol");
|
|
99
|
+
const p = object(raw, ["v", "method", "candidate", "evaluator", "metrics", "seeds", "limits", "network", "budget", "screen"], "protocol");
|
|
100
100
|
if (p.v !== 2) throw new Error("protocol.v: unsupported stage version; use a compatible ares release, keeping the original definition unchanged");
|
|
101
101
|
// Validate common fields with the authoritative v1 validator; no common bound is multiplied.
|
|
102
102
|
const common = validateProtocol({ ...p, v: 1, candidate: PLACEHOLDER_EXECUTION });
|
|
103
|
+
// A stage protocol declares no protocol-level inputs, so no evaluator-only mount exists to compare.
|
|
104
|
+
if (common.screen?.evaluatorInputs) throw new Error("protocol.screen.evaluatorInputs: stage protocols declare no protocol inputs; screen the declared literals only");
|
|
103
105
|
const { v: _v, candidate: _candidate, inputs: _inputs, ...base } = common;
|
|
104
106
|
const result: ProtocolV2 = { ...base, v: 2, candidate: { stages: candidateStages(p.candidate, common) } };
|
|
105
107
|
if (Buffer.byteLength(JSON.stringify(result, null, 2) + "\n") > PROTOCOL_BYTES) throw new Error(`protocol: too large; reduce the formatted protocol to at most ${PROTOCOL_BYTES} bytes`);
|
|
@@ -7,9 +7,10 @@ import {validateHarnessExecution, type DeclaredExecutionRef, type HarnessRound,
|
|
|
7
7
|
export const HARNESS_CONTRASTS = 64, HARNESS_SECTIONS = 32;
|
|
8
8
|
export interface ProbeRef {probe: string; projectionSha256: string; outputManifestHash?: string}
|
|
9
9
|
interface Form {v: 1; id: string; fingerprint: string; model?: string; sourceExecution?: DeclaredExecutionRef}
|
|
10
|
+
interface Presentation {first: "baseline" | "arm"; verdict: "first" | "second" | "tie"}
|
|
10
11
|
export interface HarnessContrast extends Form {
|
|
11
12
|
arm: string; outcome: "improved" | "unchanged" | "regressed" | "inconclusive";
|
|
12
|
-
basis: "deterministic-check" | "blinded-judgment" | "actor-claim"; judge?: "human" | "model"; observations: string; uncertainty: string; explanations: string[]; evidence: ProbeRef[];
|
|
13
|
+
basis: "deterministic-check" | "blinded-judgment" | "actor-claim"; judge?: "human" | "model"; observations: string; uncertainty: string; explanations: string[]; evidence: ProbeRef[]; presentations?: Presentation[];
|
|
13
14
|
}
|
|
14
15
|
export interface HarnessComposition extends Form {sections: {section: string; decision: "keep" | "drop" | "revise"; contrasts: {id: string; sha256: string}[]; reason: string}[]; successorSha256: string | null}
|
|
15
16
|
export interface IndependentCheck {state: "passed" | "failed" | "unavailable"; source: {kind: "deterministic-executable" | "unavailable"; refs: ProbeRef[]}}
|
|
@@ -43,11 +44,31 @@ function base(row: Record<string, unknown>, input: "contrast" | "compose" | "ado
|
|
|
43
44
|
if (row.sourceExecution !== undefined) {try {sourceExecution = validateHarnessExecution(row.sourceExecution);} catch {throw new Error(`harness ${input} sourceExecution: malformed or unsafe; correct sourceExecution in the ${input} input form, then retry with the current fingerprint from ares harness show --json`);}}
|
|
44
45
|
return {v: 1, id: id(row.id), fingerprint: digest(row.fingerprint), ...(row.model !== undefined ? {model: text(row.model, HARNESS_MODEL_BYTES)} : {}), ...(sourceExecution ? {sourceExecution} : {})};
|
|
45
46
|
}
|
|
47
|
+
function parsePresentations(raw: unknown, outcome: HarnessContrast["outcome"]): Presentation[] {
|
|
48
|
+
const presentations = list(raw, 2, 2).map((value): Presentation => {
|
|
49
|
+
const {first, verdict} = object(value, ["first", "verdict"]);
|
|
50
|
+
if ((first !== "baseline" && first !== "arm") || (verdict !== "first" && verdict !== "second" && verdict !== "tie")) {
|
|
51
|
+
transitionFail("presentation first must be baseline or arm and verdict must be first, second or tie");
|
|
52
|
+
}
|
|
53
|
+
return {first, verdict};
|
|
54
|
+
});
|
|
55
|
+
if (presentations[0]!.first === presentations[1]!.first) transitionFail("presentations must alternate which output is first");
|
|
56
|
+
const [first, second] = presentations.map(({first, verdict}) =>
|
|
57
|
+
verdict === "tie" ? "tie" : verdict === "first" ? first : first === "baseline" ? "arm" : "baseline");
|
|
58
|
+
const expected = first !== second ? "inconclusive" : first === "arm" ? "improved" : first === "baseline" ? "regressed" : "unchanged";
|
|
59
|
+
if (outcome !== expected) transitionFail(`swapped presentations require outcome: ${expected}`);
|
|
60
|
+
return presentations;
|
|
61
|
+
}
|
|
46
62
|
export function parseContrast(raw: unknown): HarnessContrast {
|
|
47
|
-
const row = object(raw, ["v", "id", "fingerprint", "arm", "outcome", "basis", "judge", "model", "sourceExecution", "observations", "uncertainty", "explanations", "evidence"]);
|
|
63
|
+
const row = object(raw, ["v", "id", "fingerprint", "arm", "outcome", "basis", "judge", "model", "sourceExecution", "observations", "uncertainty", "explanations", "evidence", "presentations"]);
|
|
48
64
|
if (!["improved", "unchanged", "regressed", "inconclusive"].includes(row.outcome as string) || !["deterministic-check", "blinded-judgment", "actor-claim"].includes(row.basis as string)) transitionFail("invalid contrast outcome/basis");
|
|
49
|
-
const form = {...base(row, "contrast"), arm: id(row.arm), outcome: row.outcome as HarnessContrast["outcome"], basis: row.basis as HarnessContrast["basis"], ...(row.judge !== undefined ? {judge: row.judge as "human" | "model"} : {}), observations: text(row.observations), uncertainty: text(row.uncertainty), explanations: list(row.explanations, 8).map(value => text(value, 1000)), evidence: refs(row.evidence)};
|
|
50
|
-
if (!form.evidence.length || form.basis === "blinded-judgment" && !["human", "model"].includes(String(form.judge)) || form.basis !== "blinded-judgment" && form.judge !== undefined || form.judge === "model" && !form.model) transitionFail("contrast needs admitted evidence and blinded judgments need a human/model identity (model name when applicable)");
|
|
65
|
+
const form: HarnessContrast = {...base(row, "contrast"), arm: id(row.arm), outcome: row.outcome as HarnessContrast["outcome"], basis: row.basis as HarnessContrast["basis"], ...(row.judge !== undefined ? {judge: row.judge as "human" | "model"} : {}), observations: text(row.observations), uncertainty: text(row.uncertainty), explanations: list(row.explanations, 8).map(value => text(value, 1000)), evidence: refs(row.evidence)};
|
|
66
|
+
if (!form.evidence.length || form.basis === "blinded-judgment" && !["human", "model"].includes(String(form.judge)) || form.basis !== "blinded-judgment" && form.judge !== undefined || form.judge === "model" && !form.model) transitionFail("contrast needs admitted evidence and blinded judgments need a human/model identity (model name when applicable)");
|
|
67
|
+
if (Object.hasOwn(row, "presentations")) {
|
|
68
|
+
if (form.basis !== "blinded-judgment") transitionFail("presentations require basis: blinded-judgment");
|
|
69
|
+
form.presentations = parsePresentations(row.presentations, form.outcome);
|
|
70
|
+
}
|
|
71
|
+
return form;
|
|
51
72
|
}
|
|
52
73
|
export function parseComposition(raw: unknown): HarnessComposition {
|
|
53
74
|
const row = object(raw, ["v", "id", "fingerprint", "sections", "successorSha256", "model", "sourceExecution"]);
|
|
@@ -101,7 +122,18 @@ export function transitionView(round: HarnessRound, binding: string, probes: Dec
|
|
|
101
122
|
const closures = history.slice(-16).map(record => ({...record, current: record.binding === binding && record.form.fingerprint === fingerprint && record.sha256 === closure?.sha256}));
|
|
102
123
|
const successor = successorView(probes, bucket);
|
|
103
124
|
const nextStep = closure?.current ? "Round disposition recorded; separately review source-backed lessons or start a new round" : closure ? "Round/evidence changed; use the current fingerprint to preview ares harness close/adopt again" : successor?.execution === "unexecuted" ? "Import the exact successor fixture with ares harness import; its parents do not execute it" : !bucket.contrasts.size ? "Record admitted comparisons with ares harness contrast, or close baseline-kept/inconclusive/withdrawn with ares harness close" : !bucket.composition ? "Use ares harness compose for per-section decisions, or close without adoption using ares harness close" : "Preview ares harness adopt or ares harness close with the current fingerprint";
|
|
104
|
-
|
|
125
|
+
const contrasts = [...bucket.contrasts.values()].map(record => ({
|
|
126
|
+
...record, orderControl: record.form.presentations ? "swapped" as const : "none" as const,
|
|
127
|
+
}));
|
|
128
|
+
const swapped = contrasts.filter(record => record.orderControl === "swapped").length;
|
|
129
|
+
const composition = bucket.composition ? {
|
|
130
|
+
...bucket.composition,
|
|
131
|
+
sectionOrderControl: bucket.composition.form.sections.map(section => ({
|
|
132
|
+
section: section.section,
|
|
133
|
+
orderControlled: section.contrasts.filter(ref => bucket.contrasts.get(ref.id)?.form.presentations !== undefined).length,
|
|
134
|
+
})),
|
|
135
|
+
} : null;
|
|
136
|
+
return {fingerprint, nextStep, contrasts, orderControlCounts: {swapped, none: contrasts.length - swapped}, composition, adoption: bucket.adoption ?? null, closure, closures, remainingClosures: Math.max(0, history.length - closures.length), successor, readiness: {state: closure ? closure.current ? "closed" as const : "stale" as const : "open" as const, experimental: true as const, correctness: "unavailable" as const, transfer: "not-demonstrated" as const}};
|
|
105
137
|
}
|
|
106
138
|
/** Verify each transition at its ledger position. Fixture records never manufacture native checks or metrics. */
|
|
107
139
|
export function applyTransition(state: TransitionState, event: LedgerEvent, round: HarnessRound, binding: string, probes: DeclaredProbe[]): void {
|
package/src/manifest.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PAPER_DOCUMENTS, type PaperDocument } from "./paper/document.ts";
|
|
1
2
|
import { version } from "../package.json";
|
|
2
3
|
import { COMMANDS } from "./commands-table.ts";
|
|
3
4
|
import { ARES_TOOLS } from "./mcp-tools.ts";
|
|
@@ -12,35 +13,42 @@ export const FORMAT_VERSIONS = {
|
|
|
12
13
|
harnessExperience: 1,
|
|
13
14
|
harnessFixtureProjection: 1,
|
|
14
15
|
study: 2,
|
|
15
|
-
paperEvidence:
|
|
16
|
-
paperPlan:
|
|
16
|
+
paperEvidence: 3,
|
|
17
|
+
paperPlan: 3,
|
|
18
|
+
paperRender: 1,
|
|
19
|
+
rendererConfig: 1,
|
|
17
20
|
skillProposal: 2,
|
|
18
21
|
studyRegistry: 1,
|
|
19
22
|
watchConfig: 1,
|
|
20
23
|
studyPlan: 1,
|
|
21
24
|
ledgerEvent: 1,
|
|
22
25
|
experimentProtocol: 2,
|
|
23
|
-
|
|
26
|
+
protocolScreen: 1,
|
|
27
|
+
experimentSelection: 2,
|
|
28
|
+
selectionCalibration: 1,
|
|
24
29
|
experimentFinalSeeds: 1,
|
|
25
30
|
ablateResult: 1,
|
|
26
31
|
finalResult: 1,
|
|
27
32
|
investigateResult: 1,
|
|
33
|
+
ideaCategories: 1,
|
|
34
|
+
ideaReport: 1,
|
|
28
35
|
executor: 1,
|
|
29
36
|
experimentAttempt: 3,
|
|
30
37
|
studyBundle: 1,
|
|
31
38
|
} as const;
|
|
32
39
|
export const MEMORY_LEDGER_EVENTS = ["archive.exported", "skill.proposed", "skill.decided", "lesson.proposed", "lesson.decided"] as const;
|
|
33
40
|
export const WATCH_LEDGER_EVENTS = ["watch.set", "watch.ran"] as const;
|
|
34
|
-
export const LEDGER_EVENTS = [...MEMORY_LEDGER_EVENTS, ...WATCH_LEDGER_EVENTS, "autonomy.set", "harness.round.set", "harness.probe.declared", "harness.contrast.recorded", "harness.composition.recorded", "harness.adoption.decided", "harness.round.closed", "experience.stream.set", "experience.frozen", "retention.pruned", "attempt.pipeline.code", "attempt.pipeline.inputs", "attempt.stage.terminated", "attempt.reuse.preflight", "attempt.reuse.fresh-intent", "attempt.reuse.materialized", "attempt.reuse.miss", "attempt.stage.reused", "paper.plan.set"] as const;
|
|
41
|
+
export const LEDGER_EVENTS = [...MEMORY_LEDGER_EVENTS, ...WATCH_LEDGER_EVENTS, "autonomy.set", "harness.round.set", "harness.probe.declared", "harness.contrast.recorded", "harness.composition.recorded", "harness.adoption.decided", "harness.round.closed", "experience.stream.set", "experience.frozen", "retention.pruned", "attempt.pipeline.code", "attempt.pipeline.inputs", "attempt.screen.refused", "attempt.stage.terminated", "attempt.reuse.preflight", "attempt.reuse.fresh-intent", "attempt.reuse.materialized", "attempt.reuse.miss", "attempt.stage.reused", "paper.plan.set", "paper.rendered", "selection.calibrated", "idea.categories.set"] as const;
|
|
35
42
|
export interface Manifest {
|
|
36
43
|
v: 1;
|
|
37
44
|
name: "ares";
|
|
38
45
|
version: string;
|
|
39
46
|
commands: { name: string; usage: string }[];
|
|
40
47
|
formats: typeof FORMAT_VERSIONS;
|
|
48
|
+
paperDocuments: PaperDocument[];
|
|
41
49
|
ledgerEvents: typeof LEDGER_EVENTS[number][];
|
|
42
50
|
mcp: { server: "ares"; tools: { name: string; readOnly: boolean }[] };
|
|
43
51
|
}
|
|
44
52
|
export function manifest(): Manifest {
|
|
45
|
-
return { v: 1, name: "ares", version, commands: COMMANDS.map(({ name, usage }) => ({ name, usage })), formats: { ...FORMAT_VERSIONS }, ledgerEvents: [...LEDGER_EVENTS], mcp: { server: "ares", tools: ARES_TOOLS.map(tool => ({ name: tool.name, readOnly: tool.annotations.readOnlyHint === true && tool.annotations.openWorldHint !== true })) } };
|
|
53
|
+
return { v: 1, name: "ares", version, commands: COMMANDS.map(({ name, usage }) => ({ name, usage })), formats: { ...FORMAT_VERSIONS }, paperDocuments: [...PAPER_DOCUMENTS], ledgerEvents: [...LEDGER_EVENTS], mcp: { server: "ares", tools: ARES_TOOLS.map(tool => ({ name: tool.name, readOnly: tool.annotations.readOnlyHint === true && tool.annotations.openWorldHint !== true })) } };
|
|
46
54
|
}
|