@staix/agent-research 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +255 -24
  3. package/package.json +2 -2
  4. package/src/cli.ts +117 -10
  5. package/src/commands-table.ts +39 -8
  6. package/src/commands.ts +192 -32
  7. package/src/exp/attempts.ts +500 -65
  8. package/src/exp/executor.ts +235 -12
  9. package/src/exp/final.ts +1 -1
  10. package/src/exp/logs.ts +25 -12
  11. package/src/exp/metrics.ts +6 -5
  12. package/src/exp/pipeline.ts +92 -0
  13. package/src/exp/protocol.ts +85 -18
  14. package/src/exp/retention-script.ts +649 -0
  15. package/src/exp/retention.ts +70 -0
  16. package/src/exp/reuse-admission.ts +63 -0
  17. package/src/exp/reuse-contract.ts +48 -0
  18. package/src/exp/reuse-runtime.ts +87 -0
  19. package/src/exp/reuse.ts +87 -0
  20. package/src/exp/selection.ts +1 -1
  21. package/src/exp/snapshot.ts +3 -3
  22. package/src/exp/stages.ts +117 -0
  23. package/src/harness/experience-source.ts +34 -0
  24. package/src/harness/experience.ts +206 -0
  25. package/src/harness/hub-guidance.ts +140 -0
  26. package/src/harness/hub-reference.ts +18 -0
  27. package/src/harness/lesson-candidates.ts +162 -0
  28. package/src/harness/limits.ts +2 -0
  29. package/src/harness/privacy.ts +4 -0
  30. package/src/harness/receipts.ts +84 -0
  31. package/src/harness/rounds.ts +198 -0
  32. package/src/harness/transitions.ts +152 -0
  33. package/src/lit/candidates.ts +13 -5
  34. package/src/lit/cards.ts +55 -4
  35. package/src/lit/flow.ts +82 -0
  36. package/src/lit/queries.ts +62 -0
  37. package/src/manifest.ts +13 -6
  38. package/src/mcp-tools.ts +123 -25
  39. package/src/mcp.ts +4 -0
  40. package/src/memory/amem-show.ts +135 -0
  41. package/src/memory/amem.ts +3 -0
  42. package/src/memory/archive.ts +17 -8
  43. package/src/memory/evidence-local.ts +77 -0
  44. package/src/memory/evidence.ts +39 -0
  45. package/src/memory/lessons.ts +4 -2
  46. package/src/memory/skill-check.ts +56 -0
  47. package/src/memory/skill-format.ts +77 -0
  48. package/src/memory/skills.ts +72 -26
  49. package/src/memory/source-budget.ts +11 -0
  50. package/src/memory/vault-cards.ts +226 -0
  51. package/src/paper/build.ts +16 -7
  52. package/src/paper/check.ts +37 -10
  53. package/src/paper/headings.ts +39 -0
  54. package/src/paper/hygiene.ts +153 -0
  55. package/src/paper/placeholders.ts +16 -1
  56. package/src/paper/plan.ts +170 -0
  57. package/src/paper/point-evidence.ts +63 -0
  58. package/src/paper/points.ts +83 -0
  59. package/src/paper/review.ts +102 -9
  60. package/src/paper/scopes.ts +51 -0
  61. package/src/plan/definition.ts +5 -1
  62. package/src/plan/hub.ts +6 -0
  63. package/src/plan/state.ts +5 -0
  64. package/src/playbook.ts +35 -20
  65. package/src/privacy.ts +9 -0
  66. package/src/provenance.ts +679 -0
  67. package/src/scope.ts +24 -3
  68. package/src/study-export.ts +55 -27
  69. package/src/study.ts +54 -14
  70. package/src/ui/panel.css +4 -0
  71. package/src/ui/panel.js +263 -6
  72. 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,63 @@
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
+ if (original.status === "running" || 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);
48
+ const completed = original.pipeline.completed.find(parent => parent.name === stage.name && canonical(parent.ref) === canonical(result.ref) && !parent.reuse);
49
+ record = completed?.record;
50
+ if (!record && original.stage === "candidate" && original.pipeline.definition.candidate.stages[original.pipeline.index]?.name === stage.name) record = original.stages.candidate;
51
+ const sourceDefinition = original.pipeline.definition.candidate.stages.find(value => value.name === stage.name);
52
+ 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);
53
+ const outputRoot = posix.join(original.executor.workdir, original.studyId, original.id, "stages", stage.name, "output");
54
+ 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);
55
+ } catch { return fresh("source-unavailable", key); }
56
+ const duration = Date.parse(record.endedAt ?? "") - Date.parse(record.startedAt);
57
+ const wallSeconds = Number.isFinite(duration) && duration >= 0 ? duration / 1000 : "unknown";
58
+ const gpuHours = wallSeconds !== "unknown" && Number.isFinite(record.limits.gpus) ? wallSeconds * record.limits.gpus / 3600 : "unknown";
59
+ const verificationMs = performance.now() - started;
60
+ const receipt: StageReuseReceipt = { v: 1, key, context: facts, source: result.ref, original: { wallSeconds, gpuHours, cpuSeconds: "unknown" }, verificationMs, materializationMs: 0 };
61
+ return { outcome: "reused", reason: "verified-hit", key, context: facts, verificationMs, materializationMs: 0, source: result.ref, record, receipt,
62
+ 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) })) };
63
+ }
@@ -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,87 @@
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
+ /** Read-only, source-owned facts. Caller still owns current design/policy/budget fencing at admission. */
54
+ export async function reuseSourceFacts(dir: string, attempt: Attempt, ctx: AttemptContext): Promise<StageReuseSourceFactsResult> {
55
+ const protocol = attempt.pipeline?.definition ?? attempt.protocol;
56
+ let before: ReturnType<typeof population>;
57
+ try {
58
+ const { study } = openStudy(dir);
59
+ if (study.mode !== "experiment" || study.id !== attempt.studyId) return { reason: "unsupported-study" };
60
+ before = population(dir, protocol);
61
+ } catch { return { reason: "population-unavailable" }; }
62
+ if (attempt.stage !== "candidate" || !before.selection || before.selection.run !== attempt.run || ["ablate", "final", "posthoc"].includes(attempt.run)) return { reason: "outside-investigation" };
63
+ if (protocol.limits.gpus > 0) return { reason: "unsupported-gpu-abi" };
64
+ if (!identity(process.versions.bun)) return { reason: "producer-runtime-unavailable" };
65
+ let semantics: string | undefined;
66
+ try { semantics = producerSemantics(); } catch { return { reason: "producer-source-unavailable" }; }
67
+ if (!semantics) return { reason: "producer-runtime-unavailable" };
68
+ let response;
69
+ try {
70
+ response = await runOnExecutor(attempt.executor, "python3", ["-I", "-S", "-c", PLATFORM_SCRIPT], ctx.runner ?? spawnRunner, { timeoutMs: REUSE_FACTS_TIMEOUT_MS, maxOutputBytes: REUSE_FACTS_OUTPUT_BYTES });
71
+ } catch { return { reason: "platform-unavailable" }; }
72
+ if (response.exitCode !== 0 || response.timedOut || response.truncated) return { reason: "platform-unavailable" };
73
+ let value: unknown;
74
+ try { value = JSON.parse(response.stdout); } catch { return { reason: "unsupported-platform" }; }
75
+ 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" };
76
+ if (value.os === "linux" && (!identity(value.libc.name) || !identity(value.libc.version))) return { reason: "unsupported-platform" };
77
+ if (value.os === "darwin" && !identity(value.macVersion)) return { reason: "unsupported-platform" };
78
+ 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" };
79
+ try {
80
+ const current = openStudy(dir).study;
81
+ if (current.mode !== "experiment" || current.id !== attempt.studyId) return { reason: "population-changed" };
82
+ const after = population(dir, protocol);
83
+ if (after.sha256 !== before.sha256 || after.selection?.run !== attempt.run) return { reason: "population-changed" };
84
+ } catch { return { reason: "population-changed" }; }
85
+ return { populationSha256: before.sha256, runtime: { semantics, producerVersion: version }, platform: { os: value.os, arch: value.arch,
86
+ abi: `cpu-v1:${sha256(canonical({ observed: value, executor: attempt.executor }))}` } };
87
+ }
@@ -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
+ }
@@ -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;
@@ -67,7 +67,7 @@ export async function transferSnapshot(repoArg: string, commitArg: string, execu
67
67
  }
