@staix/agent-research 0.1.0 → 0.3.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.
- package/CHANGELOG.md +137 -0
- package/README.md +356 -31
- package/package.json +4 -2
- package/src/autonomy.ts +50 -0
- package/src/cli.ts +134 -14
- package/src/commands-table.ts +43 -9
- package/src/commands.ts +244 -43
- package/src/copilot.ts +91 -0
- package/src/exp/attempts.ts +512 -69
- package/src/exp/executor.ts +235 -12
- package/src/exp/final.ts +1 -1
- package/src/exp/investigate.ts +7 -2
- package/src/exp/logs.ts +25 -12
- package/src/exp/metrics.ts +6 -5
- package/src/exp/pipeline.ts +92 -0
- package/src/exp/protocol.ts +88 -18
- package/src/exp/retention-script.ts +649 -0
- package/src/exp/retention.ts +70 -0
- package/src/exp/reuse-admission.ts +63 -0
- package/src/exp/reuse-contract.ts +48 -0
- package/src/exp/reuse-runtime.ts +87 -0
- package/src/exp/reuse.ts +87 -0
- package/src/exp/selection.ts +1 -1
- package/src/exp/snapshot.ts +3 -3
- package/src/exp/stages.ts +117 -0
- package/src/harness/experience-source.ts +34 -0
- package/src/harness/experience.ts +206 -0
- package/src/harness/hub-guidance.ts +140 -0
- package/src/harness/hub-reference.ts +18 -0
- package/src/harness/lesson-candidates.ts +162 -0
- package/src/harness/limits.ts +2 -0
- package/src/harness/privacy.ts +4 -0
- package/src/harness/receipts.ts +84 -0
- package/src/harness/rounds.ts +198 -0
- package/src/harness/transitions.ts +152 -0
- package/src/http.ts +46 -2
- package/src/lit/candidates.ts +13 -5
- package/src/lit/cards.ts +55 -4
- package/src/lit/flow.ts +82 -0
- package/src/lit/queries.ts +62 -0
- package/src/lit/watch.ts +14 -1
- package/src/manifest.ts +15 -7
- package/src/mcp-tools.ts +140 -32
- package/src/mcp.ts +6 -0
- package/src/memory/amem-show.ts +135 -0
- package/src/memory/amem.ts +3 -0
- package/src/memory/archive.ts +20 -8
- package/src/memory/evidence-local.ts +77 -0
- package/src/memory/evidence.ts +39 -0
- package/src/memory/lessons.ts +4 -2
- package/src/memory/skill-check.ts +56 -0
- package/src/memory/skill-format.ts +77 -0
- package/src/memory/skills.ts +72 -26
- package/src/memory/source-budget.ts +11 -0
- package/src/memory/vault-cards.ts +226 -0
- package/src/paper/build.ts +20 -8
- package/src/paper/check.ts +40 -12
- package/src/paper/headings.ts +39 -0
- package/src/paper/hygiene.ts +153 -0
- package/src/paper/placeholders.ts +21 -4
- package/src/paper/plan.ts +170 -0
- package/src/paper/point-evidence.ts +63 -0
- package/src/paper/points.ts +83 -0
- package/src/paper/review.ts +116 -11
- package/src/paper/scopes.ts +51 -0
- package/src/plan/controller.ts +42 -12
- package/src/plan/definition.ts +22 -6
- package/src/plan/hub.ts +6 -0
- package/src/plan/state.ts +58 -17
- package/src/playbook.ts +47 -20
- package/src/privacy.ts +9 -0
- package/src/provenance.ts +679 -0
- package/src/scope.ts +24 -3
- package/src/study-export.ts +282 -0
- package/src/study.ts +94 -26
- package/src/ui/panel.css +4 -0
- package/src/ui/panel.js +271 -9
- package/src/ui/plugin.ts +89 -17
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import {HARNESS_MODEL_BYTES} from "./limits.ts";
|
|
2
|
+
import {hasHarnessCredential} from "./privacy.ts";
|
|
3
|
+
/** Legacy synthetic projections stay separate from the hub public metadata decoder and probe receipts. */
|
|
4
|
+
import {plain} from "../study.ts";
|
|
5
|
+
import {types} from "node:util";
|
|
6
|
+
import {parseHubGuidanceReadResult, HUB_GUIDANCE_READ_BYTES, type HubGuidanceReadProjection} from "./hub-guidance.ts";
|
|
7
|
+
import {validateExecutionReference, type SupportedExecutionReferenceV1} from "../provenance.ts";
|
|
8
|
+
|
|
9
|
+
export const HARNESS_FIXTURE_BYTES = 65_536;
|
|
10
|
+
export interface VariantFixtureProjectionV1 {
|
|
11
|
+
v: 1; projectKey: string; taskId: string; revision: number; baselineRoleId: string; baselineRoleHash: string; baselineBytes: number;
|
|
12
|
+
candidateHash: string; candidateBytes: number; author: string; problemHypothesis: string; expectedObservableDifference: string; rationale: string; evidence: SupportedExecutionReferenceV1[];
|
|
13
|
+
}
|
|
14
|
+
export interface ProbeFixtureProjectionV1 {
|
|
15
|
+
v: 1; id: string; experimentId: string; arm: string; taskId: string; taskRevision: number; taskInputHash: string; workerEffectiveInputHash: string; codeTreeHash: string; baselineHash: string; guidanceHash: string; baselineContextHash: string; libraryHash: string;
|
|
16
|
+
requestedModel: string; requestedConfigHash: string; servedModel: string | null; servedConfigHash: string | null;
|
|
17
|
+
toolsetHash: string; hostRuntimeHash: string; budgetHash: string; outputManifestHash: string | null;
|
|
18
|
+
state: "succeeded" | "failed" | "cancelled" | "unknown" | "unavailable"; usage: "unknown"; samplingControl: "unknown";
|
|
19
|
+
}
|
|
20
|
+
const VARIANT = ["v", "projectKey", "taskId", "revision", "baselineRoleId", "baselineRoleHash", "baselineBytes", "candidateHash", "candidateBytes", "author", "problemHypothesis", "expectedObservableDifference", "rationale", "evidence"];
|
|
21
|
+
const PROBE = ["v", "id", "experimentId", "arm", "taskId", "taskRevision", "taskInputHash", "workerEffectiveInputHash", "codeTreeHash", "baselineHash", "guidanceHash", "baselineContextHash", "libraryHash", "requestedModel", "requestedConfigHash", "servedModel", "servedConfigHash", "toolsetHash", "hostRuntimeHash", "budgetHash", "outputManifestHash", "state", "usage", "samplingControl"];
|
|
22
|
+
function fail(field: string): never {throw new Error(`harness fixture ${field}: invalid synthetic projection; correct the bounded ares-owned fixture fields without paths, transcripts, environment, credentials or assurance claims before retrying`);}
|
|
23
|
+
function object(raw: unknown, fields: string[], kind: string): Record<string, unknown> {
|
|
24
|
+
let value = raw;
|
|
25
|
+
if (typeof value === "string") {if (Buffer.byteLength(value) > HARNESS_FIXTURE_BYTES) fail(`${kind} bound`); try {value = JSON.parse(value);} catch {fail(`${kind} JSON`);}}
|
|
26
|
+
if (!plain(value) || Object.keys(value).some(key => !fields.includes(key)) || fields.some(key => !Object.hasOwn(value, key)) || value.v !== 1) fail(`${kind} shape/version`);
|
|
27
|
+
try {if (Buffer.byteLength(JSON.stringify(value)) > HARNESS_FIXTURE_BYTES) fail(`${kind} bound`);} catch {fail(`${kind} bound/JSON`);}
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
function text(raw: unknown, field: string, bound = 256): string {
|
|
31
|
+
if (typeof raw !== "string" || !raw.trim() || Buffer.byteLength(raw) > bound || raw.includes("\0") || hasHarnessCredential(raw)) fail(field);
|
|
32
|
+
return raw;
|
|
33
|
+
}
|
|
34
|
+
function hash(raw: unknown, field: string): string {if (typeof raw !== "string" || !/^[a-f0-9]{64}$/.test(raw)) fail(field); return raw;}
|
|
35
|
+
function integer(raw: unknown, field: string, min: number, max: number): number {if (!Number.isSafeInteger(raw) || Number(raw) < min || Number(raw) > max) fail(field); return raw as number;}
|
|
36
|
+
function model(raw: unknown, field: string): string {const value = text(raw, field, HARNESS_MODEL_BYTES); if (/[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value)) fail(field); return value;}
|
|
37
|
+
export function parseVariantFixture(raw: unknown): VariantFixtureProjectionV1 {
|
|
38
|
+
const value = object(raw, VARIANT, "variant");
|
|
39
|
+
if (!Array.isArray(value.evidence) || value.evidence.length > 16) fail("variant evidence");
|
|
40
|
+
const evidence = value.evidence.map(raw => {
|
|
41
|
+
let ref: SupportedExecutionReferenceV1; try {ref = validateExecutionReference(raw);} catch {return fail("variant evidence");}
|
|
42
|
+
text(ref.projectKey, "variant evidence projectKey"); text(ref.id, "variant evidence id"); if (ref.revision !== undefined) text(ref.revision, "variant evidence revision", 128); return ref;
|
|
43
|
+
});
|
|
44
|
+
return {v: 1, projectKey: text(value.projectKey, "projectKey"), taskId: text(value.taskId, "taskId"), revision: integer(value.revision, "revision", 1, Number.MAX_SAFE_INTEGER),
|
|
45
|
+
baselineRoleId: text(value.baselineRoleId, "baselineRoleId", 128), baselineRoleHash: hash(value.baselineRoleHash, "baselineRoleHash"), baselineBytes: integer(value.baselineBytes, "baselineBytes", 0, 8192),
|
|
46
|
+
candidateHash: hash(value.candidateHash, "candidateHash"), candidateBytes: integer(value.candidateBytes, "candidateBytes", 0, 8192), author: text(value.author, "author", 128),
|
|
47
|
+
problemHypothesis: text(value.problemHypothesis, "problemHypothesis", 2000), expectedObservableDifference: text(value.expectedObservableDifference, "expectedObservableDifference", 2000), rationale: text(value.rationale, "rationale", 2000), evidence};
|
|
48
|
+
}
|
|
49
|
+
/** Format-discriminated read only: metadata never becomes a fixture probe or an admission receipt. */
|
|
50
|
+
export type HarnessVariantReadResult = {format: "ares-fixture"; variant: VariantFixtureProjectionV1} | {format: "hub-public"; view: HubGuidanceReadProjection};
|
|
51
|
+
export function parseHarnessVariant(raw: unknown): HarnessVariantReadResult {
|
|
52
|
+
let value = raw;
|
|
53
|
+
if (typeof value === "string") {
|
|
54
|
+
if (Buffer.byteLength(value) > HUB_GUIDANCE_READ_BYTES) fail("variant read bound");
|
|
55
|
+
try { value = JSON.parse(value); } catch { fail("variant read JSON"); }
|
|
56
|
+
}
|
|
57
|
+
if (types.isProxy(value)) fail("variant read inert data");
|
|
58
|
+
if (value !== null && typeof value === "object" && Object.hasOwn(value, "state")) return {format: "hub-public", view: parseHubGuidanceReadResult(value)};
|
|
59
|
+
return {format: "ares-fixture", variant: parseVariantFixture(raw)};
|
|
60
|
+
}
|
|
61
|
+
export function parseProbeFixture(raw: unknown): ProbeFixtureProjectionV1 {
|
|
62
|
+
const value = object(raw, PROBE, "probe");
|
|
63
|
+
if (!["succeeded", "failed", "cancelled", "unknown", "unavailable"].includes(String(value.state)) || value.usage !== "unknown" || value.samplingControl !== "unknown") fail("probe outcome/usage/sampling");
|
|
64
|
+
return {v: 1, id: text(value.id, "id"), experimentId: text(value.experimentId, "experimentId"), arm: text(value.arm, "arm"), taskId: text(value.taskId, "taskId"), taskRevision: integer(value.taskRevision, "taskRevision", 1, Number.MAX_SAFE_INTEGER),
|
|
65
|
+
taskInputHash: hash(value.taskInputHash, "taskInputHash"), workerEffectiveInputHash: hash(value.workerEffectiveInputHash, "workerEffectiveInputHash"), codeTreeHash: hash(value.codeTreeHash, "codeTreeHash"), baselineHash: hash(value.baselineHash, "baselineHash"), guidanceHash: hash(value.guidanceHash, "guidanceHash"), baselineContextHash: hash(value.baselineContextHash, "baselineContextHash"), libraryHash: hash(value.libraryHash, "libraryHash"),
|
|
66
|
+
requestedModel: model(value.requestedModel, "requestedModel"), requestedConfigHash: hash(value.requestedConfigHash, "requestedConfigHash"), servedModel: value.servedModel === null ? null : model(value.servedModel, "servedModel"), servedConfigHash: value.servedConfigHash === null ? null : hash(value.servedConfigHash, "servedConfigHash"),
|
|
67
|
+
toolsetHash: hash(value.toolsetHash, "toolsetHash"), hostRuntimeHash: hash(value.hostRuntimeHash, "hostRuntimeHash"), budgetHash: hash(value.budgetHash, "budgetHash"), outputManifestHash: value.outputManifestHash === null ? null : hash(value.outputManifestHash, "outputManifestHash"), state: value.state as ProbeFixtureProjectionV1["state"], usage: "unknown", samplingControl: "unknown"};
|
|
68
|
+
}
|
|
69
|
+
export interface ProbeFixtureComparison {compatible: boolean; matched: false; sourceStrength: "synthetic-fixture"; endToEndEvaluation: "unavailable"; reasons: string[]; confounders: string[]}
|
|
70
|
+
export function compareProbeFixtures(left: ProbeFixtureProjectionV1, right: ProbeFixtureProjectionV1): ProbeFixtureComparison {
|
|
71
|
+
const a = parseProbeFixture(left), b = parseProbeFixture(right), reasons: string[] = [];
|
|
72
|
+
const keys = ["experimentId", "taskId", "taskRevision", "taskInputHash", "baselineHash", "baselineContextHash", "libraryHash", "codeTreeHash", "hostRuntimeHash", "toolsetHash", "requestedModel", "requestedConfigHash", "servedModel", "servedConfigHash", "budgetHash"] as const;
|
|
73
|
+
for (const key of keys) if (a[key] !== b[key]) reasons.push(`${key}-mismatch`);
|
|
74
|
+
for (const [label, probe] of [["left", a], ["right", b]] as const) {
|
|
75
|
+
if (probe.servedModel === null) reasons.push(`${label}-served-model-unavailable`); else if (probe.servedModel !== probe.requestedModel) reasons.push(`${label}-model-fallback`);
|
|
76
|
+
if (probe.servedConfigHash === null) reasons.push(`${label}-served-config-unavailable`); else if (probe.servedConfigHash !== probe.requestedConfigHash) reasons.push(`${label}-config-fallback`);
|
|
77
|
+
}
|
|
78
|
+
if (a.guidanceHash === b.guidanceHash && a.workerEffectiveInputHash !== b.workerEffectiveInputHash) reasons.push("workerEffectiveInputHash-mismatch");
|
|
79
|
+
return {compatible: reasons.length === 0, matched: false, sourceStrength: "synthetic-fixture", endToEndEvaluation: "unavailable", reasons, confounders: ["synthetic-fixture", "producer-unavailable", "sampling-unknown"]};
|
|
80
|
+
}
|
|
81
|
+
/** Real probe receipts remain unavailable; public guidance metadata supplies no probe/handoff assurance. */
|
|
82
|
+
export function realHubProbeUnavailable(_address?: unknown) {
|
|
83
|
+
return {state: "unavailable", matched: false, sourceStrength: "producer-unavailable", endToEndEvaluation: "unavailable", reasons: ["producer-unavailable"]} as const;
|
|
84
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import {transitionState, transitionBucket, transitionView, harnessEvidenceFingerprint, applyTransition, parseContrast, parseComposition, parseAdoption, parseClosure, closureFromAdoption, transitionKey, recordHash, transitionFail, type HarnessAdoption, type HarnessClosure, type HarnessContrast, type HarnessComposition, type Recorded} from "./transitions.ts";
|
|
2
|
+
import {requireRoundExperiences} from "./experience.ts";
|
|
3
|
+
import {hasHarnessCredential} from "./privacy.ts";
|
|
4
|
+
import {lstatSync} from "node:fs";
|
|
5
|
+
import {join} from "node:path";
|
|
6
|
+
import {commit, openStudy, requireExperiment, readTextBounded, readLedger, onlyKeys, plain, sha256, requireGate, isHarnessGate, type Actor, type LedgerEvent} from "../study.ts";
|
|
7
|
+
import {canonical} from "../plan/state.ts";
|
|
8
|
+
import {validateExecutionReference} from "../provenance.ts";
|
|
9
|
+
import {skillEvidenceReference, type SkillEvidenceReference} from "../memory/evidence.ts";
|
|
10
|
+
import {parseProbeFixture, compareProbeFixtures, type ProbeFixtureProjectionV1} from "./receipts.ts";
|
|
11
|
+
|
|
12
|
+
export const HARNESS_ROUNDS = 16, HARNESS_FORM_BYTES = 65_536, HARNESS_INDEX_BYTES = 1_048_576;
|
|
13
|
+
export interface DeclaredExecutionRef {v: 1; tool: "ahub"; projectKey: string; kind: string; id: string; revision?: string; sha256: string}
|
|
14
|
+
export interface HarnessRound {
|
|
15
|
+
context?: {streamSha256: string; improverContextHash: string};
|
|
16
|
+
v: 1; id: string; task: {id: string; inputSha256: string}; baseline: {guidanceSha256: string};
|
|
17
|
+
candidates: {id: string; guidanceSha256: string; category?: "procedure" | "domain"}[];
|
|
18
|
+
hypothesis: {deficiency: string; predictedChange: string}; experience: {ref: SkillEvidenceReference; digest: string}[];
|
|
19
|
+
authoring: "uncontrolled-authoring" | "controlled-lane";
|
|
20
|
+
sourceExecutions?: Partial<Record<"proposal1" | "proposal2" | "composition" | "selection" | "reflection", DeclaredExecutionRef>>;
|
|
21
|
+
}
|
|
22
|
+
export interface DeclaredProbe {round: string; binding: string; projectionSha256: string; sourceStrength: "synthetic-fixture"; projection: ProbeFixtureProjectionV1}
|
|
23
|
+
function fail(cause: string): never {throw new Error(`harness: ${cause}; inspect ares harness show, restore the recorded definition or revise it explicitly before retrying`);}
|
|
24
|
+
function object(raw: unknown, keys: string[], label: string): Record<string, unknown> {if (!plain(raw)) fail(`${label} object required`); try {onlyKeys(raw, keys, label);} catch {fail(`${label} has an unknown field`);} return raw;}
|
|
25
|
+
function text(raw: unknown, bound: number, label: string): string {
|
|
26
|
+
if (typeof raw !== "string" || !raw.trim() || raw.includes("\0") || Buffer.byteLength(raw) > bound || hasHarnessCredential(raw)) fail(`${label} must be bounded nonblank text without credentials or NUL`); return raw;
|
|
27
|
+
}
|
|
28
|
+
function checkMetadata(value: unknown): void {
|
|
29
|
+
if (typeof value === "string") {text(value, HARNESS_FORM_BYTES, "round metadata"); return;}
|
|
30
|
+
if (Array.isArray(value)) {for (const item of value) checkMetadata(item);}
|
|
31
|
+
else if (plain(value)) for (const item of Object.values(value)) checkMetadata(item);
|
|
32
|
+
}
|
|
33
|
+
function id(raw: unknown): string {if (typeof raw !== "string" || !isHarnessGate(`harness:${raw}`)) fail("round/candidate id must follow the 1..64 ASCII run-name rule"); return raw;}
|
|
34
|
+
function hash(raw: unknown): string {if (typeof raw !== "string" || !/^[a-f0-9]{64}$/.test(raw)) fail("lowercase SHA-256 required"); return raw;}
|
|
35
|
+
export function validateHarnessExecution(raw: unknown): DeclaredExecutionRef {
|
|
36
|
+
const row = object(raw, ["v", "tool", "projectKey", "kind", "id", "revision", "sha256"], "source execution ref");
|
|
37
|
+
if (row.v !== 1 || row.tool !== "ahub") fail("source execution must name a declared ahub receipt address");
|
|
38
|
+
const checked = validateExecutionReference({...row, tool: "ares", kind: "artifact"});
|
|
39
|
+
const result: DeclaredExecutionRef = {...checked, tool: "ahub", kind: text(row.kind, 128, "producer kind"), sha256: hash(row.sha256)};
|
|
40
|
+
checkMetadata(result); return result;
|
|
41
|
+
}
|
|
42
|
+
/** Ares-owned round schema, not a producer manifest or execution admission. */
|
|
43
|
+
export function validateHarnessRound(raw: unknown, studyId?: string): HarnessRound {
|
|
44
|
+
const row = object(raw, ["v", "id", "task", "baseline", "candidates", "hypothesis", "experience", "authoring", "sourceExecutions", "context"], "round");
|
|
45
|
+
if (row.v !== 1) fail("unsupported round version; use a version supporting the original record, keeping it unchanged");
|
|
46
|
+
const task = object(row.task, ["id", "inputSha256"], "task"), baseline = object(row.baseline, ["guidanceSha256"], "baseline"), hypothesis = object(row.hypothesis, ["deficiency", "predictedChange"], "hypothesis");
|
|
47
|
+
if (!Array.isArray(row.candidates) || row.candidates.length > 2 || !Array.isArray(row.experience) || row.experience.length > 16 || !["uncontrolled-authoring", "controlled-lane"].includes(row.authoring as string)) fail("invalid candidate/experience count or authoring mode");
|
|
48
|
+
const candidates = row.candidates.map(raw => {const candidate = object(raw, ["id", "guidanceSha256", "category"], "candidate"), name = id(candidate.id); if (["baseline", "successor"].includes(name) || candidate.category !== undefined && candidate.category !== "procedure" && candidate.category !== "domain") fail("candidate id/category invalid or reserved"); return {id: name, guidanceSha256: hash(candidate.guidanceSha256), ...(candidate.category !== undefined ? {category: candidate.category as "procedure" | "domain"} : {})};});
|
|
49
|
+
if (new Set(candidates.map(candidate => candidate.id)).size !== candidates.length) fail("duplicate candidate id");
|
|
50
|
+
const experience = row.experience.map(raw => {const value = object(raw, ["ref", "digest"], "experience"), ref = skillEvidenceReference(value.ref, studyId); if (!ref) fail("unsupported or wrong-study experience ref"); const digest = hash(value.digest); if (ref.tool === "ares" && ref.sha256 !== undefined && ref.sha256 !== digest) fail("experience ref and digest disagree"); return {ref, digest};});
|
|
51
|
+
const sources = row.sourceExecutions === undefined ? undefined : object(row.sourceExecutions, ["proposal1", "proposal2", "composition", "selection", "reflection"], "source executions");
|
|
52
|
+
const sourceExecutions = sources && Object.fromEntries(Object.entries(sources).map(([stage, value]) => [stage, validateHarnessExecution(value)]));
|
|
53
|
+
if (row.authoring === "controlled-lane" && candidates.some((_candidate, index) => !sourceExecutions?.[`proposal${index + 1}`])) fail("controlled model-authored proposals require their source execution receipt refs");
|
|
54
|
+
const context = row.context === undefined ? undefined : object(row.context, ["streamSha256", "improverContextHash"], "round context");
|
|
55
|
+
const round: HarnessRound = {v: 1, id: id(row.id), task: {id: text(task.id, 256, "task id"), inputSha256: hash(task.inputSha256)}, baseline: {guidanceSha256: hash(baseline.guidanceSha256)}, candidates, hypothesis: {deficiency: text(hypothesis.deficiency, 2000, "deficiency"), predictedChange: text(hypothesis.predictedChange, 2000, "predicted change")}, experience, authoring: row.authoring as HarnessRound["authoring"], ...(sourceExecutions ? {sourceExecutions} : {}), ...(context ? {context: {streamSha256: hash(context.streamSha256), improverContextHash: hash(context.improverContextHash)}} : {})};
|
|
56
|
+
checkMetadata(round);
|
|
57
|
+
if (Buffer.byteLength(JSON.stringify(round)) > HARNESS_FORM_BYTES) fail("round exceeds 64 KiB"); return round;
|
|
58
|
+
}
|
|
59
|
+
function matchesRound(round: HarnessRound, projection: ProbeFixtureProjectionV1, successor?: string | null): boolean {
|
|
60
|
+
const expected = projection.arm === "baseline" ? round.baseline.guidanceSha256 : projection.arm === "successor" ? successor : round.candidates.find(candidate => candidate.id === projection.arm)?.guidanceSha256;
|
|
61
|
+
return !!expected && projection.taskId === round.task.id && projection.taskInputHash === round.task.inputSha256 && projection.guidanceHash === expected && projection.baselineHash === round.baseline.guidanceSha256;
|
|
62
|
+
}
|
|
63
|
+
function requireDistinctSuccessor(projection: ProbeFixtureProjectionV1, active: readonly DeclaredProbe[]): void {
|
|
64
|
+
if (active.some(probe => (projection.arm === "successor" || probe.projection.arm === "successor") && probe.projection.guidanceHash === projection.guidanceHash)) fail("this guidance already has an execution; reference it rather than count another sample");
|
|
65
|
+
}
|
|
66
|
+
export const harnessRoundBinding = (round: HarnessRound) => sha256(canonical(round));
|
|
67
|
+
const binding = harnessRoundBinding;
|
|
68
|
+
const path = (dir: string) => join(dir, "design", "harness.json");
|
|
69
|
+
function replay(events: LedgerEvent[], studyId: string) {
|
|
70
|
+
const rounds = new Map<string, HarnessRound>(), tasks = new Map<string, string>(), probes: DeclaredProbe[] = [];
|
|
71
|
+
const projectionIds = new Set<string>(), roundArms = new Set<string>(), activeProbes = new Map<string, DeclaredProbe[]>(), transitions = transitionState();
|
|
72
|
+
for (const event of events) {
|
|
73
|
+
if (!event.type.startsWith("harness.")) continue;
|
|
74
|
+
if (event.data.v !== 1) fail("unsupported harness event version; keep original bytes and use a supporting version");
|
|
75
|
+
if (event.type === "harness.round.set") {
|
|
76
|
+
const round = validateHarnessRound(event.data.round, studyId), old = rounds.get(round.id);
|
|
77
|
+
if (event.data.binding !== binding(round) || old && canonical(old.task) !== canonical(round.task) || tasks.has(canonical(round.task)) && tasks.get(canonical(round.task)) !== round.id) fail("round receipt hash or immutable/unique task identity mismatch");
|
|
78
|
+
if (!old && rounds.size >= HARNESS_ROUNDS) fail("more than 16 rounds");
|
|
79
|
+
rounds.set(round.id, round); tasks.set(canonical(round.task), round.id);
|
|
80
|
+
} else if (event.type === "harness.probe.declared") {
|
|
81
|
+
const round = rounds.get(String(event.data.round)), projection = parseProbeFixture(event.data.projection);
|
|
82
|
+
const bucket = round && transitionBucket(transitions, round.id, binding(round));
|
|
83
|
+
if (!round || !matchesRound(round, projection, bucket?.composition?.form.successorSha256) || event.data.binding !== binding(round) || event.data.projectionSha256 !== sha256(canonical(projection)) || event.data.sourceStrength !== "synthetic-fixture") fail("declared probe receipt mismatch");
|
|
84
|
+
const projectionKey = canonical([round.id, projection.id]), armKey = canonical([round.id, binding(round), projection.arm]);
|
|
85
|
+
if (projectionIds.has(projectionKey) || roundArms.has(armKey)) fail("duplicate declared probe journal event");
|
|
86
|
+
requireDistinctSuccessor(projection, activeProbes.get(canonical([round.id, binding(round)])) ?? []);
|
|
87
|
+
projectionIds.add(projectionKey); roundArms.add(armKey);
|
|
88
|
+
const probe: DeclaredProbe = {round: round.id, binding: binding(round), projectionSha256: event.data.projectionSha256 as string, sourceStrength: "synthetic-fixture", projection};
|
|
89
|
+
probes.push(probe); const activeKey = canonical([round.id, binding(round)]), active = activeProbes.get(activeKey) ?? []; active.push(probe); activeProbes.set(activeKey, active);
|
|
90
|
+
} else if (["harness.contrast.recorded", "harness.composition.recorded", "harness.adoption.decided", "harness.round.closed"].includes(event.type)) {
|
|
91
|
+
const round = rounds.get(String(event.data.round)); if (!round) fail("transition round missing");
|
|
92
|
+
applyTransition(transitions, event, round, binding(round), activeProbes.get(canonical([round.id, binding(round)])) ?? []);
|
|
93
|
+
} else fail("unsupported harness form; keep its history and use a version supporting it");
|
|
94
|
+
}
|
|
95
|
+
return {rounds: [...rounds.values()], probes, transitions};
|
|
96
|
+
}
|
|
97
|
+
function read(dirArg: string, providedEvents?: LedgerEvent[]) {
|
|
98
|
+
const {dir, study} = openStudy(dirArg); requireExperiment(study);
|
|
99
|
+
const events = providedEvents === undefined ? readLedger(dir) : providedEvents, folded = replay(events, study.id), file = path(dir);
|
|
100
|
+
let stat;
|
|
101
|
+
try {
|
|
102
|
+
const design = lstatSync(join(dir, "design"), {throwIfNoEntry: false});
|
|
103
|
+
if (design && (!design.isDirectory() || design.isSymbolicLink())) fail("design must be a regular directory, not a link");
|
|
104
|
+
stat = lstatSync(file, {throwIfNoEntry: false});
|
|
105
|
+
} catch {return fail("harness index metadata unavailable or linked; restore a regular design directory and index");}
|
|
106
|
+
requireRoundExperiences(dir, folded.rounds, events);
|
|
107
|
+
if (!stat) {if (folded.rounds.length) fail("design/harness.json missing; restore its committed index"); return {dir, study, events, ...folded};}
|
|
108
|
+
if (!stat.isFile() || stat.isSymbolicLink()) fail("harness index must be a regular file, not a link");
|
|
109
|
+
let parsed: unknown; try {parsed = JSON.parse(readTextBounded(file, HARNESS_INDEX_BYTES, {noFollow: true}));} catch {return fail("index is missing, unreadable, malformed or over 1 MiB; restore design/harness.json");}
|
|
110
|
+
const raw = object(parsed, ["v", "rounds"], "index");
|
|
111
|
+
if (raw.v !== 1) fail("unsupported harness index version; keep it unchanged and use a supporting version");
|
|
112
|
+
if (!Array.isArray(raw.rounds) || raw.rounds.length > HARNESS_ROUNDS || canonical(raw.rounds.map(row => validateHarnessRound(row, study.id))) !== canonical(folded.rounds)) fail("harness index differs from its recorded definitions");
|
|
113
|
+
return {dir, study, events, ...folded};
|
|
114
|
+
}
|
|
115
|
+
export function readHarnessRounds(dir: string, events?: LedgerEvent[]): HarnessRound[] {return read(dir, events).rounds;}
|
|
116
|
+
export function harnessBinding(dir: string, roundId: string): string | undefined {const name = id(roundId), round = read(dir).rounds.find(round => round.id === name); return round && binding(round);}
|
|
117
|
+
/** Caller holds the study lock. Definition updates preserve the prior events and reopen only this round's gate. */
|
|
118
|
+
export function setHarnessRound(dirArg: string, raw: unknown, actor: Actor): HarnessRound {
|
|
119
|
+
const current = read(dirArg), round = validateHarnessRound(raw, current.study.id), old = current.rounds.find(value => value.id === round.id);
|
|
120
|
+
requireRoundExperiences(current.dir, [round], current.events);
|
|
121
|
+
if (old && canonical(old.task) !== canonical(round.task) || current.rounds.some(value => value.id !== round.id && canonical(value.task) === canonical(round.task))) fail("task identity is immutable and may have only one round");
|
|
122
|
+
if (old && binding(old) === binding(round)) return old;
|
|
123
|
+
if (!old && current.rounds.length >= HARNESS_ROUNDS) fail("16-round limit reached; use another experiment study");
|
|
124
|
+
const rounds = old ? current.rounds.map(value => value.id === round.id ? round : value) : [...current.rounds, round];
|
|
125
|
+
commit(current.dir, [[path(current.dir), JSON.stringify({v: 1, rounds}, null, 2) + "\n", HARNESS_INDEX_BYTES]], [{actor, type: "harness.round.set", data: {v: 1, round, binding: binding(round)}}]); return round;
|
|
126
|
+
}
|
|
127
|
+
/** One preflight for every evidence mutation; reserve header/closure space within the 1 MiB read envelope. */
|
|
128
|
+
function requireEvidenceViewCapacity(current: ReturnType<typeof read>, round: HarnessRound, probes: DeclaredProbe[]): void {
|
|
129
|
+
const hash = binding(round), bucket = transitionBucket(current.transitions, round.id, hash);
|
|
130
|
+
if (Buffer.byteLength(canonical({round, probes, transitions: transitionView(round, hash, probes, bucket, current.transitions.closures.get(round.id))})) > HARNESS_INDEX_BYTES - HARNESS_FORM_BYTES) transitionFail("current round evidence view would exceed its 1 MiB bound; keep the existing round and start a separately identified round/study");
|
|
131
|
+
}
|
|
132
|
+
/** Local fixture import is a declaration only. It can never be a real producer resolution or matched comparison. */
|
|
133
|
+
export function importHarnessFixture(dirArg: string, roundId: string, raw: unknown, actor: Actor) {
|
|
134
|
+
const current = read(dirArg), round = current.rounds.find(value => value.id === id(roundId)); if (!round) fail("round missing");
|
|
135
|
+
const projection = parseProbeFixture(raw), hash = sha256(canonical(projection));
|
|
136
|
+
const old = current.probes.find(value => value.round === round.id && value.projection.id === projection.id);
|
|
137
|
+
if (old) {if (old.projectionSha256 !== hash || old.binding !== binding(round)) fail("probe id reused with changed bytes or round binding"); return {...old, matched: false as const, endToEndEvaluation: "unavailable" as const};}
|
|
138
|
+
const bucket = transitionBucket(current.transitions, round.id, binding(round));
|
|
139
|
+
if (!matchesRound(round, projection, bucket.composition?.form.successorSha256)) fail("declared probe arm/task/guidance differs from the bound round");
|
|
140
|
+
if (current.probes.some(value => value.round === round.id && value.binding === binding(round) && value.projection.arm === projection.arm)) fail("an arm already has its declared execution; create a separately identified experiment rather than count it twice");
|
|
141
|
+
if (current.probes.filter(value => value.round === round.id && value.binding === binding(round)).length >= 4) fail("this round already has its baseline, candidates and successor declarations");
|
|
142
|
+
requireDistinctSuccessor(projection, current.probes.filter(probe => probe.round === round.id && probe.binding === binding(round)));
|
|
143
|
+
const prospective: DeclaredProbe = {round: round.id, binding: binding(round), projectionSha256: hash, sourceStrength: "synthetic-fixture", projection};
|
|
144
|
+
requireEvidenceViewCapacity(current, round, [...current.probes.filter(probe => probe.round === round.id && probe.binding === binding(round)), prospective]);
|
|
145
|
+
const approval = requireGate(current.dir, current.study, `harness:${round.id}`, name => name === `harness:${round.id}` ? binding(round) : undefined);
|
|
146
|
+
commit(current.dir, [], [...approval, {actor, type: "harness.probe.declared", data: {v: 1, round: round.id, binding: binding(round), projectionSha256: hash, sourceStrength: "synthetic-fixture", projection}}]);
|
|
147
|
+
return {round: round.id, binding: binding(round), projectionSha256: hash, sourceStrength: "synthetic-fixture" as const, matched: false as const, endToEndEvaluation: "unavailable" as const, projection};
|
|
148
|
+
}
|
|
149
|
+
export function readHarnessViews(dirArg: string, roundId?: string) {
|
|
150
|
+
const current = read(dirArg), rounds = roundId === undefined ? current.rounds : current.rounds.filter(round => round.id === id(roundId));
|
|
151
|
+
if (roundId !== undefined && !rounds.length) fail("round missing");
|
|
152
|
+
const views = rounds.map(round => {
|
|
153
|
+
const probes = current.probes.filter(probe => probe.round === round.id), active = probes.filter(probe => probe.binding === binding(round)), baseline = active.find(probe => probe.projection.arm === "baseline");
|
|
154
|
+
return {definition: round, binding: binding(round), transitions: transitionView(round, binding(round), active, transitionBucket(current.transitions, round.id, binding(round)), current.transitions.closures.get(round.id)), historicalImports: probes.length - active.length, probes: active, comparisons: active.filter(probe => probe.projection.arm !== "baseline").map(probe => ({arm: probe.projection.arm, ...(baseline ? compareProbeFixtures(baseline.projection, probe.projection) : {compatible: false, matched: false, sourceStrength: "synthetic-fixture", endToEndEvaluation: "unavailable", reasons: ["baseline-unavailable"], confounders: ["producer-unavailable"]})}))};
|
|
155
|
+
});
|
|
156
|
+
return views;
|
|
157
|
+
}
|
|
158
|
+
export function showHarness(dirArg: string, roundId?: string) {
|
|
159
|
+
const views = readHarnessViews(dirArg, roundId);
|
|
160
|
+
const result = (visible: typeof views) => ({v: 1, endToEndEvaluation: "unavailable" as const, realImport: "unavailable" as const, rounds: visible, truncated: visible.length !== views.length, remaining: views.length - visible.length});
|
|
161
|
+
const visible: typeof views = [];
|
|
162
|
+
for (const view of views) {if (Buffer.byteLength(JSON.stringify(result([...visible, view]))) > HARNESS_INDEX_BYTES) break; visible.push(view);}
|
|
163
|
+
return result(visible);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export type HarnessTransitionResult = {record: Recorded<HarnessContrast | HarnessComposition | HarnessAdoption | HarnessClosure>; duplicate: boolean; experimental: true; matched: false; endToEndEvaluation: "unavailable"; nextStep: string} | {needsConfirm: true; fingerprint: string; preview: string[]};
|
|
167
|
+
/** Caller holds the study lock. Preview and unsuccessful validation never emit approvals or transition records. */
|
|
168
|
+
export function recordHarnessTransition(dirArg: string, roundId: string, kind: "contrast" | "composition" | "adoption" | "closure", raw: unknown, actor: Actor, confirm?: string): HarnessTransitionResult {
|
|
169
|
+
const current = read(dirArg), round = current.rounds.find(round => round.id === id(roundId)); if (!round) fail("round missing");
|
|
170
|
+
const form = kind === "contrast" ? parseContrast(raw) : kind === "composition" ? parseComposition(raw) : kind === "adoption" ? parseAdoption(raw) : parseClosure(raw);
|
|
171
|
+
if (Buffer.byteLength(canonical(form)) > HARNESS_FORM_BYTES) transitionFail("form exceeds 64 KiB");
|
|
172
|
+
const key = transitionKey(round.id, kind, form.id), previous = current.transitions.records.get(key);
|
|
173
|
+
if (previous) {
|
|
174
|
+
if (canonical(previous.form) !== canonical(form)) transitionFail("transition id reused with changed content");
|
|
175
|
+
return {record: previous, duplicate: true, experimental: true, matched: false, endToEndEvaluation: "unavailable", nextStep: "Inspect ares harness show --json for the current readiness; this receipt is an idempotent historical result"};
|
|
176
|
+
}
|
|
177
|
+
if (kind === "closure" && (form as HarnessClosure).outcome === "adopted-experimental") transitionFail("use ares harness adopt for an adopted-experimental closure");
|
|
178
|
+
const hash = binding(round), probes = current.probes.filter(probe => probe.round === round.id && probe.binding === hash), bucket = transitionBucket(current.transitions, round.id, hash);
|
|
179
|
+
if (form.fingerprint !== harnessEvidenceFingerprint(hash, probes, bucket)) transitionFail("stale evidence fingerprint");
|
|
180
|
+
const type = kind === "contrast" ? "harness.contrast.recorded" : kind === "composition" ? "harness.composition.recorded" : kind === "adoption" ? "harness.adoption.decided" : "harness.round.closed";
|
|
181
|
+
const recordSha = recordHash(form, actor, hash), data = {v: 1, round: round.id, binding: hash, form, sha256: recordSha, sourceStrength: "synthetic-fixture"};
|
|
182
|
+
const event: LedgerEvent = {v: 1, at: new Date(0).toISOString(), actor, type, data};
|
|
183
|
+
applyTransition(current.transitions, event, round, hash, probes);
|
|
184
|
+
const pending = [{actor, type, data}];
|
|
185
|
+
if (kind === "adoption") {
|
|
186
|
+
const closed = closureFromAdoption(form as HarnessAdoption, recordSha), closedData = {v: 1, round: round.id, binding: hash, form: closed, sha256: recordHash(closed, actor, hash), sourceStrength: "synthetic-fixture"};
|
|
187
|
+
const closeEvent: LedgerEvent = {v: 1, at: event.at, actor, type: "harness.round.closed", data: closedData};
|
|
188
|
+
applyTransition(current.transitions, closeEvent, round, hash, probes); pending.push({actor, type: closeEvent.type, data: closedData});
|
|
189
|
+
}
|
|
190
|
+
requireEvidenceViewCapacity(current, round, probes);
|
|
191
|
+
const fingerprint = sha256(canonical({binding: hash, form}));
|
|
192
|
+
if ((kind === "adoption" || kind === "closure") && confirm === undefined) return {needsConfirm: true, fingerprint, preview: ["Experimental fixture-only disposition; correctness and transfer remain unavailable", kind === "adoption" ? `Adopt ${(form as HarnessAdoption).arm} with independent check unavailable` : `Close ${(form as HarnessClosure).outcome} without adoption`, bucket.composition?.form.successorSha256 ? "A new successor needs its own exact execution; identical preserved bytes reuse their receipt" : "No successor execution is inferred", "No native attempt, scientific metric, selection or final authority is created"]};
|
|
193
|
+
if ((kind === "adoption" || kind === "closure") && confirm !== fingerprint) transitionFail("confirmation differs; open a new harness adopt/close preview");
|
|
194
|
+
const approval = requireGate(current.dir, current.study, `harness:${round.id}`, gate => gate === `harness:${round.id}` ? hash : undefined);
|
|
195
|
+
const written = commit(current.dir, [], [...approval, ...pending]);
|
|
196
|
+
const record = {...current.transitions.records.get(key)!, at: written.find(event => event.type === type)!.at};
|
|
197
|
+
return {record, duplicate: false, experimental: true, matched: false, endToEndEvaluation: "unavailable", nextStep: transitionView(round, hash, probes, bucket, current.transitions.closures.get(round.id)).nextStep};
|
|
198
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import {HARNESS_MODEL_BYTES} from "./limits.ts";
|
|
2
|
+
import {plain, onlyKeys, sha256, isHarnessGate, type Actor, type LedgerEvent} from "../study.ts";
|
|
3
|
+
import {canonical} from "../plan/state.ts";
|
|
4
|
+
import {hasHarnessCredential} from "./privacy.ts";
|
|
5
|
+
import {validateHarnessExecution, type DeclaredExecutionRef, type HarnessRound, type DeclaredProbe} from "./rounds.ts";
|
|
6
|
+
|
|
7
|
+
export const HARNESS_CONTRASTS = 64, HARNESS_SECTIONS = 32;
|
|
8
|
+
export interface ProbeRef {probe: string; projectionSha256: string; outputManifestHash?: string}
|
|
9
|
+
interface Form {v: 1; id: string; fingerprint: string; model?: string; sourceExecution?: DeclaredExecutionRef}
|
|
10
|
+
export interface HarnessContrast extends Form {
|
|
11
|
+
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
|
+
}
|
|
14
|
+
export interface HarnessComposition extends Form {sections: {section: string; decision: "keep" | "drop" | "revise"; contrasts: {id: string; sha256: string}[]; reason: string}[]; successorSha256: string | null}
|
|
15
|
+
export interface IndependentCheck {state: "passed" | "failed" | "unavailable"; source: {kind: "deterministic-executable" | "unavailable"; refs: ProbeRef[]}}
|
|
16
|
+
export interface HarnessAdoption extends Form {decision: "adopt"; arm: string; reason: string; checks: ProbeRef[]; independentCheck: IndependentCheck}
|
|
17
|
+
export type ClosureOutcome = "adopted-experimental" | "baseline-kept" | "inconclusive" | "withdrawn";
|
|
18
|
+
export interface HarnessClosure extends Form {outcome: ClosureOutcome; reason: string; adoptionSha256?: string}
|
|
19
|
+
export type ClosureRecord = Recorded<HarnessClosure> & {roundBinding: string; evidenceFingerprint: string; outcome: ClosureOutcome; reason: string};
|
|
20
|
+
export interface Recorded<T> {form: T; sha256: string; actor: Actor; at: string; binding: string; sourceStrength: "synthetic-fixture"; matched: false}
|
|
21
|
+
export interface Bucket {contrasts: Map<string, Recorded<HarnessContrast>>; composition?: Recorded<HarnessComposition>; adoption?: Recorded<HarnessAdoption>; closed?: ClosureRecord}
|
|
22
|
+
export interface TransitionState {buckets: Map<string, Bucket>; records: Map<string, Recorded<HarnessContrast | HarnessComposition | HarnessAdoption | HarnessClosure>>; closures: Map<string, ClosureRecord[]>}
|
|
23
|
+
export function transitionState(): TransitionState {return {buckets: new Map(), records: new Map(), closures: new Map()};}
|
|
24
|
+
export function transitionBucket(state: TransitionState, round: string, binding: string): Bucket {
|
|
25
|
+
const key = canonical([round, binding]); let bucket = state.buckets.get(key);
|
|
26
|
+
if (!bucket) {bucket = {contrasts: new Map()}; state.buckets.set(key, bucket);} return bucket;
|
|
27
|
+
}
|
|
28
|
+
export function transitionFail(cause: string): never {throw new Error(`harness transition: ${cause}; inspect ares harness show --json, correct the admitted refs/round and use its current fingerprint before retrying`);}
|
|
29
|
+
function object(raw: unknown, keys: string[]): Record<string, unknown> {
|
|
30
|
+
if (!plain(raw)) transitionFail("object required"); try {onlyKeys(raw, keys, "harness transition");} catch {transitionFail(`unknown field; allowed fields: ${keys.join(", ")}`);} return raw;
|
|
31
|
+
}
|
|
32
|
+
function text(raw: unknown, max = 2000): string {if (typeof raw !== "string" || !raw.trim() || raw.includes("\0") || Buffer.byteLength(raw) > max || hasHarnessCredential(raw)) transitionFail("text is blank, over-bound or contains a URL/credential"); return raw;}
|
|
33
|
+
function id(raw: unknown): string {const value = text(raw, 64); if (!isHarnessGate(`harness:${value}`)) transitionFail("invalid ASCII run-name id"); return value;}
|
|
34
|
+
function digest(raw: unknown): string {if (typeof raw !== "string" || raw.length !== 64 || !/^[a-f0-9]{64}$/.test(raw)) transitionFail("lowercase SHA-256 required"); return raw;}
|
|
35
|
+
function list(raw: unknown, max: number, min = 0): unknown[] {if (!Array.isArray(raw) || raw.length < min || raw.length > max) transitionFail(`array requires ${min}..${max} items`); return raw;}
|
|
36
|
+
function refs(raw: unknown): ProbeRef[] {
|
|
37
|
+
const result = list(raw, 16).map(raw => {const row = object(raw, ["probe", "projectionSha256", "outputManifestHash"]); return {probe: text(row.probe, 256), projectionSha256: digest(row.projectionSha256), ...(row.outputManifestHash !== undefined ? {outputManifestHash: digest(row.outputManifestHash)} : {})};});
|
|
38
|
+
if (new Set(result.map(ref => ref.probe)).size !== result.length) transitionFail("duplicate probe ref"); return result;
|
|
39
|
+
}
|
|
40
|
+
function base(row: Record<string, unknown>, input: "contrast" | "compose" | "adopt" | "close"): Form {
|
|
41
|
+
if (row.v !== 1) transitionFail("unsupported form version; keep original bytes and use a supporting version");
|
|
42
|
+
let sourceExecution: DeclaredExecutionRef | undefined;
|
|
43
|
+
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
|
+
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
|
+
export function parseContrast(raw: unknown): HarnessContrast {
|
|
47
|
+
const row = object(raw, ["v", "id", "fingerprint", "arm", "outcome", "basis", "judge", "model", "sourceExecution", "observations", "uncertainty", "explanations", "evidence"]);
|
|
48
|
+
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;
|
|
51
|
+
}
|
|
52
|
+
export function parseComposition(raw: unknown): HarnessComposition {
|
|
53
|
+
const row = object(raw, ["v", "id", "fingerprint", "sections", "successorSha256", "model", "sourceExecution"]);
|
|
54
|
+
const sections = list(row.sections, HARNESS_SECTIONS, 1).map(raw => {
|
|
55
|
+
const section = object(raw, ["section", "decision", "contrasts", "reason"]);
|
|
56
|
+
if (!["keep", "drop", "revise"].includes(section.decision as string)) transitionFail("invalid section decision");
|
|
57
|
+
const contrasts = list(section.contrasts, 16, 1).map(raw => {const ref = object(raw, ["id", "sha256"]); return {id: id(ref.id), sha256: digest(ref.sha256)};});
|
|
58
|
+
if (new Set(contrasts.map(ref => ref.id)).size !== contrasts.length) transitionFail("duplicate contrast link");
|
|
59
|
+
return {section: text(section.section, 256), decision: section.decision as "keep" | "drop" | "revise", contrasts, reason: text(section.reason, 1000)};
|
|
60
|
+
});
|
|
61
|
+
if (new Set(sections.map(section => section.section)).size !== sections.length) transitionFail("duplicate section");
|
|
62
|
+
return {...base(row, "compose"), sections, successorSha256: row.successorSha256 === null ? null : digest(row.successorSha256)};
|
|
63
|
+
}
|
|
64
|
+
export function parseAdoption(raw: unknown): HarnessAdoption {
|
|
65
|
+
const row = object(raw, ["v", "id", "fingerprint", "decision", "arm", "reason", "checks", "independentCheck", "model", "sourceExecution"]);
|
|
66
|
+
if (row.decision !== "adopt") transitionFail("invalid adoption decision");
|
|
67
|
+
return {...base(row, "adopt"), decision: row.decision as HarnessAdoption["decision"], arm: id(row.arm), reason: text(row.reason), checks: refs(row.checks), independentCheck: parseIndependentCheck(row.independentCheck)};
|
|
68
|
+
}
|
|
69
|
+
function parseIndependentCheck(raw: unknown): IndependentCheck {
|
|
70
|
+
const row = object(raw, ["state", "source"]), source = object(row.source, ["kind", "refs"]);
|
|
71
|
+
if (!["passed", "failed", "unavailable"].includes(row.state as string) || !["deterministic-executable", "unavailable"].includes(source.kind as string)) transitionFail("independentCheck needs a closed state and a deterministic-executable or unavailable source, never a judgment");
|
|
72
|
+
const evidence = refs(source.refs);
|
|
73
|
+
if (source.kind === "unavailable" && evidence.length || source.kind === "deterministic-executable" && !evidence.length) transitionFail("independent check source/ref shape differs");
|
|
74
|
+
return {state: row.state as IndependentCheck["state"], source: {kind: source.kind as IndependentCheck["source"]["kind"], refs: evidence}};
|
|
75
|
+
}
|
|
76
|
+
export function parseClosure(raw: unknown): HarnessClosure {
|
|
77
|
+
const row = object(raw, ["v", "id", "fingerprint", "outcome", "reason", "adoptionSha256", "model", "sourceExecution"]);
|
|
78
|
+
if (!["adopted-experimental", "baseline-kept", "inconclusive", "withdrawn"].includes(row.outcome as string)) transitionFail("invalid closure outcome");
|
|
79
|
+
return {...base(row, "close"), outcome: row.outcome as ClosureOutcome, reason: text(row.reason), ...(row.adoptionSha256 !== undefined ? {adoptionSha256: digest(row.adoptionSha256)} : {})};
|
|
80
|
+
}
|
|
81
|
+
export function closureFromAdoption(form: HarnessAdoption, adoptionSha256?: string): HarnessClosure {
|
|
82
|
+
return {v: 1, id: form.id, fingerprint: form.fingerprint, outcome: "adopted-experimental", reason: form.reason, ...(form.model ? {model: form.model} : {}), ...(form.sourceExecution ? {sourceExecution: form.sourceExecution} : {}), ...(adoptionSha256 ? {adoptionSha256} : {})};
|
|
83
|
+
}
|
|
84
|
+
export const recordHash = (form: unknown, actor: Actor, binding: string) => sha256(canonical({form, actor, binding}));
|
|
85
|
+
export const transitionKey = (round: string, kind: string, id: string) => canonical([round, kind, id]);
|
|
86
|
+
export function harnessEvidenceFingerprint(binding: string, probes: DeclaredProbe[], bucket: Bucket): string {
|
|
87
|
+
return sha256(canonical({binding, probes: probes.map(probe => [probe.projection.id, probe.projectionSha256]), contrasts: [...bucket.contrasts.values()].map(record => record.sha256), composition: bucket.composition?.sha256 ?? null}));
|
|
88
|
+
}
|
|
89
|
+
function admitted(refs: ProbeRef[], probes: DeclaredProbe[]): void {
|
|
90
|
+
const known = new Map(probes.map(probe => [probe.projection.id, probe]));
|
|
91
|
+
for (const ref of refs) {const probe = known.get(ref.probe); if (!probe || probe.projectionSha256 !== ref.projectionSha256 || ref.outputManifestHash !== undefined && ref.outputManifestHash !== probe.projection.outputManifestHash) transitionFail("probe/output ref is not a current admitted projection");}
|
|
92
|
+
}
|
|
93
|
+
export function successorView(probes: DeclaredProbe[], bucket: Bucket) {
|
|
94
|
+
const hash = bucket.composition?.form.successorSha256; if (!hash) return null;
|
|
95
|
+
const own = probes.find(probe => probe.projection.guidanceHash === hash);
|
|
96
|
+
return {guidanceSha256: hash, execution: own ? "fixture-declared" as const : "unexecuted" as const, ...(own ? {probeId: own.projection.id, status: own.projection.state} : {})};
|
|
97
|
+
}
|
|
98
|
+
export function transitionView(round: HarnessRound, binding: string, probes: DeclaredProbe[], bucket: Bucket, history: readonly ClosureRecord[] = []) {
|
|
99
|
+
const fingerprint = harnessEvidenceFingerprint(binding, probes, bucket), prior = bucket.closed ?? history.at(-1);
|
|
100
|
+
const closure = prior ? {...prior, current: prior.binding === binding && prior.form.fingerprint === fingerprint} : null;
|
|
101
|
+
const closures = history.slice(-16).map(record => ({...record, current: record.binding === binding && record.form.fingerprint === fingerprint && record.sha256 === closure?.sha256}));
|
|
102
|
+
const successor = successorView(probes, bucket);
|
|
103
|
+
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}};
|
|
105
|
+
}
|
|
106
|
+
/** Verify each transition at its ledger position. Fixture records never manufacture native checks or metrics. */
|
|
107
|
+
export function applyTransition(state: TransitionState, event: LedgerEvent, round: HarnessRound, binding: string, probes: DeclaredProbe[]): void {
|
|
108
|
+
const bucket = transitionBucket(state, round.id, binding), data = object(event.data, ["v", "round", "binding", "form", "sha256", "sourceStrength"]);
|
|
109
|
+
if (data.v !== 1 || data.sourceStrength !== "synthetic-fixture" || data.round !== round.id || data.binding !== binding) transitionFail("transition version/binding differs from its round");
|
|
110
|
+
const kind = event.type === "harness.contrast.recorded" ? "contrast" : event.type === "harness.composition.recorded" ? "composition" : event.type === "harness.adoption.decided" ? "adoption" : event.type === "harness.round.closed" ? "closure" : transitionFail("unsupported transition event");
|
|
111
|
+
const form = kind === "contrast" ? parseContrast(data.form) : kind === "composition" ? parseComposition(data.form) : kind === "adoption" ? parseAdoption(data.form) : parseClosure(data.form);
|
|
112
|
+
const key = transitionKey(round.id, kind, form.id);
|
|
113
|
+
if (data.sha256 !== recordHash(form, event.actor, binding) || state.records.has(key) || form.fingerprint !== harnessEvidenceFingerprint(binding, probes, bucket)) transitionFail("transition receipt/id or current evidence fingerprint differs");
|
|
114
|
+
if (round.authoring === "controlled-lane" && (kind === "composition" || kind === "adoption" || (kind === "contrast" || kind === "closure") && (!!form.model || !!form.sourceExecution)) && (!form.sourceExecution || !form.model)) transitionFail("controlled authored transition needs model and declared source execution");
|
|
115
|
+
const record = {form, actor: event.actor, at: event.at, binding, sha256: data.sha256 as string, sourceStrength: "synthetic-fixture" as const, matched: false as const};
|
|
116
|
+
if (kind === "contrast") {
|
|
117
|
+
const contrast = form as HarnessContrast;
|
|
118
|
+
if (bucket.contrasts.size >= HARNESS_CONTRASTS) transitionFail("64-contrast limit; revise the round explicitly");
|
|
119
|
+
if (contrast.arm === "baseline" || !round.candidates.some(candidate => candidate.id === contrast.arm) && !(contrast.arm === "successor" && bucket.composition?.form.successorSha256)) transitionFail("contrast arm is not declared");
|
|
120
|
+
admitted(contrast.evidence, probes);
|
|
121
|
+
const evidenceIds = new Set(contrast.evidence.map(ref => ref.probe));
|
|
122
|
+
if (contrast.outcome !== "inconclusive" && !["baseline", contrast.arm].every(arm => probes.some(probe => probe.projection.arm === arm && evidenceIds.has(probe.projection.id)))) transitionFail("a non-inconclusive contrast needs its baseline and arm execution refs");
|
|
123
|
+
if (probes.some(probe => evidenceIds.has(probe.projection.id) && probe.projection.arm !== "baseline" && probe.projection.arm !== contrast.arm)) transitionFail("contrast evidence belongs to an unrelated arm; cite only baseline and the contrast arm, or record a separate contrast");
|
|
124
|
+
bucket.contrasts.set(form.id, record as Recorded<HarnessContrast>);
|
|
125
|
+
} else if (kind === "composition") {
|
|
126
|
+
const composition = form as HarnessComposition;
|
|
127
|
+
if (bucket.composition) transitionFail("one successor/composition per definition; revise the round explicitly");
|
|
128
|
+
for (const section of composition.sections) for (const ref of section.contrasts) if (bucket.contrasts.get(ref.id)?.sha256 !== ref.sha256) transitionFail("section links a missing or changed contrast");
|
|
129
|
+
bucket.composition = record as Recorded<HarnessComposition>;
|
|
130
|
+
} else if (kind === "closure") {
|
|
131
|
+
const closure = form as HarnessClosure;
|
|
132
|
+
if (bucket.closed?.form.fingerprint === form.fingerprint) transitionFail("current evidence already has an immutable closure");
|
|
133
|
+
if (closure.outcome === "adopted-experimental") {
|
|
134
|
+
if (!bucket.adoption || closure.adoptionSha256 !== bucket.adoption.sha256 || closure.fingerprint !== bucket.adoption.form.fingerprint || closure.reason !== bucket.adoption.form.reason || canonical(event.actor) !== canonical(bucket.adoption.actor)) transitionFail("experimental adoption closure lacks its current adoption receipt");
|
|
135
|
+
} else if (closure.adoptionSha256 !== undefined) transitionFail("non-adoption closure cannot claim an adoption receipt");
|
|
136
|
+
const closed: ClosureRecord = {...record, form: closure, roundBinding: binding, evidenceFingerprint: form.fingerprint, outcome: closure.outcome, reason: closure.reason};
|
|
137
|
+
bucket.closed = closed; const history = state.closures.get(round.id) ?? []; history.push(closed); state.closures.set(round.id, history);
|
|
138
|
+
state.records.set(key, closed); return;
|
|
139
|
+
} else {
|
|
140
|
+
const adoption = form as HarnessAdoption;
|
|
141
|
+
if (bucket.adoption?.form.fingerprint === form.fingerprint) transitionFail("this evidence already has a decision; change evidence before a new disposition");
|
|
142
|
+
const known = adoption.arm === "baseline" || round.candidates.some(candidate => candidate.id === adoption.arm) || adoption.arm === "successor" && !!bucket.composition?.form.successorSha256;
|
|
143
|
+
if (!known || adoption.arm === "baseline") transitionFail("decision arm differs from its declared candidate/baseline");
|
|
144
|
+
admitted(adoption.checks, probes); admitted(adoption.independentCheck.source.refs, probes);
|
|
145
|
+
const checked = new Set(adoption.checks.map(ref => ref.probe)), successor = adoption.arm === "successor" ? successorView(probes, bucket) : null;
|
|
146
|
+
if (!probes.some(probe => checked.has(probe.projection.id) && (probe.projection.arm === adoption.arm || adoption.arm === "successor" && successor?.execution === "fixture-declared" && probe.projection.id === successor.probeId))) transitionFail(`adoption needs its selected arm's admitted execution in checks; import the exact ${adoption.arm} fixture with ares harness import, then cite its current probe in checks`);
|
|
147
|
+
if (adoption.independentCheck.state !== "unavailable") transitionFail("independent deterministic check is unavailable for fixture-only sources; never turn a judgment or fixture into passed/failed correctness");
|
|
148
|
+
if (bucket.closed?.form.fingerprint === form.fingerprint) transitionFail("current evidence already has an immutable closure");
|
|
149
|
+
bucket.adoption = record as Recorded<HarnessAdoption>;
|
|
150
|
+
}
|
|
151
|
+
state.records.set(key, record);
|
|
152
|
+
}
|
package/src/http.ts
CHANGED
|
@@ -15,6 +15,47 @@ export interface Http {
|
|
|
15
15
|
const TIMEOUT_MS = 20_000, MAX_BYTES = 5 * 1024 * 1024;
|
|
16
16
|
const EMAIL = /^[^\s@<>()]{1,64}@[^\s@<>()]{1,190}$/;
|
|
17
17
|
|
|
18
|
+
export const S2_START_INTERVAL_MS = 1_100;
|
|
19
|
+
export interface HttpPacingClock {
|
|
20
|
+
now(): number;
|
|
21
|
+
sleep(ms: number): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
export interface HttpPacing {
|
|
24
|
+
start<T>(request: () => Promise<T>): Promise<T>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Serialize admissions only: an in-flight response never holds the next start. */
|
|
28
|
+
export function createHttpPacing(clock: HttpPacingClock = {
|
|
29
|
+
now: () => performance.now(),
|
|
30
|
+
sleep: ms => new Promise(resolve => setTimeout(resolve, ms)),
|
|
31
|
+
}): HttpPacing {
|
|
32
|
+
let tail = Promise.resolve(), lastStart: number | undefined;
|
|
33
|
+
return {
|
|
34
|
+
start<T>(request: () => Promise<T>): Promise<T> {
|
|
35
|
+
const admitted = tail.then(async () => {
|
|
36
|
+
if (lastStart !== undefined) {
|
|
37
|
+
let remaining = S2_START_INTERVAL_MS - (clock.now() - lastStart);
|
|
38
|
+
while (remaining > 0) {
|
|
39
|
+
await clock.sleep(remaining);
|
|
40
|
+
remaining = S2_START_INTERVAL_MS - (clock.now() - lastStart);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
// Measure after invocation, conservatively spacing actual fetch starts.
|
|
44
|
+
let response: Promise<T>;
|
|
45
|
+
try { response = request(); } finally { lastStart = clock.now(); }
|
|
46
|
+
// Box the promise so admission releases without waiting for the response.
|
|
47
|
+
// A later admission must not delay handling a rejected response.
|
|
48
|
+
void response.catch(() => {});
|
|
49
|
+
return { response };
|
|
50
|
+
});
|
|
51
|
+
tail = admitted.then(() => {}, () => {});
|
|
52
|
+
return admitted.then(({ response }) => response);
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const processS2Pacing = createHttpPacing();
|
|
58
|
+
|
|
18
59
|
/** Read the body while counting bytes; past the limit the stream is cancelled, never buffered whole. */
|
|
19
60
|
async function readBounded(response: Response, host: string): Promise<string> {
|
|
20
61
|
if (!response.body) return "";
|
|
@@ -38,11 +79,14 @@ export function userAgent(env: NodeJS.ProcessEnv): string {
|
|
|
38
79
|
}
|
|
39
80
|
|
|
40
81
|
/** 200 returns the body, 404 returns `body: undefined`; 429, 5xx, other statuses and network failures throw HttpError. */
|
|
41
|
-
export function createHttp(env: NodeJS.ProcessEnv = process.env, fetchImpl: FetchLike = fetch as FetchLike): Http {
|
|
82
|
+
export function createHttp(env: NodeJS.ProcessEnv = process.env, fetchImpl: FetchLike = fetch as FetchLike, pacing: HttpPacing = processS2Pacing): Http {
|
|
42
83
|
async function get(url: string, headers: Record<string, string> = {}): Promise<HttpResult<string>> {
|
|
43
84
|
const host = new URL(url).host;
|
|
44
85
|
let response: Response;
|
|
45
|
-
try {
|
|
86
|
+
try {
|
|
87
|
+
const request = () => fetchImpl(url, { headers: { "user-agent": userAgent(env), ...headers }, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
88
|
+
response = await (new URL(url).hostname === "api.semanticscholar.org" ? pacing.start(request) : request());
|
|
89
|
+
}
|
|
46
90
|
catch { throw new HttpError("network", host); }
|
|
47
91
|
if (response.status === 404) return { status: 404, body: undefined };
|
|
48
92
|
if (response.status === 429) throw new HttpError("rate", host, 429);
|
package/src/lit/candidates.ts
CHANGED
|
@@ -16,9 +16,14 @@ export interface Candidate extends Omit<RawCandidate, "source"> {
|
|
|
16
16
|
citekey?: string; verify?: Verification;
|
|
17
17
|
/** Other candidates that a record linked to this one but could not be absorbed (screened or keyed). */
|
|
18
18
|
duplicates?: string[];
|
|
19
|
+
/** Id (search-<n>) of the lit.search event that created this candidate; absent for candidates created before #103. */
|
|
20
|
+
firstQuery?: string;
|
|
21
|
+
/** Declared scope exclusion code recorded with --exclude --code; absent for uncoded exclusions. */
|
|
22
|
+
exclusionCode?: string;
|
|
19
23
|
}
|
|
20
24
|
|
|
21
|
-
const ABSTRACT_MAX = 2000, TITLE_MAX = 1000, AUTHORS_MAX = 100, AUTHOR_MAX = 300
|
|
25
|
+
const ABSTRACT_MAX = 2000, TITLE_MAX = 1000, AUTHORS_MAX = 100, AUTHOR_MAX = 300;
|
|
26
|
+
export const CANDIDATES_BYTES = 64 * 1024 * 1024;
|
|
22
27
|
const ARXIV_DOI = /^10\.48550\/arxiv\.(.+)$/i;
|
|
23
28
|
|
|
24
29
|
export function normTitle(title: string): string {
|
|
@@ -93,8 +98,8 @@ function link(a: Candidate, b: Candidate): void {
|
|
|
93
98
|
b.duplicates = [...new Set([...(b.duplicates ?? []), a.id])];
|
|
94
99
|
}
|
|
95
100
|
|
|
96
|
-
export function mergeCandidates(list: Candidate[], incoming: RawCandidate[], limit: number, now = new Date().toISOString()): { added: number; merged: number; dropped: number; linked: number } {
|
|
97
|
-
let added = 0, merged = 0, dropped = 0, linked = 0;
|
|
101
|
+
export function mergeCandidates(list: Candidate[], incoming: RawCandidate[], limit: number, now = new Date().toISOString(), firstQuery?: string): { added: number; merged: number; dropped: number; linked: number; absorbed?: number } {
|
|
102
|
+
let added = 0, merged = 0, dropped = 0, linked = 0, absorbed = 0;
|
|
98
103
|
for (const raw of incoming) {
|
|
99
104
|
const clean = cleanRaw(raw);
|
|
100
105
|
if (!clean) { dropped++; continue; }
|
|
@@ -107,6 +112,7 @@ export function mergeCandidates(list: Candidate[], incoming: RawCandidate[], lim
|
|
|
107
112
|
absorb(primary, other);
|
|
108
113
|
for (const twin of other.duplicates ?? []) { const t = list.find(c => c.id === twin); if (t && t !== primary) { t.duplicates = t.duplicates!.filter(d => d !== other.id); link(primary, t); } }
|
|
109
114
|
list.splice(list.indexOf(other), 1);
|
|
115
|
+
absorbed++;
|
|
110
116
|
}
|
|
111
117
|
else { link(primary, other); linked++; }
|
|
112
118
|
}
|
|
@@ -116,10 +122,12 @@ export function mergeCandidates(list: Candidate[], incoming: RawCandidate[], lim
|
|
|
116
122
|
}
|
|
117
123
|
if (list.length >= limit) { dropped++; continue; }
|
|
118
124
|
const { source, ...rest } = clean;
|
|
119
|
-
|
|
125
|
+
// firstQuery is set only here, when this search creates the candidate; later merges never overwrite it.
|
|
126
|
+
list.push({ ...rest, id: candidateId(clean), sources: [source], addedAt: now, status: "new", ...(firstQuery ? { firstQuery } : {}) });
|
|
120
127
|
added++;
|
|
121
128
|
}
|
|
122
|
-
|
|
129
|
+
// absorbed counts existing candidates folded away by a bridging record; it is reported only when nonzero, so ordinary searches keep their event shape.
|
|
130
|
+
return { added, merged, dropped, linked, ...(absorbed ? { absorbed } : {}) };
|
|
123
131
|
}
|
|
124
132
|
|
|
125
133
|
export function candidatesPath(dir: string): string { return join(dir, "literature", "candidates.json"); }
|