@staix/agent-research 0.2.1 → 0.3.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 +129 -0
- package/README.md +261 -24
- package/package.json +2 -2
- package/src/cli.ts +117 -10
- package/src/commands-table.ts +39 -8
- package/src/commands.ts +201 -34
- package/src/exp/artifacts.ts +20 -2
- package/src/exp/attempts.ts +505 -65
- package/src/exp/executor.ts +264 -17
- package/src/exp/final.ts +1 -1
- package/src/exp/logs.ts +25 -12
- package/src/exp/metrics.ts +8 -9
- package/src/exp/pipeline.ts +92 -0
- package/src/exp/protocol.ts +87 -20
- package/src/exp/retention-script.ts +649 -0
- package/src/exp/retention.ts +70 -0
- package/src/exp/reuse-admission.ts +65 -0
- package/src/exp/reuse-contract.ts +48 -0
- package/src/exp/reuse-runtime.ts +91 -0
- package/src/exp/reuse.ts +87 -0
- package/src/exp/selection.ts +1 -1
- package/src/exp/snapshot.ts +30 -10
- 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/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/manifest.ts +13 -6
- package/src/mcp-tools.ts +123 -25
- package/src/mcp.ts +4 -0
- package/src/memory/amem-show.ts +135 -0
- package/src/memory/amem.ts +3 -0
- package/src/memory/archive.ts +17 -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 +16 -7
- package/src/paper/check.ts +37 -10
- package/src/paper/headings.ts +39 -0
- package/src/paper/hygiene.ts +153 -0
- package/src/paper/placeholders.ts +16 -1
- 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 +102 -9
- package/src/paper/scopes.ts +51 -0
- package/src/plan/definition.ts +5 -1
- package/src/plan/hub.ts +6 -0
- package/src/plan/state.ts +5 -0
- package/src/playbook.ts +35 -20
- package/src/privacy.ts +9 -0
- package/src/provenance.ts +679 -0
- package/src/scope.ts +24 -3
- package/src/study-export.ts +55 -27
- package/src/study.ts +54 -14
- package/src/ui/panel.css +4 -0
- package/src/ui/panel.js +263 -6
- package/src/ui/plugin.ts +68 -10
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { runOnExecutor, type Executor, type ProcessRunner } from "./executor.ts";
|
|
2
|
+
import { plain } from "../study.ts";
|
|
3
|
+
import { RETENTION_SCRIPT } from "./retention-script.ts";
|
|
4
|
+
|
|
5
|
+
export const RETENTION_CAP = 1024 * 1024 * 1024;
|
|
6
|
+
export const RETENTION_ADMIN_RESERVATION = 256 * 1024;
|
|
7
|
+
export const RETENTION_RESERVATION = 256 * 1024 * 1024 + 256 * 1024 + RETENTION_ADMIN_RESERVATION;
|
|
8
|
+
export interface RetainedRef { attemptId: string; stage: string; sha256: string }
|
|
9
|
+
export interface RetainedFile { path: string; sha256: string; bytes: number }
|
|
10
|
+
export interface RetainedIdentity {
|
|
11
|
+
definitionHash: string; inputHashes: Record<string, string>; codeTree: string;
|
|
12
|
+
image: string; argvHash: string; envHash: string; seed: number; producerVersion: string;
|
|
13
|
+
}
|
|
14
|
+
export interface RetainedManifest {
|
|
15
|
+
v: 1; studyId: string; attemptId: string; stage: string; identity: RetainedIdentity; reuseKey?: string;
|
|
16
|
+
observed: { containerId: string; endedAt: string; exitCode: 0 };
|
|
17
|
+
outputs: Record<string, string>; files: RetainedFile[]; directories: string[];
|
|
18
|
+
}
|
|
19
|
+
export type RetainedInput = { task: string } | { ref: RetainedRef; output?: string };
|
|
20
|
+
export type RetentionRequest = { studyId: string } & (
|
|
21
|
+
| { op: "reserve"; attemptId: string; capBytes?: number; reservationBytes?: number }
|
|
22
|
+
| { op: "release"; attemptId: string }
|
|
23
|
+
| { op: "snapshot"; attemptId: string; source: string }
|
|
24
|
+
| { op: "seal"; attemptId: string; stage: string; source: string; outputs: Record<string, string>; identity: RetainedIdentity; observed: RetainedManifest["observed"]; metadataLimit?: number; reuseKey?: string }
|
|
25
|
+
| { op: "verify"; ref: RetainedRef }
|
|
26
|
+
| { op: "lookup"; attemptId: string; stage: string; key: string; expected: RetainedIdentity; outputs: Record<string, string> }
|
|
27
|
+
| { op: "materialize"; attemptId: string; stage: string; target: string; taskRoot: string; expectedTaskTreeHash?: string; codeRoot?: string; expectedCodeHash?: string; inputs: Record<string, RetainedInput> }
|
|
28
|
+
| { op: "inspect"; offset?: number; limit?: number }
|
|
29
|
+
| { op: "prune"; refs: RetainedRef[]; fingerprint?: string }
|
|
30
|
+
);
|
|
31
|
+
export interface RetentionResult {
|
|
32
|
+
op: RetentionRequest["op"];
|
|
33
|
+
hit?: boolean; reason?: "missing" | "pruned" | "corrupt" | "unsupported" | "ineligible-source" | "scan-cap"; ref?: RetainedRef;
|
|
34
|
+
manifest?: RetainedManifest; sha256?: string; manifestBytes?: number; sidecarBytes?: number;
|
|
35
|
+
inputHashes?: Record<string, string>; files?: RetainedFile[];
|
|
36
|
+
entries?: { ref: RetainedRef; bytes: number; tombstone: boolean; active: boolean }[];
|
|
37
|
+
capBytes?: number; usedBytes?: number; reservedBytes?: number; administrativeBytes?: number;
|
|
38
|
+
reservations?: { attemptId: string; active: boolean; reservationBytes: number }[];
|
|
39
|
+
fingerprint?: string; pruned?: number;
|
|
40
|
+
archivedReservations?: number; offset?: number; limit?: number; total?: number; remaining?: number;
|
|
41
|
+
}
|
|
42
|
+
const RETENTION_NEXT_STEP = "inspect retained evidence and restore integrity before retrying";
|
|
43
|
+
/** A native reason that names its next step after '; ' keeps it; the generic repair advice would contradict that step. */
|
|
44
|
+
const withNextStep = (reason: string) => reason.includes("; ") ? reason : `${reason}; ${RETENTION_NEXT_STEP}`;
|
|
45
|
+
export class RetentionError extends Error {
|
|
46
|
+
constructor(readonly code: "busy" | "transport" | "integrity", readonly retryable: boolean, reason: string) {
|
|
47
|
+
super(`retention: ${withNextStep(reason)}`);
|
|
48
|
+
this.name = "RetentionError";
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** Executor-local bytes only. The caller owns study gates, attempt fences and observed container termination. */
|
|
52
|
+
export async function retainedOperation(executor: Executor, request: RetentionRequest, runner: ProcessRunner): Promise<RetentionResult> {
|
|
53
|
+
const text = JSON.stringify(request);
|
|
54
|
+
if (Buffer.byteLength(text) > 1024 * 1024) throw new Error("retention: request exceeds 1 MiB; reduce the declared manifest or selection");
|
|
55
|
+
let result;
|
|
56
|
+
try {
|
|
57
|
+
result = await runOnExecutor(executor, "python3", ["-I", "-S", "-c", RETENTION_SCRIPT, executor.workdir], runner, {
|
|
58
|
+
stdin: Buffer.from(text), timeoutMs: 300_000, maxOutputBytes: 1024 * 1024,
|
|
59
|
+
});
|
|
60
|
+
} catch { throw new RetentionError("transport", true, "executor operation unavailable"); }
|
|
61
|
+
if (result.exitCode !== 0 || result.timedOut || result.truncated) {
|
|
62
|
+
let reason = "executor operation failed", native = false;
|
|
63
|
+
try { const error: unknown = JSON.parse(result.stdout); if (plain(error) && typeof error.error === "string" && error.error.length <= 300) { reason = error.error; native = true; } } catch { /* Never expose executor stderr, paths or bodies. */ }
|
|
64
|
+
const busy = reason.startsWith("retention operation busy");
|
|
65
|
+
throw new RetentionError(busy ? "busy" : native ? "integrity" : "transport", busy || !native || result.timedOut === true || result.truncated === true, reason);
|
|
66
|
+
}
|
|
67
|
+
let value: unknown; try { value = JSON.parse(result.stdout); } catch { throw new RetentionError("transport", true, "malformed executor receipt"); }
|
|
68
|
+
if (!plain(value) || value.op !== request.op) throw new RetentionError("transport", true, "mismatched executor receipt");
|
|
69
|
+
return value as unknown as RetentionResult;
|
|
70
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { posix } from "node:path";
|
|
2
|
+
import { canonical } from "./protocol.ts";
|
|
3
|
+
import { plain } from "../study.ts";
|
|
4
|
+
import { stageReuseEligibility, stageReuseKey } from "./reuse.ts";
|
|
5
|
+
import { reuseSourceFacts, type StageReuseSourceFacts } from "./reuse-runtime.ts";
|
|
6
|
+
import { retainedOperation, type RetainedRef, type RetainedManifest } from "./retention.ts";
|
|
7
|
+
import { stageRetainedIdentity, type StageReuseReceipt } from "./pipeline.ts";
|
|
8
|
+
import { ARTIFACT_BYTES, ARTIFACT_FILES } from "./artifacts.ts";
|
|
9
|
+
import { OUTPUT_METADATA_BYTES } from "./metrics.ts";
|
|
10
|
+
import { spawnRunner } from "./executor.ts";
|
|
11
|
+
import type { Attempt, AttemptContext, AttemptStage, Evaluation } from "./attempts.ts";
|
|
12
|
+
|
|
13
|
+
export type ReuseDecision = { outcome: "fresh"; reason: string; key?: string; context?: StageReuseSourceFacts; verificationMs: number; materializationMs: number }
|
|
14
|
+
| { outcome: "reused"; reason: "verified-hit"; key: string; context: StageReuseSourceFacts; verificationMs: number; materializationMs: number; source: RetainedRef; record: AttemptStage; receipt: StageReuseReceipt; outputs: Evaluation["outputs"]; manifestBytes: number };
|
|
15
|
+
function validManifest(attempt: Attempt, key: string, ref: RetainedRef, manifest: RetainedManifest): boolean {
|
|
16
|
+
const stage = attempt.pipeline!.definition.candidate.stages[attempt.pipeline!.index]!;
|
|
17
|
+
if (!plain(ref) || !/^[a-f0-9]{16}$/.test(ref.attemptId) || ref.attemptId === attempt.id || ref.stage !== stage.name || !/^[a-f0-9]{64}$/.test(ref.sha256) || !plain(manifest) || manifest.v !== 1 || manifest.studyId !== attempt.studyId || manifest.attemptId !== ref.attemptId || manifest.stage !== stage.name || manifest.reuseKey !== key || canonical(manifest.identity) !== canonical(stageRetainedIdentity(attempt)) || canonical(manifest.outputs) !== canonical(stage.outputs) || !Array.isArray(manifest.files) || manifest.files.length > ARTIFACT_FILES || Buffer.byteLength(JSON.stringify(manifest)) > OUTPUT_METADATA_BYTES) return false;
|
|
18
|
+
const paths = new Set<string>(); let bytes = 0;
|
|
19
|
+
for (const file of manifest.files) {
|
|
20
|
+
if (!plain(file) || typeof file.path !== "string" || !file.path || Buffer.byteLength(file.path) > 4096 || file.path.startsWith("/") || file.path.includes("\\") || /\p{Cc}/u.test(file.path) || file.path.split("/").some(part => !part || part === "." || part === "..") || paths.has(file.path) || typeof file.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(file.sha256) || !Number.isSafeInteger(file.bytes) || file.bytes < 0) return false;
|
|
21
|
+
paths.add(file.path); bytes += file.bytes;
|
|
22
|
+
if (bytes > ARTIFACT_BYTES) return false;
|
|
23
|
+
}
|
|
24
|
+
return true;
|
|
25
|
+
}
|
|
26
|
+
/** Caller holds the current stage ownership/policy fence; native lookup verifies and pins before returning. */
|
|
27
|
+
export async function prepareStageReuse(dir: string, attempt: Attempt, ctx: AttemptContext, sourceAttempt: (id: string) => Attempt): Promise<ReuseDecision> {
|
|
28
|
+
let context: StageReuseSourceFacts | undefined;
|
|
29
|
+
const started = performance.now(), pipeline = attempt.pipeline!, stage = pipeline.definition.candidate.stages[pipeline.index]!;
|
|
30
|
+
const fresh = (reason: string, key?: string): ReuseDecision => ({ outcome: "fresh", reason, ...(key ? { key, ...(context ? { context } : {}) } : {}), verificationMs: performance.now() - started, materializationMs: 0 });
|
|
31
|
+
if (!attempt.reuse || attempt.reuse.mode === "off") return fresh(attempt.reuse?.forceFresh ? "force-fresh" : "mode-off");
|
|
32
|
+
if (["ablate", "final", "posthoc"].includes(attempt.run)) return fresh("phase-fresh");
|
|
33
|
+
const eligibility = stageReuseEligibility({ protocol: pipeline.definition, stage: { kind: "candidate", name: stage.name }, phase: "investigate", mode: "eligible" });
|
|
34
|
+
if (!eligibility.eligible) return fresh(eligibility.reason);
|
|
35
|
+
const facts = await reuseSourceFacts(dir, attempt, ctx);
|
|
36
|
+
if ("reason" in facts) return fresh(facts.reason);
|
|
37
|
+
context = facts;
|
|
38
|
+
const key = stageReuseKey({ protocol: pipeline.definition, stage: { kind: "candidate", name: stage.name }, phase: "investigate", mode: "eligible", studyId: attempt.studyId,
|
|
39
|
+
codeTree: attempt.treeId, codeSnapshotSha256: pipeline.codeSnapshotHash!, inputHashes: pipeline.inputHashes, seed: attempt.seed, ...facts });
|
|
40
|
+
if (attempt.reuse.forceFresh) return fresh("force-fresh", key);
|
|
41
|
+
const result = await retainedOperation(attempt.executor, { op: "lookup", studyId: attempt.studyId, attemptId: attempt.id, stage: stage.name, key, expected: stageRetainedIdentity(attempt), outputs: stage.outputs }, ctx.runner ?? spawnRunner);
|
|
42
|
+
if (result.hit !== true) return fresh(["missing", "pruned", "corrupt", "unsupported", "ineligible-source", "scan-cap"].includes(String(result.reason)) ? result.reason! : "unsupported", key);
|
|
43
|
+
if (!result.ref || !result.manifest || !Number.isSafeInteger(result.manifestBytes) || result.manifestBytes! < 0 || result.manifestBytes! > OUTPUT_METADATA_BYTES || !validManifest(attempt, key, result.ref, result.manifest) || result.manifestBytes! < Buffer.byteLength(JSON.stringify(result.manifest))) return fresh("invalid-hit", key);
|
|
44
|
+
let original: Attempt, record: AttemptStage | undefined;
|
|
45
|
+
try {
|
|
46
|
+
original = sourceAttempt(result.ref.attemptId);
|
|
47
|
+
// A valid done-but-not-succeeded receipt never makes a source eligible: a cancelled or unknown attempt's stages may
|
|
48
|
+
// be partial, so only a succeeded source is admitted, never merely a non-running one.
|
|
49
|
+
if (original.status !== "succeeded" || original.studyId !== attempt.studyId || !original.pipeline || original.treeId !== attempt.treeId || original.seed !== attempt.seed || original.pipeline.codeSnapshotHash !== pipeline.codeSnapshotHash || original.reuse?.stages[stage.name]?.outcome !== "fresh" || original.reuse.stages[stage.name]?.key !== key || canonical(original.executor) !== canonical(attempt.executor) || !original.sealing.candidateHasNoEvaluator || canonical(original.reuse?.stages[stage.name]?.context) !== canonical(facts)) return fresh("ineligible-source", key);
|
|
50
|
+
const completed = original.pipeline.completed.find(parent => parent.name === stage.name && canonical(parent.ref) === canonical(result.ref) && !parent.reuse);
|
|
51
|
+
record = completed?.record;
|
|
52
|
+
if (!record && original.stage === "candidate" && original.pipeline.definition.candidate.stages[original.pipeline.index]?.name === stage.name) record = original.stages.candidate;
|
|
53
|
+
const sourceDefinition = original.pipeline.definition.candidate.stages.find(value => value.name === stage.name);
|
|
54
|
+
if (!record || record.exitCode !== 0 || record.containerId !== result.manifest.observed.containerId || record.network !== "none" || record.user !== attempt.stages.candidate?.user || record.image !== stage.image || canonical(record.argv) !== canonical(stage.command) || canonical(record.limits) !== canonical(attempt.protocol.limits) || canonical(sourceDefinition) !== canonical(stage)) return fresh("ineligible-source", key);
|
|
55
|
+
const outputRoot = posix.join(original.executor.workdir, original.studyId, original.id, "stages", stage.name, "output");
|
|
56
|
+
if (!Array.isArray(record.evidence?.outputs) || result.manifest.files.some(file => !record!.evidence!.outputs.some(observed => observed.path === posix.join(outputRoot, file.path) && observed.sha256 === file.sha256 && observed.bytes === file.bytes))) return fresh("invalid-hit", key);
|
|
57
|
+
} catch { return fresh("source-unavailable", key); }
|
|
58
|
+
const duration = Date.parse(record.endedAt ?? "") - Date.parse(record.startedAt);
|
|
59
|
+
const wallSeconds = Number.isFinite(duration) && duration >= 0 ? duration / 1000 : "unknown";
|
|
60
|
+
const gpuHours = wallSeconds !== "unknown" && Number.isFinite(record.limits.gpus) ? wallSeconds * record.limits.gpus / 3600 : "unknown";
|
|
61
|
+
const verificationMs = performance.now() - started;
|
|
62
|
+
const receipt: StageReuseReceipt = { v: 1, key, context: facts, source: result.ref, original: { wallSeconds, gpuHours, cpuSeconds: "unknown" }, verificationMs, materializationMs: 0 };
|
|
63
|
+
return { outcome: "reused", reason: "verified-hit", key, context: facts, verificationMs, materializationMs: 0, source: result.ref, record, receipt,
|
|
64
|
+
manifestBytes: result.manifestBytes!, outputs: result.manifest.files.map(file => ({ ...file, path: posix.join(attempt.executor.workdir, attempt.studyId, ".retained", "objects", result.ref!.attemptId, stage.name, "data", file.path) })) };
|
|
65
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { onlyKeys, plain } from "../study.ts";
|
|
2
|
+
|
|
3
|
+
/** A reviewable declaration, never evidence of determinism or an approval receipt. */
|
|
4
|
+
export interface StageReuseContract {
|
|
5
|
+
v: 1;
|
|
6
|
+
kind: "pure-artifact";
|
|
7
|
+
inputs: "declared-only";
|
|
8
|
+
externalState: "none";
|
|
9
|
+
writableState: "fresh-output-only";
|
|
10
|
+
modelOutputs: "forbidden";
|
|
11
|
+
determinism: "byte-exact";
|
|
12
|
+
toolchain: { description: string; documentationSha256: string };
|
|
13
|
+
}
|
|
14
|
+
export const REUSE_DESCRIPTION_BYTES = 1024;
|
|
15
|
+
export const STAGE_REUSE_CONTRACT_SCHEMA = {
|
|
16
|
+
type: "object", additionalProperties: false,
|
|
17
|
+
required: ["v", "kind", "inputs", "externalState", "writableState", "modelOutputs", "determinism", "toolchain"],
|
|
18
|
+
properties: {
|
|
19
|
+
v: { type: "integer", enum: [1] }, kind: { type: "string", enum: ["pure-artifact"] },
|
|
20
|
+
inputs: { type: "string", enum: ["declared-only"] }, externalState: { type: "string", enum: ["none"] },
|
|
21
|
+
writableState: { type: "string", enum: ["fresh-output-only"] }, modelOutputs: { type: "string", enum: ["forbidden"] },
|
|
22
|
+
determinism: { type: "string", enum: ["byte-exact"] },
|
|
23
|
+
toolchain: { type: "object", additionalProperties: false, required: ["description", "documentationSha256"], properties: {
|
|
24
|
+
description: { type: "string", minLength: 1, maxLength: REUSE_DESCRIPTION_BYTES },
|
|
25
|
+
documentationSha256: { type: "string", minLength: 64, maxLength: 64 },
|
|
26
|
+
} },
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
export function reuseIdentityText(raw: unknown, label: string, bytes = 128): string {
|
|
30
|
+
if (typeof raw !== "string" || !raw.trim() || /\p{Cc}/u.test(raw) || Buffer.byteLength(raw) > bytes) throw new Error(`${label}: nonblank bounded text without control characters required`);
|
|
31
|
+
return raw;
|
|
32
|
+
}
|
|
33
|
+
export function reuseDigest(raw: unknown, label: string, length = 64): string {
|
|
34
|
+
if (typeof raw !== "string" || raw.length !== length || !/^[a-f0-9]+$/.test(raw)) throw new Error(`${label}: ${length} lowercase hex digits required`);
|
|
35
|
+
return raw;
|
|
36
|
+
}
|
|
37
|
+
export function validateReuseContract(raw: unknown): StageReuseContract {
|
|
38
|
+
if (!plain(raw)) throw new Error("stage reuse contract: object required");
|
|
39
|
+
onlyKeys(raw, STAGE_REUSE_CONTRACT_SCHEMA.required, "stage reuse contract");
|
|
40
|
+
if (raw.v !== 1) throw new Error("stage reuse contract: unsupported version; retain the original declaration and use a compatible reader");
|
|
41
|
+
if (raw.kind !== "pure-artifact" || raw.inputs !== "declared-only" || raw.externalState !== "none" || raw.writableState !== "fresh-output-only" || raw.modelOutputs !== "forbidden" || raw.determinism !== "byte-exact") throw new Error("stage reuse contract: declare byte-exact pure artifacts, complete declared inputs, no external state, fresh output only and no model-output caching");
|
|
42
|
+
if (!plain(raw.toolchain)) throw new Error("stage reuse toolchain: documented deterministic toolchain required");
|
|
43
|
+
onlyKeys(raw.toolchain, ["description", "documentationSha256"], "stage reuse toolchain");
|
|
44
|
+
return { v: 1, kind: "pure-artifact", inputs: "declared-only", externalState: "none", writableState: "fresh-output-only", modelOutputs: "forbidden", determinism: "byte-exact", toolchain: {
|
|
45
|
+
description: reuseIdentityText(raw.toolchain.description, "stage reuse toolchain description", REUSE_DESCRIPTION_BYTES),
|
|
46
|
+
documentationSha256: reuseDigest(raw.toolchain.documentationSha256, "stage reuse toolchain documentation digest"),
|
|
47
|
+
} };
|
|
48
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { fileURLToPath } from "node:url";
|
|
2
|
+
import { version } from "../../package.json";
|
|
3
|
+
import { canonical, type ProtocolDefinition } from "./protocol.ts";
|
|
4
|
+
import { readSelection } from "./selection.ts";
|
|
5
|
+
import { readFinalSeeds } from "./final.ts";
|
|
6
|
+
import { runOnExecutor, spawnRunner } from "./executor.ts";
|
|
7
|
+
import { openStudy, plain, readBytesBounded, sha256 } from "../study.ts";
|
|
8
|
+
import type { Attempt, AttemptContext } from "./attempts.ts";
|
|
9
|
+
|
|
10
|
+
export interface StageReuseSourceFacts {
|
|
11
|
+
populationSha256: string;
|
|
12
|
+
runtime: { semantics: string; producerVersion: string };
|
|
13
|
+
platform: { os: string; arch: string; abi: string };
|
|
14
|
+
}
|
|
15
|
+
export type StageReuseSourceMissReason = "unsupported-study" | "outside-investigation" | "population-unavailable" | "population-changed" | "unsupported-gpu-abi" | "producer-runtime-unavailable" | "producer-source-unavailable" | "platform-unavailable" | "unsupported-platform";
|
|
16
|
+
export type StageReuseSourceFactsResult = StageReuseSourceFacts | { reason: StageReuseSourceMissReason };
|
|
17
|
+
export const REUSE_FACTS_OUTPUT_BYTES = 4096, REUSE_FACTS_TIMEOUT_MS = 5000;
|
|
18
|
+
const PRODUCER_SOURCE_BYTES = 256 * 1024;
|
|
19
|
+
const PRODUCER_SOURCES = ["attempts.ts", "pipeline.ts", "executor.ts", "retention-script.ts", "reuse.ts", "reuse-runtime.ts", "reuse-admission.ts", "metrics.ts"] as const;
|
|
20
|
+
const PLATFORM_SCRIPT = String.raw`import hashlib,json,os,platform,subprocess,sys
|
|
21
|
+
cpu={'count':os.cpu_count(),'byteorder':sys.byteorder}
|
|
22
|
+
if sys.platform=='linux':
|
|
23
|
+
with open('/proc/cpuinfo','rb') as f:
|
|
24
|
+
block=f.read(65537).split(b'\n\n',1)[0]
|
|
25
|
+
if len(block)>65536: raise ValueError('unsupported CPU metadata')
|
|
26
|
+
keys={'vendor_id','cpu family','model','model name','stepping','microcode','flags','Features','CPU implementer','CPU architecture','CPU variant','CPU part','CPU revision'}
|
|
27
|
+
fields={}
|
|
28
|
+
for line in block.decode('utf8',errors='strict').splitlines():
|
|
29
|
+
if ':' in line:
|
|
30
|
+
key,value=line.split(':',1)
|
|
31
|
+
if key.strip() in keys: fields[key.strip()]=value.strip()
|
|
32
|
+
if not fields: raise ValueError('unsupported CPU metadata')
|
|
33
|
+
cpu['fields']=fields
|
|
34
|
+
elif sys.platform=='darwin':
|
|
35
|
+
cpu['fields']={key:subprocess.check_output(['/usr/sbin/sysctl','-n',key],timeout=1).decode().strip() for key in ['hw.model','hw.cpufamily','hw.cpusubtype']}
|
|
36
|
+
else: raise ValueError('unsupported CPU ABI')
|
|
37
|
+
cpu_hash=hashlib.sha256(json.dumps(cpu,sort_keys=True,separators=(',',':')).encode()).hexdigest()
|
|
38
|
+
libc=platform.libc_ver()
|
|
39
|
+
print(json.dumps({'v':1,'os':sys.platform,'arch':platform.machine(),'kernel':platform.release(),'libc':{'name':libc[0],'version':libc[1]},'macVersion':platform.mac_ver()[0],'cpuSha256':cpu_hash,'uid':os.getuid(),'gid':os.getgid()},separators=(',',':')))`;
|
|
40
|
+
const identity = (value: unknown): value is string => typeof value === "string" && !!value.trim() && !/\p{Cc}/u.test(value) && Buffer.byteLength(value) <= 128;
|
|
41
|
+
|
|
42
|
+
function population(dir: string, protocol: ProtocolDefinition) {
|
|
43
|
+
const selection = readSelection(dir, protocol), reservedSeeds = readFinalSeeds(dir, protocol);
|
|
44
|
+
// Null is deliberate: an absent file is different from any present reservation value.
|
|
45
|
+
return { selection, sha256: sha256(canonical({ v: 1, selection: selection ?? null, reservedSeeds: reservedSeeds ?? null })) };
|
|
46
|
+
}
|
|
47
|
+
function producerSemantics(): string | undefined {
|
|
48
|
+
const bun = process.versions.bun;
|
|
49
|
+
if (!identity(bun)) return undefined;
|
|
50
|
+
const sources = PRODUCER_SOURCES.map(name => [name, sha256(readBytesBounded(fileURLToPath(new URL(`./${name}`, import.meta.url)), PRODUCER_SOURCE_BYTES))]);
|
|
51
|
+
return `ares-stage-v2/reuse-1:${sha256(canonical({ bun, sources }))}`;
|
|
52
|
+
}
|
|
53
|
+
export function isInvestigationRun(run: string, selection: { run: string } | undefined): boolean {
|
|
54
|
+
return selection?.run === run && !["ablate", "final", "posthoc"].includes(run);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Read-only, source-owned facts. Caller still owns current design/policy/budget fencing at admission. */
|
|
58
|
+
export async function reuseSourceFacts(dir: string, attempt: Attempt, ctx: AttemptContext): Promise<StageReuseSourceFactsResult> {
|
|
59
|
+
const protocol = attempt.pipeline?.definition ?? attempt.protocol;
|
|
60
|
+
let before: ReturnType<typeof population>;
|
|
61
|
+
try {
|
|
62
|
+
const { study } = openStudy(dir);
|
|
63
|
+
if (study.mode !== "experiment" || study.id !== attempt.studyId) return { reason: "unsupported-study" };
|
|
64
|
+
before = population(dir, protocol);
|
|
65
|
+
} catch { return { reason: "population-unavailable" }; }
|
|
66
|
+
if (attempt.stage !== "candidate" || !isInvestigationRun(attempt.run, before.selection)) return { reason: "outside-investigation" };
|
|
67
|
+
if (protocol.limits.gpus > 0) return { reason: "unsupported-gpu-abi" };
|
|
68
|
+
if (!identity(process.versions.bun)) return { reason: "producer-runtime-unavailable" };
|
|
69
|
+
let semantics: string | undefined;
|
|
70
|
+
try { semantics = producerSemantics(); } catch { return { reason: "producer-source-unavailable" }; }
|
|
71
|
+
if (!semantics) return { reason: "producer-runtime-unavailable" };
|
|
72
|
+
let response;
|
|
73
|
+
try {
|
|
74
|
+
response = await runOnExecutor(attempt.executor, "python3", ["-I", "-S", "-c", PLATFORM_SCRIPT], ctx.runner ?? spawnRunner, { timeoutMs: REUSE_FACTS_TIMEOUT_MS, maxOutputBytes: REUSE_FACTS_OUTPUT_BYTES });
|
|
75
|
+
} catch { return { reason: "platform-unavailable" }; }
|
|
76
|
+
if (response.exitCode !== 0 || response.timedOut || response.truncated) return { reason: "platform-unavailable" };
|
|
77
|
+
let value: unknown;
|
|
78
|
+
try { value = JSON.parse(response.stdout); } catch { return { reason: "unsupported-platform" }; }
|
|
79
|
+
if (!plain(value) || Object.keys(value).some(key => !["v", "os", "arch", "kernel", "libc", "macVersion", "cpuSha256", "uid", "gid"].includes(key)) || value.v !== 1 || !Number.isSafeInteger(value.uid) || (value.uid as number) < 0 || !Number.isSafeInteger(value.gid) || (value.gid as number) < 0 || typeof value.cpuSha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.cpuSha256) || !["linux", "darwin"].includes(String(value.os)) || !identity(value.os) || !identity(value.arch) || !["x86_64", "amd64", "AMD64", "aarch64", "arm64"].includes(value.arch) || !identity(value.kernel) || !plain(value.libc) || Object.keys(value.libc).some(key => !["name", "version"].includes(key))) return { reason: "unsupported-platform" };
|
|
80
|
+
if (value.os === "linux" && (!identity(value.libc.name) || !identity(value.libc.version))) return { reason: "unsupported-platform" };
|
|
81
|
+
if (value.os === "darwin" && !identity(value.macVersion)) return { reason: "unsupported-platform" };
|
|
82
|
+
if (typeof value.macVersion !== "string" || typeof value.libc.name !== "string" || typeof value.libc.version !== "string" || Buffer.byteLength(value.macVersion) > 128 || Buffer.byteLength(value.libc.name) > 128 || Buffer.byteLength(value.libc.version) > 128 || /\p{Cc}/u.test(`${value.macVersion}${value.libc.name}${value.libc.version}`)) return { reason: "unsupported-platform" };
|
|
83
|
+
try {
|
|
84
|
+
const current = openStudy(dir).study;
|
|
85
|
+
if (current.mode !== "experiment" || current.id !== attempt.studyId) return { reason: "population-changed" };
|
|
86
|
+
const after = population(dir, protocol);
|
|
87
|
+
if (after.sha256 !== before.sha256 || after.selection?.run !== attempt.run) return { reason: "population-changed" };
|
|
88
|
+
} catch { return { reason: "population-changed" }; }
|
|
89
|
+
return { populationSha256: before.sha256, runtime: { semantics, producerVersion: version }, platform: { os: value.os, arch: value.arch,
|
|
90
|
+
abi: `cpu-v1:${sha256(canonical({ observed: value, executor: attempt.executor }))}` } };
|
|
91
|
+
}
|
package/src/exp/reuse.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { onlyKeys, plain, sha256 } from "../study.ts";
|
|
2
|
+
import { canonical, validateProtocolDefinition, type ProtocolDefinition } from "./protocol.ts";
|
|
3
|
+
import type { CandidateStage, ProtocolV2 } from "./stages.ts";
|
|
4
|
+
import { reuseDigest, reuseIdentityText } from "./reuse-contract.ts";
|
|
5
|
+
export { validateReuseContract, type StageReuseContract } from "./reuse-contract.ts";
|
|
6
|
+
|
|
7
|
+
export const STAGE_REUSE_KEY_VERSION = 1;
|
|
8
|
+
export interface StageReuseEligibilityInput {
|
|
9
|
+
protocol: ProtocolDefinition;
|
|
10
|
+
stage: { kind: "candidate"; name: string } | { kind: "evaluator" };
|
|
11
|
+
phase: string;
|
|
12
|
+
mode?: "off" | "eligible";
|
|
13
|
+
forceFresh?: boolean;
|
|
14
|
+
}
|
|
15
|
+
export type StageReuseReason = "force-fresh" | "mode-off" | "phase-fresh" | "evaluator-fresh" | "legacy-fresh" | "undeclared-contract" | "no-artifact-outputs" | "declared-pure-artifact";
|
|
16
|
+
/** Structural eligibility only; no current permission, gate, byte availability or hit is asserted. */
|
|
17
|
+
export interface StageReuseEligibility { v: 1; kind: "declaration-only"; eligible: boolean; reason: StageReuseReason }
|
|
18
|
+
export interface StageReuseKeyInput extends StageReuseEligibilityInput {
|
|
19
|
+
studyId: string;
|
|
20
|
+
populationSha256: string;
|
|
21
|
+
codeTree: string;
|
|
22
|
+
codeSnapshotSha256: string;
|
|
23
|
+
inputHashes: Record<string, string>;
|
|
24
|
+
seed: number;
|
|
25
|
+
runtime: { semantics: string; producerVersion: string };
|
|
26
|
+
platform: { os: string; arch: string; abi: string };
|
|
27
|
+
}
|
|
28
|
+
const ELIGIBILITY_KEYS = ["protocol", "stage", "phase", "mode", "forceFresh"];
|
|
29
|
+
function candidate(protocol: ProtocolDefinition, stage: StageReuseEligibilityInput["stage"]): CandidateStage | undefined {
|
|
30
|
+
if (!plain(stage) || (stage.kind !== "candidate" && stage.kind !== "evaluator")) throw new Error("stage reuse selection: candidate or evaluator required");
|
|
31
|
+
onlyKeys(stage, stage.kind === "candidate" ? ["kind", "name"] : ["kind"], "stage reuse selection");
|
|
32
|
+
if (stage.kind === "evaluator") return undefined;
|
|
33
|
+
reuseIdentityText(stage.name, "stage reuse candidate name", 32);
|
|
34
|
+
if (protocol.v === 1) return undefined;
|
|
35
|
+
const selected = protocol.candidate.stages.find(value => value.name === stage.name);
|
|
36
|
+
if (!selected) throw new Error("stage reuse selection: declared candidate name required");
|
|
37
|
+
return selected;
|
|
38
|
+
}
|
|
39
|
+
export function stageReuseEligibility(input: StageReuseEligibilityInput): StageReuseEligibility {
|
|
40
|
+
if (!plain(input)) throw new Error("stage reuse eligibility: object required");
|
|
41
|
+
onlyKeys(input, ELIGIBILITY_KEYS, "stage reuse eligibility");
|
|
42
|
+
const protocol = validateProtocolDefinition(input.protocol), selected = candidate(protocol, input.stage);
|
|
43
|
+
reuseIdentityText(input.phase, "stage reuse phase", 64);
|
|
44
|
+
if (input.mode !== undefined && input.mode !== "off" && input.mode !== "eligible") throw new Error("stage reuse mode: off or eligible required");
|
|
45
|
+
if (input.forceFresh !== undefined && typeof input.forceFresh !== "boolean") throw new Error("stage reuse forceFresh: boolean required");
|
|
46
|
+
const result = (reason: StageReuseReason): StageReuseEligibility => ({ v: 1, kind: "declaration-only", eligible: reason === "declared-pure-artifact", reason });
|
|
47
|
+
if (input.forceFresh) return result("force-fresh");
|
|
48
|
+
if (input.mode !== "eligible") return result("mode-off");
|
|
49
|
+
if (input.phase !== "investigate") return result("phase-fresh");
|
|
50
|
+
if (input.stage.kind === "evaluator") return result("evaluator-fresh");
|
|
51
|
+
if (protocol.v !== 2) return result("legacy-fresh");
|
|
52
|
+
if (!selected?.reuse) return result("undeclared-contract");
|
|
53
|
+
if (!Object.keys(selected.outputs).length) return result("no-artifact-outputs");
|
|
54
|
+
return result("declared-pure-artifact");
|
|
55
|
+
}
|
|
56
|
+
/** Excludes candidate definitions: the selected stage and actual inputs bind local dataflow separately. */
|
|
57
|
+
function comparisonDomain(protocol: ProtocolV2) {
|
|
58
|
+
const { candidate: _candidate, budget: _budget, ...domain } = protocol;
|
|
59
|
+
return domain;
|
|
60
|
+
}
|
|
61
|
+
function inputIdentities(raw: unknown, stage: CandidateStage): Record<string, string> {
|
|
62
|
+
if (!plain(raw)) throw new Error("stage reuse input hashes: object required");
|
|
63
|
+
const names = Object.keys(stage.inputs);
|
|
64
|
+
if (Object.keys(raw).length !== names.length || names.some(name => !Object.hasOwn(raw, name)) || Object.keys(raw).some(name => !names.includes(name))) throw new Error("stage reuse input hashes: every declared input needs exactly one digest and no undeclared inputs");
|
|
65
|
+
return Object.fromEntries(names.map(name => [name, reuseDigest(raw[name], "stage reuse input digest")]));
|
|
66
|
+
}
|
|
67
|
+
/** A key is not a lookup, reuse receipt, independent observation or authorization to skip execution. */
|
|
68
|
+
export function stageReuseKey(input: StageReuseKeyInput): string {
|
|
69
|
+
if (!plain(input)) throw new Error("stage reuse key: object required");
|
|
70
|
+
onlyKeys(input, [...ELIGIBILITY_KEYS, "studyId", "populationSha256", "codeTree", "codeSnapshotSha256", "inputHashes", "seed", "runtime", "platform"], "stage reuse key");
|
|
71
|
+
const declaration = stageReuseEligibility({ protocol: input.protocol, stage: input.stage, phase: input.phase, mode: input.mode, forceFresh: input.forceFresh });
|
|
72
|
+
if (!declaration.eligible) throw new Error(`stage reuse key: ${declaration.reason}; a declared pure-artifact investigate candidate with eligible mode is required`);
|
|
73
|
+
const protocol = validateProtocolDefinition(input.protocol);
|
|
74
|
+
if (protocol.v !== 2) throw new Error("stage reuse key: protocol v2 required");
|
|
75
|
+
const stage = candidate(protocol, input.stage)!;
|
|
76
|
+
if (typeof input.studyId !== "string" || !/^[A-Za-z0-9_-]{1,80}$/.test(input.studyId)) throw new Error("stage reuse study: valid study identity required");
|
|
77
|
+
if (!Number.isSafeInteger(input.seed) || !protocol.seeds.includes(input.seed)) throw new Error("stage reuse seed: declared integer seed required");
|
|
78
|
+
if (!plain(input.runtime) || !plain(input.platform)) throw new Error("stage reuse runtime/platform: explicit version and ABI identities required");
|
|
79
|
+
onlyKeys(input.runtime, ["semantics", "producerVersion"], "stage reuse runtime");
|
|
80
|
+
onlyKeys(input.platform, ["os", "arch", "abi"], "stage reuse platform");
|
|
81
|
+
return sha256(canonical({ v: STAGE_REUSE_KEY_VERSION, studyId: input.studyId, populationSha256: reuseDigest(input.populationSha256, "stage reuse frozen selection population digest"), domain: comparisonDomain(protocol), stage,
|
|
82
|
+
codeTree: reuseDigest(input.codeTree, "stage reuse full code tree", 40), codeSnapshotSha256: reuseDigest(input.codeSnapshotSha256, "stage reuse frozen code digest"),
|
|
83
|
+
inputHashes: inputIdentities(input.inputHashes, stage), seed: input.seed,
|
|
84
|
+
runtime: { semantics: reuseIdentityText(input.runtime.semantics, "stage reuse runtime semantics"), producerVersion: reuseIdentityText(input.runtime.producerVersion, "stage reuse producer version") },
|
|
85
|
+
platform: { os: reuseIdentityText(input.platform.os, "stage reuse operating system"), arch: reuseIdentityText(input.platform.arch, "stage reuse architecture"), abi: reuseIdentityText(input.platform.abi, "stage reuse platform ABI") },
|
|
86
|
+
}));
|
|
87
|
+
}
|
package/src/exp/selection.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { boundedText, commit, onlyKeys, openStudy, plain, readTextBounded, requireExperiment, sha256, type Actor } from "../study.ts";
|
|
4
|
-
import type { Protocol } from "./protocol.ts";
|
|
4
|
+
import type { ProtocolDefinition as Protocol } from "./protocol.ts";
|
|
5
5
|
|
|
6
6
|
export interface Selection { v: 1; run: string; metric: string; baseline: { commit: string }; minSeeds: number; minDelta: number }
|
|
7
7
|
export const SELECTION_BYTES = 65_536;
|
package/src/exp/snapshot.ts
CHANGED
|
@@ -2,8 +2,9 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { lstatSync, mkdirSync, mkdtempSync, opendirSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { dirname, join, posix } from "node:path";
|
|
5
|
-
import { runOnExecutor, spawnRunner, validateExecutor, type Executor, type ProcessResult, type ProcessRunner } from "./executor.ts";
|
|
6
|
-
import {
|
|
5
|
+
import { PORTABLE_TAR_CREATE, runOnExecutor, shellQuote, spawnRunner, validateExecutor, type Executor, type ProcessResult, type ProcessRunner } from "./executor.ts";
|
|
6
|
+
import { TarMemberScan, type ArtifactFile } from "./artifacts.ts";
|
|
7
|
+
import { TASK_BYTES, TASK_DIRECTORIES, TASK_FILES } from "./protocol.ts";
|
|
7
8
|
import { readBytesBounded, sha256 } from "../study.ts";
|
|
8
9
|
|
|
9
10
|
export const SNAPSHOT_BYTES = 256 * 1024 * 1024;
|
|
@@ -67,7 +68,7 @@ export async function transferSnapshot(repoArg: string, commitArg: string, execu
|
|
|
67
68
|
}
|
|
68
69
|
|
|
69
70
|
/** Capture each file once; the hash binds the same bytes copied into private immutable evaluator staging. */
|
|
70
|
-
export async function transferTask(taskDir: string, executor: Executor, destination: string, runner: ProcessRunner = spawnRunner, expectedTreeHash?: string): Promise<{ sha256: string; bytes: number; treeHash: string }> {
|
|
71
|
+
export async function transferTask(taskDir: string, executor: Executor, destination: string, runner: ProcessRunner = spawnRunner, expectedTreeHash?: string, includeCandidate = false): Promise<{ sha256: string; bytes: number; treeHash: string }> {
|
|
71
72
|
repository(taskDir);
|
|
72
73
|
if (expectedTreeHash !== undefined && !/^[a-f0-9]{64}$/.test(expectedTreeHash)) throw new Error("task tree hash: invalid; use the approved taskTreeHash before transferring evaluator files");
|
|
73
74
|
const staging = mkdtempSync(join(tmpdir(), "ares-task-")), entries: [string, string][] = [];
|
|
@@ -80,7 +81,7 @@ export async function transferTask(taskDir: string, executor: Executor, destinat
|
|
|
80
81
|
const source = relative ? join(taskDir, relative) : taskDir, label = relative ? `task/${relative}` : "task/", stat = lstatSync(source);
|
|
81
82
|
if (stat.isSymbolicLink()) throw new Error(`${label}: symlink refused; replace it with regular task files before ares attempt run`);
|
|
82
83
|
if (stat.isDirectory()) {
|
|
83
|
-
if (++directories >
|
|
84
|
+
if (++directories > TASK_DIRECTORIES || depth > 64) throw new Error(`${label}: task traversal limit exceeded; reduce task/ to 1000 directories and 64 levels`);
|
|
84
85
|
if (relative.startsWith("evaluator/")) mkdirSync(join(staging, relative), { recursive: true, mode: 0o700 });
|
|
85
86
|
const directory = opendirSync(source);
|
|
86
87
|
try { for (let entry = directory.readSync(); entry; entry = directory.readSync()) capture(relative ? `${relative}/${entry.name}` : entry.name, depth + 1); }
|
|
@@ -92,7 +93,7 @@ export async function transferTask(taskDir: string, executor: Executor, destinat
|
|
|
92
93
|
try { content = readBytesBounded(source, TASK_BYTES - total); }
|
|
93
94
|
catch { throw new Error(`${label}: bounded read failed; restore a readable regular file within the 64 MiB task limit`); }
|
|
94
95
|
total += content.length; entries.push([relative, sha256(content)]);
|
|
95
|
-
if (relative.startsWith("evaluator/")) {
|
|
96
|
+
if (includeCandidate || relative.startsWith("evaluator/")) {
|
|
96
97
|
const target = join(staging, relative); mkdirSync(dirname(target), { recursive: true, mode: 0o700 });
|
|
97
98
|
writeFileSync(target, content, { mode: stat.mode & 0o777 });
|
|
98
99
|
}
|
|
@@ -101,29 +102,46 @@ export async function transferTask(taskDir: string, executor: Executor, destinat
|
|
|
101
102
|
capture("", 0);
|
|
102
103
|
const treeHash = sha256(JSON.stringify(entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
|
|
103
104
|
if (expectedTreeHash !== undefined && treeHash !== expectedTreeHash) throw new Error("task/: content changed since approval; set the protocol, approve design again, and retry ares attempt run");
|
|
104
|
-
// Bounded tar headers and long-path metadata supplement the 64 MiB task payload cap.
|
|
105
|
-
|
|
105
|
+
// Bounded tar headers and long-path metadata supplement the 64 MiB task payload cap. The archive is created with the
|
|
106
|
+
// shared content-only tar rule, and its members are checked against the staged files while it streams.
|
|
107
|
+
const staged = new Map((includeCandidate ? entries : entries.filter(([path]) => path.startsWith("evaluator/"))).map(([path, digest]) => [path, digest]));
|
|
108
|
+
const transferred = await transferArchive("task", { command: "sh", args: ["-c", `${PORTABLE_TAR_CREATE} -C ${shellQuote(staging)} -cf - ${includeCandidate ? "." : "evaluator"}`] }, TASK_BYTES + 16 * 1024 * 1024, executor, destination, runner, staged);
|
|
106
109
|
return { ...transferred, treeHash };
|
|
107
110
|
} catch (error) {
|
|
108
|
-
if (error instanceof Error && (error.message.startsWith("task/") || error.message.startsWith("executor "))) throw error;
|
|
111
|
+
if (error instanceof Error && (error.message.startsWith("task/") || error.message.startsWith("task archive:") || error.message.startsWith("executor "))) throw error;
|
|
109
112
|
throw new Error("task archive capture failed; restore readable task/evaluator files, then retry ares attempt run");
|
|
110
113
|
} finally { rmSync(staging, { recursive: true, force: true }); }
|
|
111
114
|
}
|
|
112
115
|
|
|
113
|
-
|
|
116
|
+
/** Checks a task archive's members against the staged files: refuses AppleDouble `._*` members and any other drift by name. */
|
|
117
|
+
function memberCheck(files: ArtifactFile[], staged: Map<string, string>): void {
|
|
118
|
+
const metadata = files.find(file => file.path.split("/").some(part => part.startsWith("._")) && !staged.has(file.path));
|
|
119
|
+
if (metadata) throw new Error(`task archive: AppleDouble/extended-attribute metadata member ${metadata.path.slice(0, 200)} refused; the archive must carry task content only (tar --no-xattrs with COPYFILE_DISABLE=1, GNU tar >= 1.27 or bsdtar), then retry ares attempt run`);
|
|
120
|
+
const extra = files.find(file => staged.get(file.path) !== file.sha256);
|
|
121
|
+
if (extra || files.length !== staged.size) throw new Error(`task archive: member ${(extra?.path ?? "set").slice(0, 200)} differs from the staged task files; check the controller tar (GNU tar >= 1.27 or bsdtar) and retry ares attempt run`);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function transferArchive(kind: "snapshot" | "task", source: { command: string; args: string[] }, limit: number, executorArg: Executor, destination: string, runner: ProcessRunner, staged?: Map<string, string>): Promise<{ sha256: string; bytes: number }> {
|
|
114
125
|
const executor = validateExecutor(executorArg);
|
|
115
126
|
if (!destination.startsWith("/") || destination.length > 4096 || /[\0\r\n,"]/.test(destination) || posix.normalize(destination) === "/") throw new Error("snapshot destination: invalid directory; use a private absolute non-root directory without NUL, newlines, commas or double quotes");
|
|
116
127
|
const stream = new ArchiveChannel(), controller = new AbortController(), hash = createHash("sha256");
|
|
117
|
-
|
|
128
|
+
const scan = staged ? new TarMemberScan(TASK_BYTES, TASK_FILES, TASK_FILES + TASK_DIRECTORIES) : undefined;
|
|
129
|
+
let bytes = 0, oversized = false, failedSide: "archive" | "extract" | undefined, refused: Error | undefined;
|
|
118
130
|
const archive = (async () => {
|
|
119
131
|
try {
|
|
120
132
|
const result = await runner({ ...source, signal: controller.signal, timeoutMs: 300_000,
|
|
121
133
|
stdoutSink: async chunk => {
|
|
122
134
|
if (bytes + chunk.byteLength > limit) { oversized = true; throw new Error("archive size limit"); }
|
|
123
135
|
bytes += chunk.byteLength; hash.update(chunk);
|
|
136
|
+
try { scan?.push(chunk); } catch { refused ??= new Error("task archive: malformed or unsupported tar stream refused; check the controller tar (GNU tar >= 1.27 or bsdtar) and retry ares attempt run"); throw refused; }
|
|
124
137
|
await stream.write(chunk);
|
|
125
138
|
} });
|
|
126
139
|
if (!passed(result)) throw gitFailure("archive");
|
|
140
|
+
if (scan && staged) {
|
|
141
|
+
let files: ArtifactFile[];
|
|
142
|
+
try { files = scan.finish(); } catch { refused ??= new Error("task archive: truncated tar stream refused; retry ares attempt run"); throw refused; }
|
|
143
|
+
try { memberCheck(files, staged); } catch (error) { refused ??= error as Error; throw refused; }
|
|
144
|
+
}
|
|
127
145
|
stream.end();
|
|
128
146
|
} catch (error) { failedSide ??= "archive"; stream.end(error as Error); throw error; }
|
|
129
147
|
})();
|
|
@@ -141,6 +159,8 @@ async function transferArchive(kind: "snapshot" | "task", source: { command: str
|
|
|
141
159
|
controller.abort(); stream.end(new Error("archive transfer cancelled"));
|
|
142
160
|
await Promise.allSettled([archive, extract]);
|
|
143
161
|
if (oversized) throw new Error(`${kind} archive: larger than ${limit} bytes; reduce the ${kind === "snapshot" ? "committed snapshot" : "task evaluator"} before ares attempt run`);
|
|
162
|
+
// A refused member is named even though extraction may have begun; the attempt fails and nothing is marked verified.
|
|
163
|
+
if (refused) throw refused;
|
|
144
164
|
if (failedSide === "archive") throw kind === "snapshot" ? gitFailure("archive") : new Error("task archive failed; restore readable task/evaluator files, then retry ares attempt run");
|
|
145
165
|
throw new Error(`executor ${executor.kind === "ssh" ? executor.host : "local"}: snapshot extraction failed; check the private destination directory and tar on the executor host, then retry ares attempt run`);
|
|
146
166
|
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { validateReuseContract, type StageReuseContract } from "./reuse-contract.ts";
|
|
2
|
+
import { plain, sha256 } from "../study.ts";
|
|
3
|
+
import { PROTOCOL_BYTES, canonical, validateProtocol, type Protocol } from "./protocol.ts";
|
|
4
|
+
|
|
5
|
+
/** T1 definition only. The v1 executor must never interpret this as a single candidate. */
|
|
6
|
+
export type StageInput = { task: string } | { stage: string; output: string };
|
|
7
|
+
export interface CandidateStage {
|
|
8
|
+
name: string;
|
|
9
|
+
image: string;
|
|
10
|
+
command: string[];
|
|
11
|
+
env?: Record<string, string>;
|
|
12
|
+
seed: boolean;
|
|
13
|
+
code: "snapshot";
|
|
14
|
+
needs: string[];
|
|
15
|
+
inputs: Record<string, StageInput>;
|
|
16
|
+
outputs: Record<string, string>;
|
|
17
|
+
reuse?: StageReuseContract;
|
|
18
|
+
}
|
|
19
|
+
export interface ProtocolV2 extends Omit<Protocol, "v" | "candidate" | "inputs"> {
|
|
20
|
+
v: 2;
|
|
21
|
+
candidate: { stages: CandidateStage[] };
|
|
22
|
+
}
|
|
23
|
+
export const STAGE_LIMIT = 16, STAGE_PORT_LIMIT = 32;
|
|
24
|
+
// Structural validation must not count the evaluator twice or combine it with every stage.
|
|
25
|
+
const PLACEHOLDER_EXECUTION = { image: `ares-validation@sha256:${"0".repeat(64)}`, command: ["validate"] };
|
|
26
|
+
|
|
27
|
+
function object(raw: unknown, keys: readonly string[], label: string): Record<string, unknown> {
|
|
28
|
+
if (!plain(raw) || Object.keys(raw).some(key => !keys.includes(key))) throw new Error(`${label}: object with declared fields required; remove unknown fields`);
|
|
29
|
+
return raw;
|
|
30
|
+
}
|
|
31
|
+
function name(raw: unknown, label: string): string {
|
|
32
|
+
if (typeof raw !== "string" || !/^[a-z][a-z0-9_-]{0,31}$/.test(raw) || ["constructor", "prototype", "__proto__", "evaluator"].includes(raw)) throw new Error(`${label}: use a nonreserved lowercase name of 1..32 letters, digits, underscores or hyphens starting with a letter`);
|
|
33
|
+
return raw;
|
|
34
|
+
}
|
|
35
|
+
function relativePath(raw: unknown, label: string): string {
|
|
36
|
+
if (typeof raw !== "string" || raw.length > 256 || !/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(raw) || raw.split("/").some(part => part === "." || part === "..")) throw new Error(`${label}: normalized relative path required; remove absolute paths, dot segments and unsafe characters`);
|
|
37
|
+
return raw;
|
|
38
|
+
}
|
|
39
|
+
function ports(raw: unknown, label: string): [string, unknown][] {
|
|
40
|
+
if (!plain(raw) || Object.keys(raw).length > STAGE_PORT_LIMIT) throw new Error(`${label}: object with at most ${STAGE_PORT_LIMIT} named ports required`);
|
|
41
|
+
return Object.entries(raw).map(([key, value]) => [name(key, `${label}.${key}`), value]);
|
|
42
|
+
}
|
|
43
|
+
function outputs(raw: unknown, label: string): Record<string, string> {
|
|
44
|
+
const entries: [string, string][] = [];
|
|
45
|
+
for (const [key, value] of ports(raw, label)) {
|
|
46
|
+
const path = relativePath(value, `${label}.${key}`);
|
|
47
|
+
if (entries.some(([, other]) => path === other || path.startsWith(`${other}/`) || other.startsWith(`${path}/`))) throw new Error(`${label}.${key}: overlapping output paths; declare disjoint files or directories`);
|
|
48
|
+
entries.push([key, path]);
|
|
49
|
+
}
|
|
50
|
+
return Object.fromEntries(entries);
|
|
51
|
+
}
|
|
52
|
+
function inputs(raw: unknown, prior: ReadonlyMap<string, CandidateStage>, label: string): Record<string, StageInput> {
|
|
53
|
+
return Object.fromEntries(ports(raw, label).map(([key, value]): [string, StageInput] => {
|
|
54
|
+
if (plain(value) && Object.hasOwn(value, "task")) {
|
|
55
|
+
const input = object(value, ["task"], `${label}.${key}`), path = relativePath(input.task, `${label}.${key}.task`);
|
|
56
|
+
if (path === "evaluator" || path.startsWith("evaluator/")) throw new Error(`${label}.${key}: evaluator inputs are private; choose a candidate task snapshot path`);
|
|
57
|
+
return [key, { task: path }];
|
|
58
|
+
}
|
|
59
|
+
const input = object(value, ["stage", "output"], `${label}.${key}`), producer = name(input.stage, `${label}.${key}.stage`), output = name(input.output, `${label}.${key}.output`);
|
|
60
|
+
const parent = prior.get(producer);
|
|
61
|
+
if (!parent || !Object.hasOwn(parent.outputs, output)) throw new Error(`${label}.${key}: undeclared or forward stage output; refer only to a named output of an earlier stage`);
|
|
62
|
+
return [key, { stage: producer, output }];
|
|
63
|
+
}));
|
|
64
|
+
}
|
|
65
|
+
function reuseContract(raw: unknown, label: string): StageReuseContract {
|
|
66
|
+
try { return validateReuseContract(raw); }
|
|
67
|
+
catch (error) { throw new Error(`${label}.reuse: ${error instanceof Error ? error.message : "invalid pure-artifact contract"}`); }
|
|
68
|
+
}
|
|
69
|
+
function candidateStages(raw: unknown, common: Protocol): CandidateStage[] {
|
|
70
|
+
const candidate = object(raw, ["stages"], "candidate");
|
|
71
|
+
if (!Array.isArray(candidate.stages) || !candidate.stages.length || candidate.stages.length > STAGE_LIMIT) throw new Error(`candidate.stages: declare 1..${STAGE_LIMIT} stages in execution order`);
|
|
72
|
+
const prior = new Map<string, CandidateStage>();
|
|
73
|
+
for (const [index, rawStage] of candidate.stages.entries()) {
|
|
74
|
+
const indexLabel = `candidate.stages[${index}]`;
|
|
75
|
+
const s = object(rawStage, ["name", "image", "command", "env", "seed", "code", "needs", "inputs", "outputs", "reuse"], indexLabel), stageName = name(s.name, `${indexLabel}.name`);
|
|
76
|
+
const label = `${indexLabel}(${stageName})`;
|
|
77
|
+
if (prior.has(stageName)) throw new Error(`${label}.name: duplicate; give each stage a unique name`);
|
|
78
|
+
if (typeof s.seed !== "boolean" || s.code !== "snapshot") throw new Error(`${label}: declare boolean seed use and code: "snapshot"; mutable code inputs are unsupported`);
|
|
79
|
+
if (!Array.isArray(s.needs) || s.needs.length > STAGE_LIMIT) throw new Error(`${label}.needs: declare an array of earlier stage names (empty allowed)`);
|
|
80
|
+
const needs = s.needs.map((value, i) => name(value, `${label}.needs[${i}]`));
|
|
81
|
+
if (new Set(needs).size !== needs.length || needs.some(value => !prior.has(value))) throw new Error(`${label}.needs: duplicate, cyclic or forward ordering edge; refer only to unique earlier stages`);
|
|
82
|
+
// Share v1 image/argv/env validation without charging the real evaluator again.
|
|
83
|
+
let execution: Protocol["candidate"];
|
|
84
|
+
try {
|
|
85
|
+
execution = validateProtocol({ ...common, evaluator: PLACEHOLDER_EXECUTION, candidate: { image: s.image, command: s.command, ...(s.env === undefined ? {} : { env: s.env }) } }).candidate;
|
|
86
|
+
} catch (error) {
|
|
87
|
+
const message = error instanceof Error ? error.message.replaceAll("candidate", label) : "invalid execution definition";
|
|
88
|
+
throw new Error(message.includes(label) ? message : `${label}: ${message}`);
|
|
89
|
+
}
|
|
90
|
+
prior.set(stageName, { name: stageName, ...execution, seed: s.seed, code: "snapshot", needs,
|
|
91
|
+
inputs: inputs(s.inputs, prior, `${label}.inputs`), outputs: outputs(s.outputs, `${label}.outputs`),
|
|
92
|
+
...(s.reuse === undefined ? {} : { reuse: reuseContract(s.reuse, label) }) });
|
|
93
|
+
}
|
|
94
|
+
return [...prior.values()];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Pure preflight: no study writes, process calls, mounts or artifact availability claims. */
|
|
98
|
+
export function validateStageProtocol(raw: unknown): ProtocolV2 {
|
|
99
|
+
const p = object(raw, ["v", "method", "candidate", "evaluator", "metrics", "seeds", "limits", "network", "budget"], "protocol");
|
|
100
|
+
if (p.v !== 2) throw new Error("protocol.v: unsupported stage version; use a compatible ares release, keeping the original definition unchanged");
|
|
101
|
+
// Validate common fields with the authoritative v1 validator; no common bound is multiplied.
|
|
102
|
+
const common = validateProtocol({ ...p, v: 1, candidate: PLACEHOLDER_EXECUTION });
|
|
103
|
+
const { v: _v, candidate: _candidate, inputs: _inputs, ...base } = common;
|
|
104
|
+
const result: ProtocolV2 = { ...base, v: 2, candidate: { stages: candidateStages(p.candidate, common) } };
|
|
105
|
+
if (Buffer.byteLength(JSON.stringify(result, null, 2) + "\n") > PROTOCOL_BYTES) throw new Error(`protocol: too large; reduce the formatted protocol to at most ${PROTOCOL_BYTES} bytes`);
|
|
106
|
+
return result;
|
|
107
|
+
}
|
|
108
|
+
/** Every stage, declared order, ordering/data edge and execution field participates. Budget stays seal-only. */
|
|
109
|
+
export function stageProtocolHash(protocol: ProtocolV2): string {
|
|
110
|
+
const { budget: _budget, ...identity } = validateStageProtocol(protocol);
|
|
111
|
+
return sha256(canonical(identity));
|
|
112
|
+
}
|
|
113
|
+
/** Pure protocol/task component of a future design seal; not an approval or full study binding. */
|
|
114
|
+
export function stageDesignBinding(protocol: ProtocolV2, treeHash: string): string {
|
|
115
|
+
if (!/^[a-f0-9]{64}$/.test(treeHash)) throw new Error("task tree: expected a SHA-256 identity from bounded task snapshot validation");
|
|
116
|
+
return sha256(canonical({ protocol: validateStageProtocol(protocol), treeHash }));
|
|
117
|
+
}
|