68
68
 
69
69
  /** 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 }> {
70
+ 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
71
  repository(taskDir);
72
72
  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
73
  const staging = mkdtempSync(join(tmpdir(), "ares-task-")), entries: [string, string][] = [];
@@ -92,7 +92,7 @@ export async function transferTask(taskDir: string, executor: Executor, destinat
92
92
  try { content = readBytesBounded(source, TASK_BYTES - total); }
93
93
  catch { throw new Error(`${label}: bounded read failed; restore a readable regular file within the 64 MiB task limit`); }
94
94
  total += content.length; entries.push([relative, sha256(content)]);
95
- if (relative.startsWith("evaluator/")) {
95
+ if (includeCandidate || relative.startsWith("evaluator/")) {
96
96
  const target = join(staging, relative); mkdirSync(dirname(target), { recursive: true, mode: 0o700 });
97
97
  writeFileSync(target, content, { mode: stat.mode & 0o777 });
98
98
  }
@@ -102,7 +102,7 @@ export async function transferTask(taskDir: string, executor: Executor, destinat
102
102
  const treeHash = sha256(JSON.stringify(entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
103
103
  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
104
  // Bounded tar headers and long-path metadata supplement the 64 MiB task payload cap.
105
- const transferred = await transferArchive("task", { command: "tar", args: ["-C", staging, "-cf", "-", "evaluator"] }, TASK_BYTES + 16 * 1024 * 1024, executor, destination, runner);
105
+ const transferred = await transferArchive("task", { command: "tar", args: ["-C", staging, "-cf", "-", includeCandidate ? "." : "evaluator"] }, TASK_BYTES + 16 * 1024 * 1024, executor, destination, runner);
106
106
  return { ...transferred, treeHash };
107
107
  } catch (error) {
108
108
  if (error instanceof Error && (error.message.startsWith("task/") || error.message.startsWith("executor "))) throw error;
@@ -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
+ }
@@ -0,0 +1,34 @@
1
+ import {plain} from "../study.ts";
2
+ import {readScreenedAmem, supportsScreenedAmem, type ScreenedAmemInspection} from "../memory/amem-show.ts";
3
+ import type {ProcessRunner} from "../exp/executor.ts";
4
+
5
+ export interface ExperienceSourcePin {id: string; digest: string; sourceVersion: string}
6
+ export interface ExperienceSourceObservation {
7
+ id: string; state: ScreenedAmemInspection["state"]; digest: string | null; sourceVersion?: string; observedAt: string;
8
+ }
9
+ export const EXPERIENCE_SOURCE_LIMIT = 16;
10
+ function fail(): never {
11
+ throw new Error("experience source pins: malformed, duplicate or over-bound snapshot; restore the original snapshot or freeze an explicitly reviewed new round before retrying");
12
+ }
13
+ /** Liveness/version recheck only, never proof of temporal eligibility, applicability or claim support. */
14
+ export async function recheckExperienceSources(dir: string, entries: readonly ExperienceSourcePin[], options: {runner?: ProcessRunner; env?: NodeJS.ProcessEnv; now?: () => number} = {}): Promise<{state: "available" | "unavailable"; observations: ExperienceSourceObservation[]}> {
15
+ if (!Array.isArray(entries) || entries.length > EXPERIENCE_SOURCE_LIMIT) fail();
16
+ const pins = entries.map(entry => {
17
+ if (!plain(entry) || Object.keys(entry).some(key => !["id", "digest", "sourceVersion"].includes(key)) || typeof entry.id !== "string" || entry.id.length !== 32 || !/^[a-f0-9]{32}$/.test(entry.id) || typeof entry.digest !== "string" || entry.digest.length !== 64 || !/^[a-f0-9]{64}$/.test(entry.digest) || typeof entry.sourceVersion !== "string" || entry.sourceVersion.length > 128 || !supportsScreenedAmem(entry.sourceVersion)) fail();
18
+ return {id: entry.id, digest: entry.digest, sourceVersion: entry.sourceVersion};
19
+ });
20
+ if (new Set(pins.map(pin => pin.id)).size !== pins.length) fail();
21
+ const observations: ExperienceSourceObservation[] = [];
22
+ // Sequential and bounded: <=16 owning reads, each with its existing total 25-second lifetime. No retry or fallback.
23
+ for (const pin of pins) {
24
+ let inspected: ScreenedAmemInspection;
25
+ try {inspected = await readScreenedAmem(dir, pin.id, options);}
26
+ catch {
27
+ let time = Date.now(); try {const value = options.now?.(); if (value !== undefined && Number.isFinite(value) && Math.abs(value) <= 8.64e15) time = value;} catch { /* a failed clock cannot bypass the refusal */ }
28
+ inspected = {state: "unavailable", digest: null, observedAt: new Date(time).toISOString()};
29
+ }
30
+ const state = inspected.state === "available" && (inspected.digest !== pin.digest || inspected.sourceVersion !== pin.sourceVersion) ? "changed" : inspected.state;
31
+ observations.push({id: pin.id, state, digest: inspected.digest, ...(inspected.sourceVersion === undefined ? {} : {sourceVersion: inspected.sourceVersion}), observedAt: inspected.observedAt});
32
+ }
33
+ return {state: observations.every(observation => observation.state === "available") ? "available" : "unavailable", observations};
34
+ }