@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.
@@ -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
- export interface Selection { v: 1; run: string; metric: string; baseline: { commit: string }; minSeeds: number; minDelta: number }
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, ["v", "run", "metric", "baseline", "minSeeds", "minDelta"], "selection");
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
- return { v: 1, run: raw.run, metric, baseline: { commit: raw.baseline.commit.toLowerCase() }, minSeeds: raw.minSeeds as number, minDelta: raw.minDelta };
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`);
@@ -18,9 +18,12 @@ export interface HubGuidanceMetadata {
18
18
  readonly status: "declared" | "withdrawn";
19
19
  readonly applicable: boolean;
20
20
  readonly evidence: readonly Readonly<{key: string; status: "declared" | "unavailable"}>[];
21
+ /** Display only: screened hub prose or the literal `withheld`. Absent when the hub read (N-1) carries none. */
22
+ readonly rationale?: HubGuidanceRationale;
21
23
  }
24
+ export type HubGuidanceRationale = Readonly<{problemHypothesis: string; expectedObservableDifference: string}>;
22
25
  export type HubGuidanceReadProjection = {readonly state: "unavailable"}
23
- | {readonly state: "available"; readonly records: readonly HubGuidanceMetadata[]; readonly rationaleOmitted: true};
26
+ | {readonly state: "available"; readonly records: readonly HubGuidanceMetadata[]};
24
27
 
25
28
  function invalid(): never {
26
29
  throw new Error("hub guidance read: invalid closed metadata shape or bounds; reload a supported public guidance read result and retry");
@@ -76,16 +79,18 @@ function token(raw: unknown, pattern: RegExp, maximum: number): string {
76
79
  if (!pattern.test(result)) invalid();
77
80
  return result;
78
81
  }
79
- function rationaleBytes(raw: unknown): number {
82
+ function rationale(raw: unknown): HubGuidanceRationale {
80
83
  const row = object(raw, ["problemHypothesis", "expectedObservableDifference"]);
81
- const result = {problemHypothesis: text(row.problemHypothesis, 2000), expectedObservableDifference: text(row.expectedObservableDifference, 2000)};
82
- const bytes = Buffer.byteLength(JSON.stringify(result));
83
- if (bytes > 2000) invalid();
84
- return bytes;
84
+ const result = Object.freeze({problemHypothesis: text(row.problemHypothesis, 2000), expectedObservableDifference: text(row.expectedObservableDifference, 2000)});
85
+ if (Buffer.byteLength(JSON.stringify(result)) > 2000) invalid();
86
+ return result;
85
87
  }
88
+ const FIELDS = ["id", "experimentId", "taskId", "taskCreated", "flowRevision", "roleId", "layer", "baselineSha256", "candidateSha256", "changedSections", "bytes", "author", "status", "applicable", "evidence"];
86
89
 
87
90
  function record(raw: unknown): {metadata: HubGuidanceMetadata; sourceBytes: number} {
88
- const row = object(raw, ["id", "experimentId", "taskId", "taskCreated", "flowRevision", "roleId", "layer", "baselineSha256", "candidateSha256", "changedSections", "bytes", "author", "status", "applicable", "rationale", "evidence"]);
91
+ // A pre-rationale (N-1) hub read omits `rationale`; it parses with the rationale absent.
92
+ const hasRationale = raw !== null && typeof raw === "object" && !types.isProxy(raw) && Object.hasOwn(raw, "rationale");
93
+ const row = object(raw, hasRationale ? [...FIELDS, "rationale"] : FIELDS);
89
94
  const experimentId = text(row.experimentId, 256);
90
95
  if (/[\p{Cc}\p{Cs}]/u.test(experimentId)) invalid();
91
96
  if (row.layer !== "shipped" && row.layer !== "project") invalid();
@@ -109,12 +114,13 @@ function record(raw: unknown): {metadata: HubGuidanceMetadata; sourceBytes: numb
109
114
  baselineSha256: digest(row.baselineSha256), candidateSha256: digest(row.candidateSha256), changedSections: Object.freeze(changedSections),
110
115
  bytes: Object.freeze({baseline: integer(sizes.baseline, 1, 8192), candidate: integer(sizes.candidate, 1, 8192), record: integer(sizes.record, 1, 32_768)}),
111
116
  author: token(row.author, /^[a-z][a-z0-9-]{0,31}$/, 32), status: row.status, applicable: row.applicable, evidence: Object.freeze(evidence),
117
+ ...hasRationale ? {rationale: rationale(row.rationale)} : {},
112
118
  });
113
- const sourceBytes = Buffer.byteLength(JSON.stringify(metadata)) + Buffer.byteLength(',"rationale":') + rationaleBytes(row.rationale);
119
+ const sourceBytes = Buffer.byteLength(JSON.stringify(metadata));
114
120
  return {metadata, sourceBytes};
115
121
  }
116
122
 
117
- /** Parse public lifecycle metadata, never private role snapshots or rationale output. */
123
+ /** Parse public lifecycle metadata and the hub-screened rationale (display only), never private role snapshots. */
118
124
  export function parseHubGuidanceReadResult(raw: unknown): HubGuidanceReadProjection {
119
125
  if (typeof raw === "string") {
120
126
  if (raw.length > HUB_GUIDANCE_READ_BYTES || Buffer.byteLength(raw) > HUB_GUIDANCE_READ_BYTES) invalid();
@@ -132,9 +138,8 @@ export function parseHubGuidanceReadResult(raw: unknown): HubGuidanceReadProject
132
138
  const row = object(raw, ["state", "records"]);
133
139
  const parsed = array(row.records, 16).map(record);
134
140
  if (new Set(parsed.map(value => value.metadata.id)).size !== parsed.length) invalid();
135
- // Rationale text never leaves its validator; only byte counts cross the record boundary.
136
141
  const sourceBytes = Buffer.byteLength('{"state":"available","records":[]}')
137
142
  + parsed.reduce((sum, value) => sum + value.sourceBytes, 0) + Math.max(0, parsed.length - 1);
138
143
  if (sourceBytes > HUB_GUIDANCE_READ_BYTES) invalid();
139
- return Object.freeze({state: "available", records: Object.freeze(parsed.map(value => value.metadata)), rationaleOmitted: true});
144
+ return Object.freeze({state: "available", records: Object.freeze(parsed.map(value => value.metadata))});
140
145
  }
@@ -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)"); return form;
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
- return {fingerprint, nextStep, contrasts: [...bucket.contrasts.values()], composition: bucket.composition ?? null, 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}};
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: 2,
16
- paperPlan: 2,
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
- experimentSelection: 1,
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
  }