@staix/agent-research 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +70 -0
- package/README.md +93 -22
- package/package.json +4 -1
- package/src/cli-output.ts +446 -0
- package/src/cli.ts +208 -66
- package/src/commands-table.ts +213 -93
- package/src/commands.ts +86 -17
- package/src/exp/artifacts.ts +20 -2
- package/src/exp/attempts.ts +26 -9
- package/src/exp/calibrate.ts +125 -0
- package/src/exp/executor.ts +130 -21
- package/src/exp/final.ts +12 -3
- package/src/exp/idea-report.ts +97 -0
- package/src/exp/ideas.ts +90 -6
- package/src/exp/investigate.ts +25 -22
- package/src/exp/metrics.ts +3 -5
- package/src/exp/protocol.ts +28 -3
- package/src/exp/reuse-admission.ts +3 -1
- package/src/exp/reuse-runtime.ts +5 -1
- package/src/exp/screen.ts +83 -0
- package/src/exp/selection.ts +110 -4
- package/src/exp/snapshot.ts +28 -8
- package/src/exp/stages.ts +3 -1
- package/src/harness/transitions.ts +37 -5
- package/src/manifest.ts +13 -5
- package/src/mcp-tools.ts +67 -14
- package/src/memory/archive.ts +8 -3
- package/src/paper/build.ts +39 -25
- package/src/paper/check.ts +46 -15
- package/src/paper/dependencies.ts +47 -0
- package/src/paper/document.ts +19 -0
- package/src/paper/figures.ts +152 -0
- package/src/paper/hygiene.ts +16 -5
- package/src/paper/plan.ts +71 -29
- package/src/paper/point-evidence.ts +27 -12
- package/src/paper/render.ts +113 -0
- package/src/paper/renderer.ts +128 -0
- package/src/paper/review.ts +41 -5
- package/src/plan/definition.ts +6 -1
- package/src/playbook.ts +21 -11
- package/src/provenance.ts +4 -3
- package/src/study-export.ts +7 -4
- package/src/study.ts +9 -4
- package/src/ui/plugin.ts +3 -1
|
@@ -7,9 +7,10 @@ import {validateHarnessExecution, type DeclaredExecutionRef, type HarnessRound,
|
|
|
7
7
|
export const HARNESS_CONTRASTS = 64, HARNESS_SECTIONS = 32;
|
|
8
8
|
export interface ProbeRef {probe: string; projectionSha256: string; outputManifestHash?: string}
|
|
9
9
|
interface Form {v: 1; id: string; fingerprint: string; model?: string; sourceExecution?: DeclaredExecutionRef}
|
|
10
|
+
interface Presentation {first: "baseline" | "arm"; verdict: "first" | "second" | "tie"}
|
|
10
11
|
export interface HarnessContrast extends Form {
|
|
11
12
|
arm: string; outcome: "improved" | "unchanged" | "regressed" | "inconclusive";
|
|
12
|
-
basis: "deterministic-check" | "blinded-judgment" | "actor-claim"; judge?: "human" | "model"; observations: string; uncertainty: string; explanations: string[]; evidence: ProbeRef[];
|
|
13
|
+
basis: "deterministic-check" | "blinded-judgment" | "actor-claim"; judge?: "human" | "model"; observations: string; uncertainty: string; explanations: string[]; evidence: ProbeRef[]; presentations?: Presentation[];
|
|
13
14
|
}
|
|
14
15
|
export interface HarnessComposition extends Form {sections: {section: string; decision: "keep" | "drop" | "revise"; contrasts: {id: string; sha256: string}[]; reason: string}[]; successorSha256: string | null}
|
|
15
16
|
export interface IndependentCheck {state: "passed" | "failed" | "unavailable"; source: {kind: "deterministic-executable" | "unavailable"; refs: ProbeRef[]}}
|
|
@@ -43,11 +44,31 @@ function base(row: Record<string, unknown>, input: "contrast" | "compose" | "ado
|
|
|
43
44
|
if (row.sourceExecution !== undefined) {try {sourceExecution = validateHarnessExecution(row.sourceExecution);} catch {throw new Error(`harness ${input} sourceExecution: malformed or unsafe; correct sourceExecution in the ${input} input form, then retry with the current fingerprint from ares harness show --json`);}}
|
|
44
45
|
return {v: 1, id: id(row.id), fingerprint: digest(row.fingerprint), ...(row.model !== undefined ? {model: text(row.model, HARNESS_MODEL_BYTES)} : {}), ...(sourceExecution ? {sourceExecution} : {})};
|
|
45
46
|
}
|
|
47
|
+
function parsePresentations(raw: unknown, outcome: HarnessContrast["outcome"]): Presentation[] {
|
|
48
|
+
const presentations = list(raw, 2, 2).map((value): Presentation => {
|
|
49
|
+
const {first, verdict} = object(value, ["first", "verdict"]);
|
|
50
|
+
if ((first !== "baseline" && first !== "arm") || (verdict !== "first" && verdict !== "second" && verdict !== "tie")) {
|
|
51
|
+
transitionFail("presentation first must be baseline or arm and verdict must be first, second or tie");
|
|
52
|
+
}
|
|
53
|
+
return {first, verdict};
|
|
54
|
+
});
|
|
55
|
+
if (presentations[0]!.first === presentations[1]!.first) transitionFail("presentations must alternate which output is first");
|
|
56
|
+
const [first, second] = presentations.map(({first, verdict}) =>
|
|
57
|
+
verdict === "tie" ? "tie" : verdict === "first" ? first : first === "baseline" ? "arm" : "baseline");
|
|
58
|
+
const expected = first !== second ? "inconclusive" : first === "arm" ? "improved" : first === "baseline" ? "regressed" : "unchanged";
|
|
59
|
+
if (outcome !== expected) transitionFail(`swapped presentations require outcome: ${expected}`);
|
|
60
|
+
return presentations;
|
|
61
|
+
}
|
|
46
62
|
export function parseContrast(raw: unknown): HarnessContrast {
|
|
47
|
-
const row = object(raw, ["v", "id", "fingerprint", "arm", "outcome", "basis", "judge", "model", "sourceExecution", "observations", "uncertainty", "explanations", "evidence"]);
|
|
63
|
+
const row = object(raw, ["v", "id", "fingerprint", "arm", "outcome", "basis", "judge", "model", "sourceExecution", "observations", "uncertainty", "explanations", "evidence", "presentations"]);
|
|
48
64
|
if (!["improved", "unchanged", "regressed", "inconclusive"].includes(row.outcome as string) || !["deterministic-check", "blinded-judgment", "actor-claim"].includes(row.basis as string)) transitionFail("invalid contrast outcome/basis");
|
|
49
|
-
const form = {...base(row, "contrast"), arm: id(row.arm), outcome: row.outcome as HarnessContrast["outcome"], basis: row.basis as HarnessContrast["basis"], ...(row.judge !== undefined ? {judge: row.judge as "human" | "model"} : {}), observations: text(row.observations), uncertainty: text(row.uncertainty), explanations: list(row.explanations, 8).map(value => text(value, 1000)), evidence: refs(row.evidence)};
|
|
50
|
-
if (!form.evidence.length || form.basis === "blinded-judgment" && !["human", "model"].includes(String(form.judge)) || form.basis !== "blinded-judgment" && form.judge !== undefined || form.judge === "model" && !form.model) transitionFail("contrast needs admitted evidence and blinded judgments need a human/model identity (model name when applicable)");
|
|
65
|
+
const form: HarnessContrast = {...base(row, "contrast"), arm: id(row.arm), outcome: row.outcome as HarnessContrast["outcome"], basis: row.basis as HarnessContrast["basis"], ...(row.judge !== undefined ? {judge: row.judge as "human" | "model"} : {}), observations: text(row.observations), uncertainty: text(row.uncertainty), explanations: list(row.explanations, 8).map(value => text(value, 1000)), evidence: refs(row.evidence)};
|
|
66
|
+
if (!form.evidence.length || form.basis === "blinded-judgment" && !["human", "model"].includes(String(form.judge)) || form.basis !== "blinded-judgment" && form.judge !== undefined || form.judge === "model" && !form.model) transitionFail("contrast needs admitted evidence and blinded judgments need a human/model identity (model name when applicable)");
|
|
67
|
+
if (Object.hasOwn(row, "presentations")) {
|
|
68
|
+
if (form.basis !== "blinded-judgment") transitionFail("presentations require basis: blinded-judgment");
|
|
69
|
+
form.presentations = parsePresentations(row.presentations, form.outcome);
|
|
70
|
+
}
|
|
71
|
+
return form;
|
|
51
72
|
}
|
|
52
73
|
export function parseComposition(raw: unknown): HarnessComposition {
|
|
53
74
|
const row = object(raw, ["v", "id", "fingerprint", "sections", "successorSha256", "model", "sourceExecution"]);
|
|
@@ -101,7 +122,18 @@ export function transitionView(round: HarnessRound, binding: string, probes: Dec
|
|
|
101
122
|
const closures = history.slice(-16).map(record => ({...record, current: record.binding === binding && record.form.fingerprint === fingerprint && record.sha256 === closure?.sha256}));
|
|
102
123
|
const successor = successorView(probes, bucket);
|
|
103
124
|
const nextStep = closure?.current ? "Round disposition recorded; separately review source-backed lessons or start a new round" : closure ? "Round/evidence changed; use the current fingerprint to preview ares harness close/adopt again" : successor?.execution === "unexecuted" ? "Import the exact successor fixture with ares harness import; its parents do not execute it" : !bucket.contrasts.size ? "Record admitted comparisons with ares harness contrast, or close baseline-kept/inconclusive/withdrawn with ares harness close" : !bucket.composition ? "Use ares harness compose for per-section decisions, or close without adoption using ares harness close" : "Preview ares harness adopt or ares harness close with the current fingerprint";
|
|
104
|
-
|
|
125
|
+
const contrasts = [...bucket.contrasts.values()].map(record => ({
|
|
126
|
+
...record, orderControl: record.form.presentations ? "swapped" as const : "none" as const,
|
|
127
|
+
}));
|
|
128
|
+
const swapped = contrasts.filter(record => record.orderControl === "swapped").length;
|
|
129
|
+
const composition = bucket.composition ? {
|
|
130
|
+
...bucket.composition,
|
|
131
|
+
sectionOrderControl: bucket.composition.form.sections.map(section => ({
|
|
132
|
+
section: section.section,
|
|
133
|
+
orderControlled: section.contrasts.filter(ref => bucket.contrasts.get(ref.id)?.form.presentations !== undefined).length,
|
|
134
|
+
})),
|
|
135
|
+
} : null;
|
|
136
|
+
return {fingerprint, nextStep, contrasts, orderControlCounts: {swapped, none: contrasts.length - swapped}, composition, adoption: bucket.adoption ?? null, closure, closures, remainingClosures: Math.max(0, history.length - closures.length), successor, readiness: {state: closure ? closure.current ? "closed" as const : "stale" as const : "open" as const, experimental: true as const, correctness: "unavailable" as const, transfer: "not-demonstrated" as const}};
|
|
105
137
|
}
|
|
106
138
|
/** Verify each transition at its ledger position. Fixture records never manufacture native checks or metrics. */
|
|
107
139
|
export function applyTransition(state: TransitionState, event: LedgerEvent, round: HarnessRound, binding: string, probes: DeclaredProbe[]): void {
|
package/src/manifest.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PAPER_DOCUMENTS, type PaperDocument } from "./paper/document.ts";
|
|
1
2
|
import { version } from "../package.json";
|
|
2
3
|
import { COMMANDS } from "./commands-table.ts";
|
|
3
4
|
import { ARES_TOOLS } from "./mcp-tools.ts";
|
|
@@ -12,35 +13,42 @@ export const FORMAT_VERSIONS = {
|
|
|
12
13
|
harnessExperience: 1,
|
|
13
14
|
harnessFixtureProjection: 1,
|
|
14
15
|
study: 2,
|
|
15
|
-
paperEvidence:
|
|
16
|
-
paperPlan:
|
|
16
|
+
paperEvidence: 3,
|
|
17
|
+
paperPlan: 3,
|
|
18
|
+
paperRender: 1,
|
|
19
|
+
rendererConfig: 1,
|
|
17
20
|
skillProposal: 2,
|
|
18
21
|
studyRegistry: 1,
|
|
19
22
|
watchConfig: 1,
|
|
20
23
|
studyPlan: 1,
|
|
21
24
|
ledgerEvent: 1,
|
|
22
25
|
experimentProtocol: 2,
|
|
23
|
-
|
|
26
|
+
protocolScreen: 1,
|
|
27
|
+
experimentSelection: 2,
|
|
28
|
+
selectionCalibration: 1,
|
|
24
29
|
experimentFinalSeeds: 1,
|
|
25
30
|
ablateResult: 1,
|
|
26
31
|
finalResult: 1,
|
|
27
32
|
investigateResult: 1,
|
|
33
|
+
ideaCategories: 1,
|
|
34
|
+
ideaReport: 1,
|
|
28
35
|
executor: 1,
|
|
29
36
|
experimentAttempt: 3,
|
|
30
37
|
studyBundle: 1,
|
|
31
38
|
} as const;
|
|
32
39
|
export const MEMORY_LEDGER_EVENTS = ["archive.exported", "skill.proposed", "skill.decided", "lesson.proposed", "lesson.decided"] as const;
|
|
33
40
|
export const WATCH_LEDGER_EVENTS = ["watch.set", "watch.ran"] as const;
|
|
34
|
-
export const LEDGER_EVENTS = [...MEMORY_LEDGER_EVENTS, ...WATCH_LEDGER_EVENTS, "autonomy.set", "harness.round.set", "harness.probe.declared", "harness.contrast.recorded", "harness.composition.recorded", "harness.adoption.decided", "harness.round.closed", "experience.stream.set", "experience.frozen", "retention.pruned", "attempt.pipeline.code", "attempt.pipeline.inputs", "attempt.stage.terminated", "attempt.reuse.preflight", "attempt.reuse.fresh-intent", "attempt.reuse.materialized", "attempt.reuse.miss", "attempt.stage.reused", "paper.plan.set"] as const;
|
|
41
|
+
export const LEDGER_EVENTS = [...MEMORY_LEDGER_EVENTS, ...WATCH_LEDGER_EVENTS, "autonomy.set", "harness.round.set", "harness.probe.declared", "harness.contrast.recorded", "harness.composition.recorded", "harness.adoption.decided", "harness.round.closed", "experience.stream.set", "experience.frozen", "retention.pruned", "attempt.pipeline.code", "attempt.pipeline.inputs", "attempt.screen.refused", "attempt.stage.terminated", "attempt.reuse.preflight", "attempt.reuse.fresh-intent", "attempt.reuse.materialized", "attempt.reuse.miss", "attempt.stage.reused", "paper.plan.set", "paper.rendered", "selection.calibrated", "idea.categories.set"] as const;
|
|
35
42
|
export interface Manifest {
|
|
36
43
|
v: 1;
|
|
37
44
|
name: "ares";
|
|
38
45
|
version: string;
|
|
39
46
|
commands: { name: string; usage: string }[];
|
|
40
47
|
formats: typeof FORMAT_VERSIONS;
|
|
48
|
+
paperDocuments: PaperDocument[];
|
|
41
49
|
ledgerEvents: typeof LEDGER_EVENTS[number][];
|
|
42
50
|
mcp: { server: "ares"; tools: { name: string; readOnly: boolean }[] };
|
|
43
51
|
}
|
|
44
52
|
export function manifest(): Manifest {
|
|
45
|
-
return { v: 1, name: "ares", version, commands: COMMANDS.map(({ name, usage }) => ({ name, usage })), formats: { ...FORMAT_VERSIONS }, ledgerEvents: [...LEDGER_EVENTS], mcp: { server: "ares", tools: ARES_TOOLS.map(tool => ({ name: tool.name, readOnly: tool.annotations.readOnlyHint === true && tool.annotations.openWorldHint !== true })) } };
|
|
53
|
+
return { v: 1, name: "ares", version, commands: COMMANDS.map(({ name, usage }) => ({ name, usage })), formats: { ...FORMAT_VERSIONS }, paperDocuments: [...PAPER_DOCUMENTS], ledgerEvents: [...LEDGER_EVENTS], mcp: { server: "ares", tools: ARES_TOOLS.map(tool => ({ name: tool.name, readOnly: tool.annotations.readOnlyHint === true && tool.annotations.openWorldHint !== true })) } };
|
|
46
54
|
}
|
package/src/mcp-tools.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { PAPER_DOCUMENTS, paperDocument } from "./paper/document.ts";
|
|
2
|
+
import { PAPER_FIGURES, PAPER_FIGURE_PATH_BYTES, PAPER_FIGURE_WAIVER_BYTES } from "./paper/figures.ts";
|
|
1
3
|
import { STAGE_REUSE_CONTRACT_SCHEMA } from "./exp/reuse-contract.ts";
|
|
2
4
|
import {HARNESS_MODEL_BYTES} from "./harness/limits.ts";
|
|
3
5
|
import { PROVENANCE_KINDS, type ExecutionReferenceV1 } from "./provenance.ts";
|
|
@@ -11,9 +13,10 @@ import type { RetainedRef } from "./exp/retention.ts";
|
|
|
11
13
|
import { PLAYBOOK } from "./playbook.ts";
|
|
12
14
|
import { PLAN_ID_BYTES, STEP_COMMANDS } from "./plan/definition.ts";
|
|
13
15
|
import { PLAN_GATE_BYTES } from "./plan/state.ts";
|
|
14
|
-
import { PAPER_PLAN_BYTES, PAPER_PLAN_SECTIONS, PAPER_PLAN_CITES, PAPER_PLAN_POINTS, PAPER_POINT_CLAIM_CHARACTERS, PAPER_POINT_EVIDENCE, PAPER_POINT_EVIDENCE_BYTES } from "./paper/plan.ts";
|
|
16
|
+
import { PAPER_PLAN_BYTES, PAPER_PLAN_SECTIONS, PAPER_PLAN_CITES, PAPER_PLAN_POINTS, PAPER_POINT_CLAIM_CHARACTERS, PAPER_POINT_EVIDENCE, PAPER_POINT_EVIDENCE_BYTES, PAPER_PLAN_DEPENDENCIES, PAPER_DEPENDENCY_WAIVER_BYTES, PAPER_DEPENDENCY_KINDS } from "./paper/plan.ts";
|
|
15
17
|
import { detectActor, type Actor } from "./study.ts";
|
|
16
18
|
|
|
19
|
+
const paperDoc = { type: "string", enum: [...PAPER_DOCUMENTS] };
|
|
17
20
|
const study = { type: "string", minLength: 1, maxLength: 4096, description: "Absolute path of the study directory (holds study.json)" };
|
|
18
21
|
const id = { type: "string", minLength: 1, maxLength: 300 };
|
|
19
22
|
const ids = { type: "array", items: id, maxItems: 200 };
|
|
@@ -26,7 +29,20 @@ const obj = (properties: Record<string, unknown>, required: string[]) => ({ type
|
|
|
26
29
|
const text = (max: number) => ({ type: "string", minLength: 1, maxLength: max });
|
|
27
30
|
const texts = (items: number, max: number) => ({ type: "array", items: text(max), maxItems: items });
|
|
28
31
|
const year = { type: "integer", minimum: 1000, maximum: 2100 };
|
|
29
|
-
const
|
|
32
|
+
const PAPER_DEPENDENCY = obj({
|
|
33
|
+
id: {...text(64), pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$"},
|
|
34
|
+
kind: {type: "string", enum: [...PAPER_DEPENDENCY_KINDS]},
|
|
35
|
+
name: text(PAPER_PLAN_BYTES),
|
|
36
|
+
cites: {type: "array", minItems: 1, maxItems: PAPER_PLAN_CITES, uniqueItems: true, items: text(PAPER_PLAN_BYTES)},
|
|
37
|
+
waiver: text(PAPER_DEPENDENCY_WAIVER_BYTES),
|
|
38
|
+
}, ["id", "kind", "name"]);
|
|
39
|
+
const PAPER_FIGURE = obj({
|
|
40
|
+
id: {...text(64), pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$"},
|
|
41
|
+
file: text(PAPER_FIGURE_PATH_BYTES), kind: {type: "string", enum: ["plot", "diagram"]},
|
|
42
|
+
evidence: {type: "array", minItems: 1, maxItems: PAPER_POINT_EVIDENCE, items: text(PAPER_POINT_EVIDENCE_BYTES)},
|
|
43
|
+
waiver: text(PAPER_FIGURE_WAIVER_BYTES),
|
|
44
|
+
}, ["id", "file", "kind"]);
|
|
45
|
+
const PAPER_PLAN = obj({v: {type: "integer", enum: [1, 2, 3]}, sections: {type: "array", maxItems: PAPER_PLAN_SECTIONS, items: obj({
|
|
30
46
|
id: {...text(64), pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$"}, heading: text(PAPER_PLAN_BYTES),
|
|
31
47
|
cites: {type: "array", maxItems: PAPER_PLAN_CITES, uniqueItems: true, items: text(PAPER_PLAN_BYTES)},
|
|
32
48
|
points: {type: "array", maxItems: PAPER_PLAN_POINTS, items: obj({
|
|
@@ -36,7 +52,7 @@ const PAPER_PLAN = obj({v: {type: "integer", enum: [1, 2]}, sections: {type: "ar
|
|
|
36
52
|
requires: {type: "array", maxItems: PAPER_PLAN_CITES, uniqueItems: true, items: text(PAPER_PLAN_BYTES)},
|
|
37
53
|
evidence: {type: "array", maxItems: PAPER_POINT_EVIDENCE, items: {...text(PAPER_POINT_EVIDENCE_BYTES), description: "Existing current-study card:<paper-id> or attempt:<16-hex-id>, at most 4096 UTF-8 bytes; existence only"}},
|
|
38
54
|
}, ["id", "claim", "requires"])},
|
|
39
|
-
}, ["id", "heading", "cites"])}}, ["sections"]);
|
|
55
|
+
}, ["id", "heading", "cites"])}, dependencies: {type: "array", maxItems: PAPER_PLAN_DEPENDENCIES, items: PAPER_DEPENDENCY}, figures: {type: "array", maxItems: PAPER_FIGURES, items: PAPER_FIGURE}}, ["sections"]);
|
|
40
56
|
const EXECUTION_REFERENCE = obj({ v: { type: "integer", enum: [1] }, tool: { type: "string", enum: ["ares"] }, projectKey: text(256), kind: { type: "string", enum: [...PROVENANCE_KINDS] }, id: text(256), revision: text(128), sha256: { type: "string", minLength: 64, maxLength: 64 } }, ["v", "tool", "projectKey", "kind", "id"]);
|
|
41
57
|
const LINEAGE_ATTEMPTS = { type: "array", minItems: 1, maxItems: 8, items: { ...text(16), minLength: 16 } };
|
|
42
58
|
const LINEAGE_CANDIDATES = { type: "array", minItems: 1, maxItems: 8, items: { ...text(40), minLength: 40 } };
|
|
@@ -45,6 +61,7 @@ const REVIEW = obj({
|
|
|
45
61
|
checklist: obj({ negativeResults: { type: "boolean" }, denominators: { type: "boolean" }, limitations: { type: "boolean" }, reproducibility: { type: "boolean" },
|
|
46
62
|
survey: obj({ taxonomyPrinciple: { type: "boolean" }, noEnumeration: { type: "boolean" }, specificGaps: { type: "boolean" }, citationRelations: { type: "boolean" }, selectionReported: { type: "boolean" }, scopeControl: { type: "boolean" } }, ["taxonomyPrinciple", "noEnumeration", "specificGaps", "citationRelations", "selectionReported", "scopeControl"]) }, ["negativeResults", "denominators", "limitations", "reproducibility"]),
|
|
47
63
|
findings: { type: "array", maxItems: 200, items: obj({ id: text(128), kind: { type: "string", enum: ["contradiction", "unsupported-claim", "number", "citation", "method", "clarity", "other"] }, location: text(4000), text: text(4000), blocking: { type: "boolean" }, repair: { type: "string", enum: ["edit", "paragraph", "section"] }, section: text(256) }, ["id", "kind", "location", "text", "blocking"]) },
|
|
64
|
+
readback: obj({ claims: { type: "array", minItems: 1, maxItems: 8, items: { type: "string", minLength: 1, maxLength: 1000 } } }, ["claims"]),
|
|
48
65
|
}, ["v", "reviewer", "buildSha256", "checklist", "findings"]);
|
|
49
66
|
// Source-specific current-study/exact-id rules are owned by the shared validator; the MCP transport bounds both shapes.
|
|
50
67
|
const SKILL_REF = {...EXECUTION_REFERENCE, type: ["string", "object"], minLength: 1, maxLength: 4096, required: ["v", "tool", "id"], properties: {...EXECUTION_REFERENCE.properties, tool: {type: "string", enum: ["ares", "amem"]}}};
|
|
@@ -71,6 +88,10 @@ const PROTOCOL_V1 = obj({
|
|
|
71
88
|
network: { type: "string", enum: ["none"] },
|
|
72
89
|
inputs: { type: "object", maxProperties: 8, properties: {}, additionalProperties: obj({ path: text(4096), sha256: text(64), mount: obj({ candidate: text(256), evaluator: text(256) }, []) }, ["path", "sha256", "mount"]) },
|
|
73
90
|
budget: obj({ maxAttempts: integer(1, 1_000_000), maxWallHours: { type: "number", minimum: 0.000001, maximum: 1_000_000 }, maxGpuHours: { type: "number", minimum: 0, maximum: 64_000_000 } }, ["maxAttempts", "maxWallHours", "maxGpuHours"]),
|
|
91
|
+
screen: obj({
|
|
92
|
+
evaluatorInputs: { type: "boolean", enum: [true], description: "Refuse a candidate commit that carries a byte copy of an input mounted only for the evaluator" },
|
|
93
|
+
literals: { type: "array", minItems: 1, maxItems: 64, items: { type: "string", minLength: 8, maxLength: 200 }, description: "Fixed strings of 8..200 bytes searched over the candidate commit's files" },
|
|
94
|
+
}, []),
|
|
74
95
|
}, ["v", "method", "candidate", "evaluator", "metrics", "seeds", "limits", "network", "budget"]);
|
|
75
96
|
|
|
76
97
|
const STAGE_PROTOCOL = obj({ ...PROTOCOL_V1.properties,
|
|
@@ -102,13 +123,25 @@ const PLAN = obj({
|
|
|
102
123
|
edges: { type: "array", maxItems: 512, items: { type: "array", minItems: 2, maxItems: 2, items: planId } },
|
|
103
124
|
}, ["v", "nodes", "edges"]);
|
|
104
125
|
|
|
105
|
-
const
|
|
106
|
-
|
|
126
|
+
const SELECTION_FIELDS = {
|
|
127
|
+
run: text(64), metric: text(128),
|
|
107
128
|
baseline: obj({ commit: { type: "string", minLength: 40, maxLength: 40 } }, ["commit"]),
|
|
108
129
|
minSeeds: integer(1, 1000), minDelta: { type: "number", minimum: 0 },
|
|
109
|
-
}
|
|
130
|
+
};
|
|
131
|
+
const SELECTION_REQUIRED = ["v", "run", "metric", "baseline", "minSeeds", "minDelta"];
|
|
132
|
+
const SELECTION = { oneOf: [
|
|
133
|
+
obj({ v: { type: "integer", enum: [1] }, ...SELECTION_FIELDS }, SELECTION_REQUIRED),
|
|
134
|
+
obj({
|
|
135
|
+
v: { type: "integer", enum: [2] }, ...SELECTION_FIELDS,
|
|
136
|
+
guards: { type: "array", maxItems: 8, items: obj({ metric: text(128), maxRegression: { type: "number", minimum: 0 } }, ["metric", "maxRegression"]) },
|
|
137
|
+
cost: obj({ metric: text(128), free: { type: "number", minimum: 0 }, perUnit: { type: "number", minimum: 0 } }, ["metric", "free", "perUnit"]),
|
|
138
|
+
calibration: obj({ sha256: { type: "string", minLength: 64, maxLength: 64, pattern: "^[a-f0-9]{64}$" } }, ["sha256"]),
|
|
139
|
+
}, SELECTION_REQUIRED),
|
|
140
|
+
] };
|
|
110
141
|
|
|
111
|
-
const
|
|
142
|
+
const PREDICTION = obj({ metric: text(128), expect: { type: "string", enum: ["improve", "no-change", "regress"] }, minDelta: { type: "number", minimum: 0 } }, ["metric", "expect"]);
|
|
143
|
+
const IDEA = obj({ id: text(64), title: text(500), hypothesis: text(4000), parent: text(64), commit: { type: "string", minLength: 40, maxLength: 40 },
|
|
144
|
+
category: text(64), bundle: integer(1, 16), predicts: { type: "array", minItems: 1, maxItems: 4, items: PREDICTION } }, ["id", "title", "hypothesis"]);
|
|
112
145
|
|
|
113
146
|
export const ARES_TOOLS: readonly McpTool[] = [
|
|
114
147
|
{ name: "ares_retention_inspect", description: "Inspect executor-local retained identities, quota reservations and tombstones without a study write. Active sources/consumers remain explicit; no artifact bodies are returned.", inputSchema: obj({study, offset: integer(0, 16_000_000), limit: integer(1, 500)}, ["study"]), annotations: {...read, openWorldHint: true} },
|
|
@@ -156,6 +189,8 @@ export const ARES_TOOLS: readonly McpTool[] = [
|
|
|
156
189
|
{ name: "ares_gate", description: "List gates, or approve/reject scope, screen, design, final, review, plan:node-id, accept:hypotheses|paper|reviews or harness:<round-id>. Copilot accepts bind current draft hashes and are never automatic. Plan approvals bind all upstream output references and need complete upstream outputs; skip never bypasses them. The ledger records the actor; approval authority is workspace policy.", inputSchema: obj({ study, action: { type: "string", enum: ["list", "approve", "reject"] }, gate: text(PLAN_GATE_BYTES), reason }, ["study", "action"]), annotations: write },
|
|
157
190
|
{ name: "ares_idea_add", description: "Add an experiment idea to the ledger, with optional existing parent and frozen commit. Unique run-name ids and commit ownership; at most 1000 ideas. Starts no work.", inputSchema: obj({ study, idea: IDEA }, ["study", "idea"]), annotations: write },
|
|
158
191
|
{ name: "ares_idea_decide", description: "Record refine/pivot with a reason of at most 2000 bytes. Ideas with commits require terminal own-commit attempts (at most 200). Untested ideas omit attempts to attach a first commit or pivot. Refine requires --commit with unique idea ownership; Pivot accepts optional cause/retryWhen (2000 bytes each); refine refuses them. Pivot rejects commit and closes further decisions. Starts no work.", inputSchema: obj({ study, id: text(64), decision: { type: "string", enum: ["refine", "pivot"] }, reason: text(2000), cause: text(2000), retryWhen: text(2000), attempts: { type: "array", maxItems: 200, items: attemptId }, commit: { type: "string", minLength: 40, maxLength: 40 } }, ["study", "id", "decision", "reason"]), annotations: write },
|
|
192
|
+
{ name: "ares_idea_categories", description: "Declare the study-local idea category vocabulary (1..32 names) in design/idea-categories.json. Later idea add refuses unknown categories. A planning aid outside the design seal; starts no work.", inputSchema: obj({ study, categories: obj({ v: { type: "integer", enum: [1] }, categories: { type: "array", minItems: 1, maxItems: 32, items: text(64) } }, ["v", "categories"]) }, ["study", "categories"]), annotations: write },
|
|
193
|
+
{ name: "ares_idea_report", description: "Read an advisory idea report: prediction timing and hit/miss against the investigation pairing, unpredicted regressions, per-category recent gain, confounded bundles, stalled search and untried categories. Writes nothing, opens no gate.", inputSchema: obj({ study, run: text(64), window: integer(1, 1000) }, ["study"]), annotations: read },
|
|
159
194
|
{ name: "ares_investigate_show", description: "Read investigation candidate/baseline paired-seed scores, winner or no-winner reason and all run attempt totals/exclusions. No executor or network calls.", inputSchema: obj({ study }, ["study"]), annotations: read },
|
|
160
195
|
{ name: "ares_investigate_close", description: "Close the selected investigation run after all its attempts stop. Write a deterministic winner or no-winner result and ledger receipt; identical inputs write nothing. The no-arg investigate.close plan step emits {sha256,winner} for gates. Starts no attempts.", inputSchema: obj({ study }, ["study"]), annotations: write },
|
|
161
196
|
{ name: "ares_ablate_add", description: "Declare what a unique frozen ablation removes, at most 200 declarations. Winner/baseline commits are refused. Requires a current closed investigation winner; writes one journal event and starts no work.", inputSchema: obj({ study, ablation: obj({ id: text(64), commit: { type: "string", minLength: 40, maxLength: 40 }, removes: text(2000) }, ["id", "commit", "removes"]) }, ["study", "ablation"]), annotations: write },
|
|
@@ -165,6 +200,7 @@ export const ARES_TOOLS: readonly McpTool[] = [
|
|
|
165
200
|
{ name: "ares_final_close", description: "Close one-shot reserved-seed evaluation under the currently approved final gate. Re-approval keeps first attempt data fixed; later retries never replace it. Winner changes cannot buy a new final; changed protocol is not comparable. Refuses running or missing decisive attempts; writes deterministic qualified/not_qualified with unchanged inputs a no-op. The no-arg final.close plan step emits {sha256,status}; both qualification outcomes complete the step.", inputSchema: obj({ study }, ["study"]), annotations: write },
|
|
166
201
|
{ name: "ares_final_seeds", description: "Reserve unused unique declared protocol seeds for final evaluation (new/changed values reject prior use in every run/status), at least one and at most half the declared seeds. New/changed raw file bytes join the design seal; identical bytes are a no-op. Experiment mode only; starts no work.", inputSchema: obj({ study, final: obj({ v: { type: "integer", enum: [1] }, seeds: { type: "array", minItems: 1, maxItems: 500, items: seed } }, ["v", "seeds"]) }, ["study", "final"]), annotations: write },
|
|
167
202
|
{ name: "ares_selection_set", description: "Set a declared investigation selection rule before results: run (not reserved ablate/final/posthoc), primary metric, frozen baseline commit, minimum paired seeds and nonnegative improvement. Changes reopen the design gate; identical bytes leave the cutoff unchanged. Requires experiment mode and a protocol; starts no investigation or executor.", inputSchema: obj({ study, selection: SELECTION }, ["study", "selection"]), annotations: write },
|
|
203
|
+
{ name: "ares_selection_calibrate", description: "Record a recommended minimum delta from baseline variance (or paired A/A deltas for identical trees). Requires three non-reserved seeds. Never changes the selection rule or starts attempts.", inputSchema: obj({ study, fromRun: text(64), nullCommit: { type: "string", minLength: 40, maxLength: 40 }, z: { type: "number", minimum: 0 } }, ["study", "fromRun"]), annotations: write },
|
|
168
204
|
{ name: "ares_protocol_set", description: "Set an experiment protocol after bounded validation of protocol and task/. Sealed identity changes reopen design approval; same-identity input locator-only edits preserve approval. Comparable attempt identity excludes budget and input locators.", inputSchema: obj({ study, protocol: PROTOCOL }, ["study", "protocol"]), annotations: write },
|
|
169
205
|
{ name: "ares_executor_set", description: "Configure local or SSH Docker execution with an explicit private absolute workdir. Stores the host alias only, never credentials. Optional gpu settings enable a one-pass device/memory/load admission check; failed admission defers without an attempt.", inputSchema: obj({ study, kind: { type: "string", enum: ["local", "ssh"] }, host: text(128), workdir: text(4096), retentionCapBytes: integer(1, 1024 ** 4), gpu: obj({ devices: { type: "array", minItems: 1, maxItems: 64, items: { type: ["string", "integer"], maxLength: 40 } }, minFreeMemoryMb: integer(0, 2147483647), maxLoadRatio: { type: "number", exclusiveMinimum: 0, maximum: 1000000 } }, ["devices", "minFreeMemoryMb", "maxLoadRatio"]) }, ["study", "kind", "workdir"]), annotations: write },
|
|
170
206
|
{ name: "ares_executor_inputs_hash", description: "Hash a pre-staged input directory on the configured local or SSH executor host. Returns only sha256, files and bytes; never copies input paths or bodies into the study. Read-only external host access, with no gate or ledger write.", inputSchema: obj({ study, path: text(4096) }, ["study", "path"]), annotations: { ...read, openWorldHint: true } },
|
|
@@ -188,12 +224,17 @@ export const ARES_TOOLS: readonly McpTool[] = [
|
|
|
188
224
|
{ name: "ares_lit_bib", description: "Write refs/references.bib from included and verified candidates. Needs the screen gate. Citekeys never change once assigned.", inputSchema: obj({ study }, ["study"]), annotations: write },
|
|
189
225
|
{ name: "ares_review_add", description: "Record a bounded current-evidence-hash review with self-reported model family and checklist. Contradictions are always blocking; 100 reports per build, 200 findings per report, 4000-byte texts and a 60 KiB combined payload ceiling. Starts no build or controller.", inputSchema: obj({ study, review: REVIEW }, ["study", "review"]), annotations: write },
|
|
190
226
|
{ name: "ares_review_resolve", description: "Resolve a recorded review-id/finding-id with an explicit reason and actor. No votes or automatic contradiction resolution; historical reports stay in the ledger.", inputSchema: obj({ study, target: text(257), reason: text(4000) }, ["study", "target", "reason"]), annotations: write },
|
|
191
|
-
{ name: "ares_review_show", description: "Read current build/check readiness, review families, checklists and unresolved blocking findings. Claims readiness is unavailable (agent-hub#931) and nonblocking. Starts no network, build or controller.", inputSchema: obj({ study }, ["study"]), annotations: read },
|
|
227
|
+
{ name: "ares_review_show", description: "Read current build/check readiness, review families, checklists, reviewer read-backs beside plan point claims (never matched or scored) and unresolved blocking findings. Claims readiness is unavailable (agent-hub#931) and nonblocking. Starts no network, build or controller.", inputSchema: obj({ study }, ["study"]), annotations: read },
|
|
192
228
|
{ name: "ares_review_checklist", description: "List the six optional survey checklist keys with their questions, the same wording reviewers answer in checklist.survey. Answers are displayed and never gate. Opens no study.", inputSchema: obj({}, []), annotations: read },
|
|
193
|
-
{ name: "ares_paper_plan_set", description: "Validate and atomically store a declared citation routing plan, at most 64 sections/300 keys per section and 64 KiB. Only current included, identifier-verified bibliography keys. Optional writing points (40 per section) require citation presence in their own anchor windows; claims/evidence never establish support. Points select stored v2; no points keep v1. No automatic routing or relevance judgment. Starts no build/controller/network calls.", inputSchema: obj({study, plan: PAPER_PLAN}, ["study", "plan"]), annotations: write },
|
|
194
|
-
{ name: "ares_paper_plan_show", description: "Read the optional paper citation plan
|
|
195
|
-
{ name: "ares_paper_build", description: "Check the bounded manuscript and refuse blocking findings before writing. Commit rendered Markdown,
|
|
196
|
-
{ name: "
|
|
229
|
+
{ name: "ares_paper_plan_set", description: "Validate and atomically store a declared citation routing plan, at most 64 sections/300 keys per section and 64 KiB. Only current included, identifier-verified bibliography keys. Optional experiment dependencies (at most 200; dataset, metric, baseline, model, method or software) each carry verified cites or a written waiver and select stored v3. Optional writing points (40 per section) require citation presence in their own anchor windows; claims/evidence never establish support. Points select stored v2; no dependencies or points keep v1. No automatic routing or relevance judgment. Starts no build/controller/network calls.", inputSchema: obj({study, plan: PAPER_PLAN}, ["study", "plan"]), annotations: write },
|
|
230
|
+
{ name: "ares_paper_plan_show", description: "Read the optional paper citation plan, routing coverage (included references routed/total) and dependency coverage (cited/waived/total). Revalidates current references; starts no build/controller/network calls or writes.", inputSchema: obj({study}, ["study"]), annotations: read },
|
|
231
|
+
{ name: "ares_paper_build", description: "Check the bounded manuscript or slides and refuse blocking findings before writing. Commit rendered Markdown, versioned evidence, and paper.built together; identical inputs/outputs record nothing. Unknown evidence versions are preserved. The no-arg paper.build plan step emits the committed evidence {sha256} for downstream gates. Starts no controller, executor or network calls.", inputSchema: obj({ study, doc: paperDoc }, ["study"]), annotations: write },
|
|
232
|
+
{ name: "ares_paper_render_record", description: "Record an externally rendered document of the current build under paper/build/render/ with its renderReceipt v1 and one paper.rendered event. Refuses before any write unless the receipt's evidence and manuscript hashes match the current build and the file's SHA-256 matches a receipt output; regular files only, at most 64 MiB. Identical file and receipt record nothing. Never runs a renderer or judges fidelity.", inputSchema: obj({ study, doc: paperDoc, file: text(4096), receipt: text(4096) }, ["study", "file", "receipt"]), annotations: write },
|
|
233
|
+
{ name: "ares_paper_render_show", description: "Read-only: the last recorded render and whether it matches the current build. A rebuild with a new evidence hash makes it stale without deleting it.", inputSchema: obj({ study, doc: paperDoc }, ["study"]), annotations: read },
|
|
234
|
+
{ name: "ares_renderer_set", description: "Set this machine's renderer for the study: an argv array (program first, then arguments with {study} and {out} placeholders) and an optional wall time in seconds. Stored under the family home, never in the study or plan.json; the paper.render plan step runs it.", inputSchema: obj({ study, command: { type: "array", minItems: 1, maxItems: 64, items: text(4096) }, timeoutS: { type: "integer", minimum: 1, maximum: 86400 } }, ["study", "command"]), annotations: write },
|
|
235
|
+
{ name: "ares_renderer_show", description: "Read-only: this machine's renderer for the study, or that none is configured.", inputSchema: obj({ study }, ["study"]), annotations: read },
|
|
236
|
+
{ name: "ares_renderer_check", description: "Read-only: check the renderer configuration and that its program is on PATH, without running it.", inputSchema: obj({ study }, ["study"]), annotations: read },
|
|
237
|
+
{ name: "ares_paper_check", description: "Read-only manuscript readiness check: positioned bare-number, placeholder, citation, optional paper-plan scope and missing-negative-result findings plus every literal escape. Experiment numbers require closed evidence; survey checks citations and refuses experiment refs. Reads bounded paper/manuscript.md or paper/slides.md, starts no build/controller/network calls.", inputSchema: obj({ study, doc: paperDoc }, ["study"]), annotations: read },
|
|
197
238
|
{ name: "ares_cite_check", description: "Check [@key] citations in a draft against verified references; lists unknown and unverified keys.", inputSchema: obj({ study, draft: { type: "string", minLength: 1, maxLength: 4096 } }, ["study", "draft"]), annotations: read },
|
|
198
239
|
{ name: "ares_playbook", description: "Standalone literature, experiment and plan/conductor workflows, CLI-only controller startup, gate rules and evidence boundaries.", inputSchema: obj({}, []), annotations: read },
|
|
199
240
|
];
|
|
@@ -252,6 +293,8 @@ export function createAresMcp(env: NodeJS.ProcessEnv, http: Http = createHttp(en
|
|
|
252
293
|
ares_scope_set: a => ops.scope(dir(a), a.scope, ctx),
|
|
253
294
|
ares_idea_add: a => ops.ideaAdd(dir(a), a.idea, ctx),
|
|
254
295
|
ares_idea_decide: a => ops.ideaDecide(dir(a), a.id as string, { decision: a.decision, reason: a.reason, ...(a.cause !== undefined ? { cause: a.cause } : {}), ...(a.retryWhen !== undefined ? { retryWhen: a.retryWhen } : {}), ...(a.attempts !== undefined ? { attempts: a.attempts } : {}), ...(a.commit !== undefined ? { commit: a.commit } : {}) }, ctx),
|
|
296
|
+
ares_idea_categories: a => ops.ideaCategories(dir(a), a.categories, ctx),
|
|
297
|
+
ares_idea_report: a => ops.ideaReport(dir(a), { ...(a.run !== undefined ? { run: a.run as string } : {}), ...(a.window !== undefined ? { window: a.window as number } : {}) }),
|
|
255
298
|
ares_investigate_show: a => ops.investigateShow(dir(a)),
|
|
256
299
|
ares_investigate_close: a => ops.investigateClose(dir(a), ctx),
|
|
257
300
|
ares_ablate_add: a => ops.ablateAdd(dir(a), a.ablation, ctx),
|
|
@@ -261,6 +304,11 @@ export function createAresMcp(env: NodeJS.ProcessEnv, http: Http = createHttp(en
|
|
|
261
304
|
ares_final_close: a => ops.finalClose(dir(a), ctx),
|
|
262
305
|
ares_final_seeds: a => ops.finalSeeds(dir(a), a.final, ctx),
|
|
263
306
|
ares_selection_set: a => ops.selection(dir(a), a.selection, ctx),
|
|
307
|
+
ares_selection_calibrate: a => ops.selectionCalibrate(dir(a), {
|
|
308
|
+
fromRun: a.fromRun as string,
|
|
309
|
+
...(a.nullCommit === undefined ? {} : { nullCommit: a.nullCommit as string }),
|
|
310
|
+
...(a.z === undefined ? {} : { z: a.z as number }),
|
|
311
|
+
}, ctx),
|
|
264
312
|
ares_protocol_set: a => ops.protocol(dir(a), a.protocol, ctx),
|
|
265
313
|
ares_harness_set: a => ops.harnessSet(dir(a), a.round, ctx),
|
|
266
314
|
ares_harness_show: a => ops.harnessShow(dir(a), a.round as string | undefined),
|
|
@@ -294,10 +342,15 @@ export function createAresMcp(env: NodeJS.ProcessEnv, http: Http = createHttp(en
|
|
|
294
342
|
ares_review_resolve: a => ops.reviewResolve(dir(a), a.target as string, a.reason as string, ctx),
|
|
295
343
|
ares_review_show: a => ops.reviewShow(dir(a)),
|
|
296
344
|
ares_review_checklist: () => ops.reviewChecklistShow(),
|
|
297
|
-
ares_paper_build: a => ops.paperBuild(dir(a), ctx),
|
|
345
|
+
ares_paper_build: a => ops.paperBuild(dir(a), ctx, paperDocument(a.doc)),
|
|
346
|
+
ares_paper_render_record: a => ops.paperRenderRecord(dir(a), absolute(a.file, "file"), absolute(a.receipt, "receipt"), ctx, paperDocument(a.doc)),
|
|
347
|
+
ares_paper_render_show: a => ops.paperRenderShow(dir(a), paperDocument(a.doc)),
|
|
348
|
+
ares_renderer_set: a => ops.rendererSet(dir(a), { command: a.command, ...(a.timeoutS !== undefined ? { timeoutS: a.timeoutS } : {}) }, env),
|
|
349
|
+
ares_renderer_show: a => ops.rendererShow(dir(a), env),
|
|
350
|
+
ares_renderer_check: a => ops.rendererCheck(dir(a), env),
|
|
298
351
|
ares_paper_plan_set: a => ops.paperPlanSet(dir(a), a.plan, ctx),
|
|
299
352
|
ares_paper_plan_show: a => ops.paperPlanShow(dir(a)),
|
|
300
|
-
ares_paper_check: a => ops.paperCheck(dir(a)),
|
|
353
|
+
ares_paper_check: a => ops.paperCheck(dir(a), paperDocument(a.doc)),
|
|
301
354
|
ares_cite_check: a => ops.cite(dir(a), absolute(a.draft, "draft")),
|
|
302
355
|
ares_playbook: () => ({ playbook: PLAYBOOK }),
|
|
303
356
|
};
|
package/src/memory/archive.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
+
import { paperEventFor } from "../paper/document.ts";
|
|
1
2
|
import {recheckLessonExports, boundLessonExportBatch} from "../harness/lesson-candidates.ts";
|
|
2
3
|
import type {SkillCheckOptions} from "./skill-check.ts";
|
|
3
4
|
import { ACCEPT_ARTIFACTS } from "../autonomy.ts";
|
|
4
5
|
import { requireCopilotAccept } from "../copilot.ts";
|
|
5
|
-
import { commit, prepareCommit, openStudy, plain, sha256, type Actor, type LedgerEvent } from "../study.ts";
|
|
6
|
+
import { commit, prepareCommit, openStudy, plain, readLedger, sha256, type Actor, type LedgerEvent } from "../study.ts";
|
|
7
|
+
import { renderSummary } from "../paper/render.ts";
|
|
8
|
+
const readLedgerSafe = (dir: string) => { try { return readLedger(dir); } catch { return []; } };
|
|
6
9
|
import { canonical } from "../plan/state.ts";
|
|
7
10
|
import { createAmemClient, type AmemNote } from "./amem.ts";
|
|
8
11
|
import { deriveLessons, readLessonSources } from "./lessons.ts";
|
|
@@ -10,7 +13,7 @@ import type { ProcessRunner } from "../exp/executor.ts";
|
|
|
10
13
|
|
|
11
14
|
export const ARCHIVE_NOTES = 200;
|
|
12
15
|
export interface ArchiveReceipt { sha256: string; id: string }
|
|
13
|
-
export interface ArchivePreview { recovery?: string; fingerprint: string; notes: { sha256: string; note: AmemNote }[] }
|
|
16
|
+
export interface ArchivePreview { recovery?: string; fingerprint: string; notes: { sha256: string; note: AmemNote }[]; render?: { current: boolean; reason: string | null } }
|
|
14
17
|
export interface ArchiveResult extends ArchivePreview { written: ArchiveReceipt[]; remaining: number }
|
|
15
18
|
/** Carries receipt progress for adapters; CLI/MCP retain the existing retry instruction verbatim. */
|
|
16
19
|
export class ArchivePartialError extends Error {
|
|
@@ -43,7 +46,9 @@ export function previewArchive(dir: string): ArchivePreview {
|
|
|
43
46
|
const sources = readLessonSources(dir), notes = deriveLessons(sources), known = new Set(archiveReceiptIndex(sources.events).keys());
|
|
44
47
|
const unique = new Map(notes.map(note => [sha256(canonical(note)), note]));
|
|
45
48
|
const pending = [...unique].filter(([hash]) => !known.has(hash)).map(([sha256, note]) => ({ sha256, note }));
|
|
46
|
-
|
|
49
|
+
// Render status is display-only and never enters the fingerprint; shown once a render was recorded (#162).
|
|
50
|
+
const render = readLedgerSafe(dir).some(event => paperEventFor(event, "paper.rendered")) ? { render: renderSummary(dir) } : {};
|
|
51
|
+
return {fingerprint: sha256(canonical(notes)), notes: pending, ...render, ...(sources.contrastNotes?.length ? {recovery: "Receipt-only dedupe: if an earlier archive was interrupted after amem add, operator reconciliation is required before retry; unreceipted writes cannot be detected and may duplicate"} : {})};
|
|
47
52
|
}
|
|
48
53
|
/** Preview and confirmed export use the same note/source bounds and ordered prefix. */
|
|
49
54
|
export function archiveExportBatch(dir: string, notes: ArchivePreview["notes"]) {
|
package/src/paper/build.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { paperDocument, paperEventFor, paperSourcePath, type PaperDocument } from "./document.ts";
|
|
2
|
+
import { figuresStillMatch, validFigureEvidence, type FigureEvidence } from "./figures.ts";
|
|
1
3
|
import { requireCopilotAccept } from "../copilot.ts";
|
|
2
4
|
import { existsSync } from "node:fs";
|
|
3
|
-
import { join } from "node:path";
|
|
5
|
+
import { basename, join } from "node:path";
|
|
4
6
|
import { assertWritable, commit, openStudy, plain, readLedger, readTextBounded, sha256, type Actor } from "../study.ts";
|
|
5
|
-
import { checkPaper
|
|
7
|
+
import { checkPaper } from "./check.ts";
|
|
6
8
|
import { MANUSCRIPT_BYTES } from "./placeholders.ts";
|
|
7
9
|
import { readPaperPlanSnapshot } from "./plan.ts";
|
|
8
10
|
|
|
@@ -15,41 +17,50 @@ interface EvidenceBody {
|
|
|
15
17
|
source: { file: string; sha256: string };
|
|
16
18
|
}[];
|
|
17
19
|
}
|
|
18
|
-
export type PaperEvidence = EvidenceBody & ({ v: 1 } | { v: 2; planSha256: string });
|
|
20
|
+
export type PaperEvidence = EvidenceBody & ({ v: 1 } | { v: 2; planSha256: string } | { v: 3; planSha256: string; figures: FigureEvidence[] });
|
|
19
21
|
/** Legacy evidence stays readable; plan-bound evidence requires a reader that understands its binding. */
|
|
20
|
-
export function paperEvidenceVersion(raw: unknown): 1 | 2 {
|
|
21
|
-
if (!plain(raw) || (raw.v !== 1 && raw.v !== 2)) throw new Error("paper evidence: unsupported version; use an ares version that supports it, keeping paper/build/evidence.json unchanged");
|
|
22
|
+
export function paperEvidenceVersion(raw: unknown): 1 | 2 | 3 {
|
|
23
|
+
if (!plain(raw) || (raw.v !== 1 && raw.v !== 2 && raw.v !== 3)) throw new Error("paper evidence: unsupported version; use an ares version that supports it, keeping paper/build/evidence.json unchanged");
|
|
22
24
|
if (raw.v === 2 && (Object.keys(raw).some(key => !["v", "manuscriptSha256", "placeholders", "planSha256"].includes(key)) || typeof raw.planSha256 !== "string" || !/^[a-f0-9]{64}$/.test(raw.planSha256))) throw new Error("paper evidence: invalid v2 plan binding or unknown field; restore the last valid paper/build/evidence.json, then run ares paper check and paper build");
|
|
25
|
+
if (raw.v === 3 && (Object.keys(raw).some(key => !["v", "manuscriptSha256", "placeholders", "planSha256", "figures"].includes(key))
|
|
26
|
+
|| typeof raw.planSha256 !== "string" || !/^[a-f0-9]{64}$/.test(raw.planSha256) || !validFigureEvidence(raw.figures))) {
|
|
27
|
+
throw new Error("paper evidence: invalid v3 plan binding or figure evidence; restore paper/build/evidence.json, then run ares paper check and paper build");
|
|
28
|
+
}
|
|
23
29
|
return raw.v;
|
|
24
30
|
}
|
|
25
|
-
export function paperBuildPaths(dir: string
|
|
31
|
+
export function paperBuildPaths(dir: string, doc: PaperDocument = "manuscript") {
|
|
32
|
+
return { manuscript: join(dir, "paper", "build", `${doc}.md`), evidence: join(dir, "paper", "build", doc === "slides" ? "slides.evidence.json" : "evidence.json") };
|
|
33
|
+
}
|
|
26
34
|
function previous(file: string, bound: number): string | undefined {
|
|
27
35
|
if (!existsSync(file)) return undefined;
|
|
28
36
|
try { return readTextBounded(file, bound); }
|
|
29
|
-
catch { throw new Error(`paper build: previous output is unreadable, non-regular, invalid UTF-8 or oversized; restore the last valid
|
|
37
|
+
catch { throw new Error(`paper build: previous output is unreadable, non-regular, invalid UTF-8 or oversized; restore the last valid paper/build/${basename(file)} before rebuilding`); }
|
|
30
38
|
}
|
|
31
|
-
function evidenceBytes(dir: string): string | undefined {
|
|
32
|
-
const oldEvidence = previous(paperBuildPaths(dir).evidence, PAPER_EVIDENCE_BYTES);
|
|
39
|
+
function evidenceBytes(dir: string, doc: PaperDocument): string | undefined {
|
|
40
|
+
const oldEvidence = previous(paperBuildPaths(dir, doc).evidence, PAPER_EVIDENCE_BYTES);
|
|
33
41
|
if (oldEvidence !== undefined) {
|
|
34
42
|
let raw: unknown;
|
|
35
|
-
try { raw = JSON.parse(oldEvidence); } catch { throw new Error(
|
|
43
|
+
try { raw = JSON.parse(oldEvidence); } catch { throw new Error(`paper evidence: invalid JSON; restore the last valid paper/build/${doc === "slides" ? "slides.evidence.json" : "evidence.json"} before rebuilding`); }
|
|
36
44
|
paperEvidenceVersion(raw);
|
|
37
45
|
}
|
|
38
46
|
return oldEvidence;
|
|
39
47
|
}
|
|
40
|
-
function calculatePaper(dir: string) {
|
|
41
|
-
const report = checkPaper(dir);
|
|
48
|
+
function calculatePaper(dir: string, doc: PaperDocument) {
|
|
49
|
+
const report = checkPaper(dir, doc);
|
|
42
50
|
if (!report.ok) {
|
|
43
51
|
const blocking = report.findings.filter(f => f.severity === "blocking");
|
|
44
52
|
const reasons = blocking.slice(0, 10).map(f => `${f.code} at ${f.line}:${f.column}`).join(", ");
|
|
45
|
-
throw new Error(`paper build: paper check found ${blocking.length} blocking finding(s): ${reasons}; run ares paper check <dir
|
|
53
|
+
throw new Error(`paper build: paper check found ${blocking.length} blocking finding(s): ${reasons}; run ares paper check <dir>${doc === "slides" ? " --doc slides" : ""} --json and fix every finding before rebuilding`);
|
|
46
54
|
}
|
|
47
|
-
const
|
|
55
|
+
const version = report.planSha256 === undefined ? { v: 1 as const }
|
|
56
|
+
: report.figures === undefined ? { v: 2 as const, planSha256: report.planSha256 }
|
|
57
|
+
: { v: 3 as const, planSha256: report.planSha256, figures: report.figures };
|
|
58
|
+
const evidence: PaperEvidence = { ...version, manuscriptSha256: report.manuscriptSha256, placeholders: report.placeholders.map(entry => {
|
|
48
59
|
const token = entry.placeholder;
|
|
49
60
|
return { kind: token.kind, raw: token.raw, start: token.start, end: token.end, line: token.line, column: token.column,
|
|
50
61
|
...(token.kind === "number" ? { ref: token.ref, ...(token.format === undefined ? {} : { format: token.format }) } : {}),
|
|
51
62
|
value: entry.value, rendered: entry.rendered,
|
|
52
|
-
source: entry.source ?? { file:
|
|
63
|
+
source: entry.source ?? { file: `paper/${doc}.md`, sha256: report.manuscriptSha256 },
|
|
53
64
|
};
|
|
54
65
|
}) };
|
|
55
66
|
const text = JSON.stringify(evidence, null, 2) + "\n";
|
|
@@ -58,25 +69,28 @@ function calculatePaper(dir: string) {
|
|
|
58
69
|
return { report, evidence, text, manuscriptSha256: sha256(report.rendered), evidenceSha256: sha256(text) };
|
|
59
70
|
}
|
|
60
71
|
/** Caller holds the study lock. Refusals precede the single output-and-receipt commit. */
|
|
61
|
-
export function buildPaper(dirArg: string, actor: Actor) {
|
|
72
|
+
export function buildPaper(dirArg: string, actor: Actor, doc: PaperDocument = "manuscript") {
|
|
73
|
+
paperDocument(doc);
|
|
62
74
|
const { dir } = openStudy(dirArg);
|
|
63
75
|
requireCopilotAccept(dir, "hypotheses");
|
|
64
|
-
const paths = paperBuildPaths(dir), oldEvidence = evidenceBytes(dir);
|
|
65
|
-
const { report, text, manuscriptSha256, evidenceSha256 } = calculatePaper(dir), oldManuscript = previous(paths.manuscript, MANUSCRIPT_BYTES);
|
|
66
|
-
const receipt = readLedger(dir).findLast(event => event
|
|
76
|
+
const paths = paperBuildPaths(dir, doc), oldEvidence = evidenceBytes(dir, doc);
|
|
77
|
+
const { report, text, manuscriptSha256, evidenceSha256 } = calculatePaper(dir, doc), oldManuscript = previous(paths.manuscript, MANUSCRIPT_BYTES);
|
|
78
|
+
const receipt = readLedger(dir).findLast(event => paperEventFor(event, "paper.built", doc));
|
|
67
79
|
const changed = oldManuscript !== report.rendered || oldEvidence !== text || receipt?.data.manuscriptSha256 !== manuscriptSha256 || receipt.data.evidenceSha256 !== evidenceSha256;
|
|
68
|
-
if (sha256(readTextBounded(
|
|
69
|
-
if (readPaperPlanSnapshot(dir)?.sha256 !== report.planSha256) throw new Error("paper build: source plan was added, removed or changed during checking; rerun ares paper check and paper build on the current paper/plan.json");
|
|
70
|
-
if (
|
|
80
|
+
if (sha256(readTextBounded(paperSourcePath(dir, doc), MANUSCRIPT_BYTES)) !== report.manuscriptSha256) throw new Error("paper build: source manuscript changed during checking; rerun ares paper check and paper build on the current manuscript");
|
|
81
|
+
if (doc === "manuscript" && readPaperPlanSnapshot(dir)?.sha256 !== report.planSha256) throw new Error("paper build: source plan was added, removed or changed during checking; rerun ares paper check and paper build on the current paper/plan.json");
|
|
82
|
+
if (report.figures && !figuresStillMatch(dir, report.figures)) throw new Error("paper build: figure bytes or paths changed during checking; restore the figures and rerun ares paper check and paper build");
|
|
83
|
+
if (changed) commit(dir, [[paths.manuscript, report.rendered, MANUSCRIPT_BYTES], [paths.evidence, text, PAPER_EVIDENCE_BYTES]], [{ actor, type: "paper.built", data: { ...(doc === "slides" ? { doc } : {}), manuscriptSha256, evidenceSha256, sourceManuscriptSha256: report.manuscriptSha256, ...(report.planSha256 === undefined ? {} : {planSha256: report.planSha256}) } }]);
|
|
71
84
|
return { manuscriptSha256, evidenceSha256, changed };
|
|
72
85
|
}
|
|
73
86
|
|
|
74
87
|
|
|
75
88
|
/** The exact fresh build and both output receipts must agree; never repairs or writes files. */
|
|
76
|
-
export function readCurrentBuild(dirArg: string) {
|
|
77
|
-
|
|
89
|
+
export function readCurrentBuild(dirArg: string, doc: PaperDocument = "manuscript") {
|
|
90
|
+
paperDocument(doc);
|
|
91
|
+
const { dir } = openStudy(dirArg), paths = paperBuildPaths(dir, doc), evidence = evidenceBytes(dir, doc), manuscript = previous(paths.manuscript, MANUSCRIPT_BYTES);
|
|
78
92
|
if (evidence === undefined || manuscript === undefined) throw new Error("paper build: missing output; run ares paper build before reviewing");
|
|
79
|
-
const fresh = calculatePaper(dir), receipt = readLedger(dir).findLast(event => event
|
|
93
|
+
const fresh = calculatePaper(dir, doc), receipt = readLedger(dir).findLast(event => paperEventFor(event, "paper.built", doc));
|
|
80
94
|
if (evidence !== fresh.text || manuscript !== fresh.report.rendered || receipt?.data.manuscriptSha256 !== fresh.manuscriptSha256 || receipt.data.evidenceSha256 !== fresh.evidenceSha256 || receipt.data.sourceManuscriptSha256 !== fresh.report.manuscriptSha256) throw new Error("paper build: stale outputs or missing/mismatched receipt; run ares paper check and ares paper build before reviewing");
|
|
81
95
|
return { manuscriptSha256: fresh.manuscriptSha256, evidenceSha256: fresh.evidenceSha256, check: fresh.report };
|
|
82
96
|
}
|