@staix/agent-research 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/README.md +93 -22
  3. package/package.json +4 -1
  4. package/src/cli-output.ts +446 -0
  5. package/src/cli.ts +208 -66
  6. package/src/commands-table.ts +213 -93
  7. package/src/commands.ts +86 -17
  8. package/src/exp/artifacts.ts +20 -2
  9. package/src/exp/attempts.ts +26 -9
  10. package/src/exp/calibrate.ts +125 -0
  11. package/src/exp/executor.ts +130 -21
  12. package/src/exp/final.ts +12 -3
  13. package/src/exp/idea-report.ts +97 -0
  14. package/src/exp/ideas.ts +90 -6
  15. package/src/exp/investigate.ts +25 -22
  16. package/src/exp/metrics.ts +3 -5
  17. package/src/exp/protocol.ts +28 -3
  18. package/src/exp/reuse-admission.ts +3 -1
  19. package/src/exp/reuse-runtime.ts +5 -1
  20. package/src/exp/screen.ts +83 -0
  21. package/src/exp/selection.ts +110 -4
  22. package/src/exp/snapshot.ts +28 -8
  23. package/src/exp/stages.ts +3 -1
  24. package/src/harness/transitions.ts +37 -5
  25. package/src/manifest.ts +13 -5
  26. package/src/mcp-tools.ts +67 -14
  27. package/src/memory/archive.ts +8 -3
  28. package/src/paper/build.ts +39 -25
  29. package/src/paper/check.ts +46 -15
  30. package/src/paper/dependencies.ts +47 -0
  31. package/src/paper/document.ts +19 -0
  32. package/src/paper/figures.ts +152 -0
  33. package/src/paper/hygiene.ts +16 -5
  34. package/src/paper/plan.ts +71 -29
  35. package/src/paper/point-evidence.ts +27 -12
  36. package/src/paper/render.ts +113 -0
  37. package/src/paper/renderer.ts +128 -0
  38. package/src/paper/review.ts +41 -5
  39. package/src/plan/definition.ts +6 -1
  40. package/src/playbook.ts +21 -11
  41. package/src/provenance.ts +4 -3
  42. package/src/study-export.ts +7 -4
  43. package/src/study.ts +9 -4
  44. package/src/ui/plugin.ts +3 -1
package/src/commands.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { PaperDocument } from "./paper/document.ts";
2
+ import { colorFor, fillMessage, outputAscii, renderError, streamWidth } from "./cli-output.ts";
1
3
  import {proposeLesson, decideLesson, checkLesson, listLessonCandidates} from "./harness/lesson-candidates.ts";
2
4
  import type {SkillCheckOptions} from "./memory/skill-check.ts";
3
5
  import {setHarnessStream, readHarnessStream, selectExperience, freezeExperience, checkExperience} from "./harness/experience.ts";
@@ -15,13 +17,18 @@ import { createAmemClient } from "./memory/amem.ts";
15
17
  import { previewArchive, exportArchive, type ArchivePreview, type ArchiveResult } from "./memory/archive.ts";
16
18
  import { addReview, resolveReview, reviewChecklist, reviewReadiness, reviewBinding, requireReviewReady } from "./paper/review.ts";
17
19
  import { buildPaper } from "./paper/build.ts";
20
+ import { recordPaperRender, showPaperRender } from "./paper/render.ts";
21
+ import { checkRenderer, runRenderStep, setRenderer, showRenderer } from "./paper/renderer.ts";
18
22
  import { checkPaper } from "./paper/check.ts";
19
23
  import { setPaperPlan, showPaperPlan } from "./paper/plan.ts";
20
24
  import { addAblation, showAblate, closeAblate } from "./exp/ablate.ts";
21
25
  import { setFinalSeeds, finalGateBinding, requireFinalInputs, closeFinal, showPosthoc } from "./exp/final.ts";
22
- import { addIdea, decideIdea } from "./exp/ideas.ts";
26
+ import { addIdea, decideIdea, setCategories } from "./exp/ideas.ts";
27
+ import { ideaReport as foldIdeaReport } from "./exp/idea-report.ts";
23
28
  import { showInvestigation, closeInvestigation } from "./exp/investigate.ts";
24
- import { setSelection } from "./exp/selection.ts";
29
+ import { isInvestigationRun } from "./exp/reuse-runtime.ts";
30
+ import { calibrateSelection, type CalibrationOptions } from "./exp/calibrate.ts";
31
+ import { readSelection, setSelection } from "./exp/selection.ts";
25
32
  import { createHubClient } from "./plan/hub.ts";
26
33
  import { runPlan, type ControllerRuntime, type Observation, type StepNode } from "./plan/controller.ts";
27
34
  import { resolveSnapshot } from "./exp/snapshot.ts";
@@ -34,19 +41,19 @@ import { existsSync, readdirSync, utimesSync } from "node:fs";
34
41
  import { join, resolve } from "node:path";
35
42
  import type { Http } from "./http.ts";
36
43
  import { readScope, scopeHash, setScope } from "./scope.ts";
37
- import { boundedText, commit, decideGate, gateState, GATES, initStudy, openStudy, readBytesBounded, readLedger, readTextBounded, requireGate, isHarnessGate, sha256, withLock, readPlanOwner, type Actor, type Binder, type GateName, type Study, STUDY_BYTES } from "./study.ts";
44
+ import { boundedText, commit, decideGate, gateState, GATES, initStudy, openStudy, readBytesBounded, readLedger, readTextBounded, requireGate, isHarnessGate, sha256, withLock, readPlanOwner, StudyLockBusyError, type Actor, type Binder, type GateName, type Study, STUDY_BYTES } from "./study.ts";
38
45
  import { candidatesFile, includedHash, isVerified, loadCandidates, mergeCandidates, sameWork, verifySubject, type Candidate } from "./lit/candidates.ts";
39
46
  import { litQueries, nextSearchId, validateIntent } from "./lit/queries.ts";
40
47
  import { flowMarkdown, litFlow } from "./lit/flow.ts";
41
48
  import { searchSource, SOURCES, type SourceName } from "./lit/sources.ts";
42
49
  import { verifyCandidates } from "./lit/verify.ts";
43
50
  import { assignCitekeys, renderBib } from "./lit/bibtex.ts";
44
- import { checkCitations } from "./lit/cite.ts";
51
+ import { checkCitations, citationOccurrences } from "./lit/cite.ts";
45
52
  import { cardPath, validateCard } from "./lit/cards.ts";
46
53
  import { createVaultClient, exportCards, importCards, listCards, previewCardExport } from "./memory/vault-cards.ts";
47
- import { designBinding, protocolHash, readDesign, setProtocol } from "./exp/protocol.ts";
54
+ import { designBinding, protocolHash, readDesign, readProtocol, setProtocol } from "./exp/protocol.ts";
48
55
  import { requireExperiment } from "./study.ts";
49
- import { checkExecutor, setExecutor, readExecutor, hashExecutorInput, type InputManifest } from "./exp/executor.ts";
56
+ import { checkExecutor, checkExecutorReport, setExecutor, readExecutor, hashExecutorInput, type InputManifest } from "./exp/executor.ts";
50
57
  import { cancelAttempt, listAttempts, listAttemptSummaries, reconcileAttempts, runAttempt, showAttempt, type AttemptContext, type AttemptListOptions, type AttemptOptions } from "./exp/attempts.ts";
51
58
  import { readAttemptLogs, type LogOptions } from "./exp/logs.ts";
52
59
  import { retainedOperation, type RetainedRef, type RetentionResult } from "./exp/retention.ts";
@@ -120,6 +127,7 @@ export async function executorInputsHash(dirArg: string, path: string, ctx: Ctx)
120
127
  if (!executor) throw new Error("executor: not configured; run ares executor set <dir> --kind local|ssh [--host ALIAS] --workdir PATH");
121
128
  return hashExecutorInput(executor, path, ctx.runner);
122
129
  }
130
+ export const executorCheckReport = (dir: string, ctx: Ctx) => checkExecutorReport(dir, ctx.runner);
123
131
  export const executorCheck = (dir: string, ctx: Ctx) => checkExecutor(dir, ctx.runner);
124
132
 
125
133
  function retentionRefs(raw: unknown): RetainedRef[] {
@@ -194,8 +202,14 @@ export const harnessImport = (dir: string, round: string, raw: unknown, ctx: Ctx
194
202
  export async function attemptRun(dir: string, options: AttemptOptions, ctx: Ctx) {
195
203
  if (options.reuse !== undefined && options.reuse !== "off" && options.reuse !== "eligible") throw new Error("attempt reuse: off or eligible required; select --reuse off|eligible (MCP reuse) and retry");
196
204
  if (options.forceFresh !== undefined && typeof options.forceFresh !== "boolean") throw new Error("attempt forceFresh: boolean required; set forceFresh to true/false or use --force-fresh, then retry");
197
- try { return await runAttempt(dir, options, ctx); }
198
- catch (error) { if (error instanceof GpuAdmissionDeferred) return error.result; throw error; }
205
+ const protocol = options.reuse === "eligible" ? readProtocol(dir) : undefined;
206
+ const selection = protocol ? readSelection(dir, protocol) : undefined;
207
+ const warnings = options.reuse === "eligible" && !isInvestigationRun(options.run ?? "main", selection)
208
+ ? [{ code: "outside-investigation", cause: "not an investigation run", nextStep: "declare the selection run, or drop --reuse" }] : undefined;
209
+ let result;
210
+ try { result = await runAttempt(dir, options, ctx); }
211
+ catch (error) { if (error instanceof GpuAdmissionDeferred) result = error.result; else throw error; }
212
+ return warnings ? { ...result, warnings } : result;
199
213
  }
200
214
  export const attemptList = (dir: string, options: AttemptListOptions = {}) => listAttemptSummaries(dir, options);
201
215
  export const attemptShow = (dir: string, id: string) => {
@@ -395,9 +409,29 @@ export async function bib(dirArg: string, ctx: Ctx) {
395
409
  });
396
410
  }
397
411
 
398
- export function cite(dirArg: string, draft: string) {
412
+ function inspectCitations(dirArg: string, draft: string) {
399
413
  const { dir } = openStudy(dirArg), path = resolve(draft);
400
- return { draft: path, ...checkCitations(readTextBounded(path, DRAFT_BYTES), loadCandidates(dir)) };
414
+ const source = readTextBounded(path, DRAFT_BYTES);
415
+ return { source, result: { draft: path, ...checkCitations(source, loadCandidates(dir)) } };
416
+ }
417
+ export function cite(dirArg: string, draft: string) { return inspectCitations(dirArg, draft).result; }
418
+ export function citeHuman(dirArg: string, draft: string) {
419
+ const { source, result } = inspectCitations(dirArg, draft);
420
+ const unknown = new Set(result.unknown), unverified = new Set(result.notVerified);
421
+ let start = 0, line = 1, nextLine = source.indexOf("\n");
422
+ const findings = [];
423
+ for (const citation of citationOccurrences(source)) {
424
+ while (nextLine >= 0 && nextLine < citation.start) {
425
+ start = nextLine + 1;
426
+ nextLine = source.indexOf("\n", start);
427
+ line++;
428
+ }
429
+ if (unknown.has(citation.key) || unverified.has(citation.key)) {
430
+ const kind = unknown.has(citation.key) ? "Unknown" : "Unverified";
431
+ findings.push({ name: `${line}:${citation.start - start + 1}`, state: "failed", detail: `${kind} citation ${citation.key}` });
432
+ }
433
+ }
434
+ return { ...result, checks: findings };
401
435
  }
402
436
 
403
437
  export async function planSet(dirArg: string, raw: unknown, ctx: Pick<Ctx, "actor">) {
@@ -450,7 +484,7 @@ function stepNumber(node: StepNode, key: string): number | undefined {
450
484
  if ((typeof value !== "string" && typeof value !== "number") || !/^-?\d+$/.test(String(value)) || !Number.isSafeInteger(Number(value))) throw new Error(`plan step ${node.id}.${key}: integer required; correct the argument with ares plan set`);
451
485
  return Number(value);
452
486
  }
453
- export async function planRun(dirArg: string, options: { parallel?: number }, ctx: Ctx) {
487
+ export async function planRun(dirArg: string, options: { parallel?: number; env?: NodeJS.ProcessEnv }, ctx: Ctx) {
454
488
  const { dir } = openStudy(dirArg);
455
489
  const attemptOptions = (node: StepNode, retryOf?: string): AttemptOptions => {
456
490
  const parent = retryOf ?? (node.args.retry !== undefined ? stepText(node, "retry") : undefined);
@@ -521,6 +555,11 @@ export async function planRun(dirArg: string, options: { parallel?: number }, ct
521
555
  const result = await paperBuild(dir, ctx);
522
556
  return { status: "done", output: { sha256: result.evidenceSha256 } };
523
557
  }
558
+ case "paper.render": {
559
+ // Fail closed: every renderer refusal is a failed step with its reason and no study write (#163).
560
+ try { const result = await paperRenderStep(dir, ctx, options.env ?? process.env); return { status: "done", output: { sha256: result.sha256 } }; }
561
+ catch (error) { if (error instanceof StudyLockBusyError) throw error; return { status: "failed", reason: error instanceof Error ? error.message : "renderer failed; run ares renderer check" }; }
562
+ }
524
563
  case "cite.check": { const value = cite(dir, resolve(dir, stepText(node, "draft"))); result = value; ok = value.ok; break; }
525
564
  }
526
565
  return { status: ok ? "done" : "failed", ...(ok ? { output: { sha256: sha256(JSON.stringify(result)) } } : { reason: "step reported failure; inspect its command result and inputs before retry" }) };
@@ -549,6 +588,18 @@ export async function selection(dirArg: string, raw: unknown, ctx: Pick<Ctx, "ac
549
588
  }
550
589
 
551
590
 
591
+ export async function selectionCalibrate(dirArg: string, options: CalibrationOptions, ctx: Pick<Ctx, "actor">) {
592
+ const { dir, study } = openStudy(dirArg);
593
+ requireExperiment(study);
594
+ return withLock(dir, () => calibrateSelection(dir, options, ctx.actor));
595
+ }
596
+
597
+ export async function ideaCategories(dirArg: string, raw: unknown, ctx: Pick<Ctx, "actor">) {
598
+ const { dir, study } = openStudy(dirArg); requireExperiment(study);
599
+ return withLock(dir, () => setCategories(dir, raw, ctx.actor));
600
+ }
601
+ /** Read-only and advisory: no lock, no write, no gate. */
602
+ export const ideaReport = (dir: string, options: { run?: string; window?: number } = {}) => foldIdeaReport(dir, options);
552
603
  export const investigateShow = (dir: string) => showInvestigation(dir);
553
604
  export async function investigateClose(dirArg: string, ctx: Pick<Ctx, "actor">) {
554
605
  const { dir, study } = openStudy(dirArg); requireExperiment(study);
@@ -599,14 +650,27 @@ export async function finalClose(dirArg: string, ctx: Pick<Ctx, "actor">) {
599
650
 
600
651
  export const posthocShow = (dir: string) => showPosthoc(dir);
601
652
 
602
- export const paperCheck = (dir: string) => checkPaper(dir);
653
+ export const paperCheck = (dir: string, doc?: PaperDocument) => checkPaper(dir, doc);
603
654
  export async function paperPlanSet(dirArg: string, raw: unknown, ctx: Pick<Ctx, "actor">) {
604
655
  const { dir } = openStudy(dirArg); return withLock(dir, () => setPaperPlan(dir, raw, ctx.actor));
605
656
  }
606
657
  export const paperPlanShow = (dir: string) => showPaperPlan(dir);
607
658
 
608
- export async function paperBuild(dirArg: string, ctx: Pick<Ctx, "actor">) {
609
- const { dir } = openStudy(dirArg); return withLock(dir, () => buildPaper(dir, ctx.actor));
659
+ export async function paperBuild(dirArg: string, ctx: Pick<Ctx, "actor">, doc?: PaperDocument) {
660
+ const { dir } = openStudy(dirArg); return withLock(dir, () => buildPaper(dir, ctx.actor, doc));
661
+ }
662
+ /** Records an external render of the current build; never runs a renderer (#162). */
663
+ export async function paperRenderRecord(dirArg: string, file: string, receipt: string, ctx: Pick<Ctx, "actor">, doc?: PaperDocument) {
664
+ const { dir } = openStudy(dirArg); return withLock(dir, () => recordPaperRender(dir, file, receipt, ctx.actor, doc));
665
+ }
666
+ export const paperRenderShow = (dir: string, doc?: PaperDocument) => showPaperRender(dir, doc);
667
+ /** Machine-local renderer settings live under the family home, never in the study (#163). */
668
+ export const rendererSet = (dir: string, raw: { command: unknown; timeoutS?: unknown }, env: NodeJS.ProcessEnv) => setRenderer(consoleHome(env), dir, raw);
669
+ export const rendererShow = (dir: string, env: NodeJS.ProcessEnv) => showRenderer(consoleHome(env), dir);
670
+ export const rendererCheck = (dir: string, env: NodeJS.ProcessEnv) => checkRenderer(consoleHome(env), dir, env);
671
+ export async function paperRenderStep(dirArg: string, ctx: Pick<Ctx, "actor" | "runner">, env: NodeJS.ProcessEnv) {
672
+ const { dir } = openStudy(dirArg);
673
+ return runRenderStep(dir, { home: consoleHome(env), actor: ctx.actor, ...(ctx.runner ? { runner: ctx.runner } : {}) }, (file, receipt) => withLock(dir, () => recordPaperRender(dir, file, receipt, ctx.actor)));
610
674
  }
611
675
 
612
676
  export async function reviewAdd(dirArg: string, raw: unknown, ctx: Pick<Ctx, "actor">) {
@@ -677,6 +741,11 @@ export interface WatchStarted { started: true; configSha256: string }
677
741
  /** Acknowledge only validated admission; the finite pass keeps the same lock until its receipt is written. */
678
742
  export function watchRunDetached(dirArg: string, ctx: Ctx, track?: (completion: Promise<void>, terminate: () => void) => void): Promise<WatchStarted> {
679
743
  const { dir, study } = openStudy(dirArg);
744
+ const report = (message: string) => {
745
+ const tty = Boolean(process.stderr.isTTY);
746
+ const columns = Math.min(streamWidth(tty, process.stderr.columns) ?? 80, 80);
747
+ console.error(renderError(fillMessage(message, { dir }), tty, colorFor({}, tty) === true, outputAscii({}, process.env), columns));
748
+ };
680
749
  let accept!: (value: WatchStarted) => void, reject!: (cause: unknown) => void, started = false;
681
750
  let terminate = () => {};
682
751
  const admission = new Promise<WatchStarted>((resolve, refuse) => { accept = resolve; reject = refuse; });
@@ -686,7 +755,7 @@ export function watchRunDetached(dirArg: string, ctx: Ctx, track?: (completion:
686
755
  terminate = () => {
687
756
  if (settled) return; settled = true;
688
757
  recordWatchFailure(dir, snapshot, ctx.actor, "terminated");
689
- console.error("ares watch: terminated; inspect ares watch show and lit list before retrying");
758
+ report("watch: terminated; run ares watch show <dir>");
690
759
  };
691
760
  started = true; accept({ started: true, configSha256: snapshot.sha256 });
692
761
  try { await watchRunLocked(dir, snapshot, ctx); settled = true; }
@@ -694,11 +763,11 @@ export function watchRunDetached(dirArg: string, ctx: Ctx, track?: (completion:
694
763
  if (settled) return; settled = true;
695
764
  const kind = watchFailureClass(cause);
696
765
  recordWatchFailure(dir, snapshot, ctx.actor, kind);
697
- console.error(`ares watch: background pass failed (${kind}); inspect ares watch show and lit list before retrying`);
766
+ report(`watch: background pass failed (${kind}); run ares watch show <dir>`);
698
767
  }
699
768
  }).then(() => {}, cause => {
700
769
  if (!started) reject(cause);
701
- else console.error(`ares watch: failure receipt could not be written (${watchFailureClass(cause)}); restore study storage, inspect ares watch show and lit list, then retry`);
770
+ else report(`watch: failure receipt could not be written (${watchFailureClass(cause)}); restore study storage and run ares watch show <dir>`);
702
771
  });
703
772
  track?.(completion, () => terminate());
704
773
  return admission;
@@ -4,6 +4,8 @@ import { runOnExecutor, type Executor, type ProcessRunner } from "./executor.ts"
4
4
  export const ARTIFACT_FILES = 500, ARTIFACT_BYTES = 256 * 1024 * 1024;
5
5
  export const ARTIFACT_CAPTURE_BYTES = 65_536;
6
6
  export const ARTIFACT_HEADERS = 2048, ARTIFACT_METADATA_BYTES = 65_536;
7
+ /** One entry header plus at most a GNU long-name (`L`) and a PAX (`x`) header, plus one shared global (`g`) slack. */
8
+ const TAR_HEADERS_PER_ENTRY = 4;
7
9
  export const ARTIFACT_WIRE_BYTES = ARTIFACT_BYTES + 16 * 1024 * 1024;
8
10
  export type ArtifactErrorCode = "invalid-artifact" | "artifact-limit" | "artifact-read";
9
11
  export class ArtifactError extends Error {
@@ -93,7 +95,7 @@ class TarArtifacts {
93
95
  private pendingMetadata = false;
94
96
  private longName?: string;
95
97
  private seen = new Map<string, "file" | "directory">();
96
- constructor(private capture: string | undefined, private captureBytes: number, private maxBytes: number, private maxFiles: number) {}
98
+ constructor(private capture: string | undefined, private captureBytes: number, private maxBytes: number, private maxFiles: number, private maxHeaders = ARTIFACT_HEADERS) {}
97
99
  push(chunk: Uint8Array): void {
98
100
  if (!(chunk instanceof Uint8Array)) return invalid("non-binary archive stream");
99
101
  this.wireBytes += chunk.byteLength;
@@ -126,7 +128,7 @@ class TarArtifacts {
126
128
  const header = this.header;
127
129
  if (header.every(byte => byte === 0)) { if (++this.zeros === 2) this.ended = true; return; }
128
130
  if (this.zeros) return invalid("entry after an incomplete tar end marker");
129
- if (++this.headers > ARTIFACT_HEADERS) return limit(`archive exceeds ${ARTIFACT_HEADERS} headers`);
131
+ if (++this.headers > this.maxHeaders) return limit(`archive exceeds ${this.maxHeaders} headers`);
130
132
  const expected = octal(header.subarray(148, 156));
131
133
  let checksum = 0;
132
134
  for (let i = 0; i < 512; i++) checksum += i >= 148 && i < 156 ? 32 : header[i]!;
@@ -206,6 +208,22 @@ class TarArtifacts {
206
208
  }
207
209
  }
208
210
 
211
+ /**
212
+ * Streaming member scan for an archive the caller transfers elsewhere: the same header, PAX and path validation as
213
+ * artifact reads, exposing each regular member's path and digest when the archive ends. The caller sizes the header
214
+ * budget from its own entry limits (each file or directory: its header plus GNU long-name or PAX headers). Metadata
215
+ * stays bounded per record by ARTIFACT_METADATA_BYTES, which already exceeds the 4096-byte path limit.
216
+ */
217
+ export class TarMemberScan {
218
+ private readonly parser: TarArtifacts;
219
+ constructor(maxBytes: number, maxFiles: number, maxEntries: number) {
220
+ const entries = bound(maxEntries, 1_000_000, "maxEntries");
221
+ this.parser = new TarArtifacts(undefined, 0, bound(maxBytes, ARTIFACT_BYTES, "maxBytes"), bound(maxFiles, ARTIFACT_FILES, "maxFiles"), Math.max(ARTIFACT_HEADERS, entries * TAR_HEADERS_PER_ENTRY));
222
+ }
223
+ push(chunk: Uint8Array): void { this.parser.push(chunk); }
224
+ finish(): ArtifactFile[] { return this.parser.finish().files; }
225
+ }
226
+
209
227
  /** Hash regular artifacts, retaining no payload except an explicitly selected bounded capture. */
210
228
  export async function readArtifactArchive(executor: Executor, command: string, args: string[], runner: ProcessRunner, options: ArtifactArchiveOptions = {}): Promise<ArtifactArchive> {
211
229
  const capture = options.capture === undefined ? undefined : relative(options.capture), captureBytes = bound(options.captureBytes ?? ARTIFACT_CAPTURE_BYTES, ARTIFACT_CAPTURE_BYTES, "captureBytes");
@@ -12,12 +12,13 @@ import { randomUUID } from "node:crypto";
12
12
  import { AsyncLocalStorage } from "node:async_hooks";
13
13
  import { boundedText, commit, openStudy, plain, readJsonFile, readTextBounded, requireExperiment, requireGate, sha256, withLock, StudyLockBusyError, type Actor, type PendingEvent } from "../study.ts";
14
14
  import { canonical, designBinding, sameProtocolInputs, frozenProtocol, validateStoredProtocol, protocolHash, readProtocol, readDesign, type Protocol } from "./protocol.ts";
15
- import { buildContainerArgs, probeGpuAdmission, GpuAdmissionDeferred, validateGpuDevices, validateContainerInputSources, executionPathsOverlap, verifyExecutorInputs, InputVerificationError, checkExecutorInputs, containerName, readExecutor, runOnExecutor, shellQuote, spawnRunner, startWatchdog, type ContainerPaths, type Executor, type ProcessRunner, type Stage } from "./executor.ts";
15
+ import { buildContainerArgs, probeGpuAdmission, GpuAdmissionDeferred, validateGpuDevices, validateContainerInputSources, executionPathsOverlap, verifyExecutorInputs, InputVerificationError, checkExecutorInputs, stageContainerName, readExecutor, runOnExecutor, shellQuote, spawnRunner, startWatchdog, type ContainerPaths, type Executor, type ProcessRunner, type Stage } from "./executor.ts";
16
16
  import { resolveSnapshot, transferSnapshot, transferTask } from "./snapshot.ts";
17
+ import { screenCandidate, type ScreenSummary } from "./screen.ts";
17
18
  import { collectEvaluation as defaultEvaluationCollector, collectStageEvidence as defaultStageCollector, EvidenceError, MetricsError, OUTPUT_METADATA_BYTES, outputBudget, type StageEvidence } from "./metrics.ts";
18
19
 
19
20
  export type AttemptStatus = "running" | "succeeded" | "failed" | "cancelled" | "unknown";
20
- export interface AttemptStage { image: string; argv: string[]; mounts: { target: string; readOnly: boolean }[]; network: "none"; limits: Protocol["limits"]; user: string; containerId?: string; startedAt: string; endedAt?: string; exitCode?: number; evidence?: StageEvidence; evidenceError?: { reason: string; message: string }; launchPending?: true }
21
+ export interface AttemptStage { image: string; argv: string[]; mounts: { target: string; readOnly: boolean }[]; network: "none"; limits: Protocol["limits"]; user: string; containerName?: string; containerId?: string; startedAt: string; endedAt?: string; exitCode?: number; evidence?: StageEvidence; evidenceError?: { reason: string; message: string }; launchPending?: true }
21
22
  export interface Evaluation { metrics: { name: string; unit: string; value: number; provenance: "ares-observed" }[]; outputs: { path: string; sha256: string; bytes: number }[] }
22
23
  export interface Attempt {
23
24
  v: 1 | 2 | 3; pipeline?: PipelineState; reuse?: AttemptReuseState; freshRequest?: { reuse: "off" | "eligible"; forceFresh: boolean }; id: string; studyId: string; run: string; protocolHash: string; sealBinding: string; commit: string; treeId: string; snapshotSha256?: string; seed: number; label: string; retryOf?: string;
@@ -275,7 +276,7 @@ function executionProtocol(dir: string, attempt: Attempt): Protocol {
275
276
  return { ...attempt.protocol, inputs: current.inputs };
276
277
  }
277
278
  function stageRecord(attempt: Attempt, stage: Stage, user: string, ctx: AttemptContext): AttemptStage {
278
- return { image: attempt.protocol[stage].image, argv: attempt.protocol[stage].command, mounts: [...(stage === "candidate" ? [{ target: "/workspace", readOnly: true }, { target: "/out", readOnly: false }] : [{ target: "/eval", readOnly: true }, { target: "/candidate", readOnly: true }, { target: "/result", readOnly: false }]), ...(pipelineInputRoot(attempt) ? [{ target: "/in", readOnly: true }] : []), ...Object.values(attempt.protocol.inputs ?? {}).flatMap(input => input.mount[stage] ? [{ target: input.mount[stage]!, readOnly: true }] : [])], network: "none", limits: attempt.protocol.limits, user, startedAt: at(ctx) };
279
+ return { image: attempt.protocol[stage].image, argv: attempt.protocol[stage].command, mounts: [...(stage === "candidate" ? [{ target: "/workspace", readOnly: true }, { target: "/out", readOnly: false }] : [{ target: "/eval", readOnly: true }, { target: "/candidate", readOnly: true }, { target: "/result", readOnly: false }]), ...(pipelineInputRoot(attempt) ? [{ target: "/in", readOnly: true }] : []), ...Object.values(attempt.protocol.inputs ?? {}).flatMap(input => input.mount[stage] ? [{ target: input.mount[stage]!, readOnly: true }] : [])], network: "none", limits: attempt.protocol.limits, user, containerName: stageContainerName(attempt.studyId, attempt.id, stage, attempt.pipeline && stage === "candidate" ? attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name : undefined), startedAt: at(ctx) };
279
280
  }
280
281
 
281
282
  /** Validate observed container settings before describing its sealing as ares-observed. */
@@ -348,10 +349,14 @@ async function recordVerifiedStage(dir: string, attempt: Attempt, state: Observe
348
349
  return event;
349
350
  }, approvals);
350
351
  }
351
- function attemptContainerName(attempt: Attempt): string {
352
- const base = containerName(attempt.id, attempt.stage);
352
+ function legacyContainerName(attempt: Attempt): string {
353
+ // Records written before study-scoped names carry no launched name; keep resolving the one they used.
354
+ const base = `ares-${attempt.id}-${attempt.stage}`;
353
355
  return attempt.pipeline && attempt.stage === "candidate" ? `${base}-${attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name}` : base;
354
356
  }
357
+ function attemptContainerName(attempt: Attempt): string {
358
+ return attempt.stages[attempt.stage]?.containerName ?? legacyContainerName(attempt);
359
+ }
355
360
  async function inspect(dir: string, attempt: Attempt, ctx: AttemptContext, ownershipOnly = false) {
356
361
  const protocol = ownershipOnly ? attempt.protocol : executionProtocol(dir, attempt);
357
362
  let result;
@@ -504,7 +509,8 @@ async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptC
504
509
  if (decision.outcome === "reused") return attempt;
505
510
  }
506
511
  // Keep configuration refusals outside the uncertain container-start catch.
507
- args = buildContainerArgs({ protocol, stage: attempt.stage, studyId: openStudy(dir).study.id, attemptId: attempt.id, seed: attempt.seed, user, paths: attempt.paths, ...(attempt.gpuDevices ? { gpuDevices: attempt.gpuDevices } : {}), ...(attempt.pipeline && attempt.stage === "candidate" ? { pipeline: { name: attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name, inputRoot: pipelineInputRoot(attempt)!, seed: attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.seed } } : {}) });
512
+ // The record's own name is authoritative: a stage recorded before study-scoped names must start where inspect looks.
513
+ args = buildContainerArgs({ protocol, stage: attempt.stage, studyId: attempt.studyId, attemptId: attempt.id, name: attemptContainerName(attempt), seed: attempt.seed, user, paths: attempt.paths, ...(attempt.gpuDevices ? { gpuDevices: attempt.gpuDevices } : {}), ...(attempt.pipeline && attempt.stage === "candidate" ? { pipeline: { name: attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.name, inputRoot: pipelineInputRoot(attempt)!, seed: attempt.pipeline.definition.candidate.stages[attempt.pipeline.index]!.seed } } : {}) });
508
514
  if (attempt.reuse) attempt = await update(dir, attempt.id, recoveryCtx, current => {
509
515
  if (current.status !== "running" || current.stage !== attempt.stage || current.pipeline?.index !== attempt.pipeline?.index || current.launching?.token !== attempt.launching?.token) throw new InputVerificationError("reuse: container launch ownership changed; run ares attempt reconcile <dir> after the active control operation finishes before retrying");
510
516
  requireCopilotAccept(dir, "hypotheses");
@@ -530,7 +536,7 @@ async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptC
530
536
  if (!/^[a-f0-9]{64}$/.test(cid)) throw hostError(attempt, "container start");
531
537
  startedId = cid;
532
538
  attempt.stages[attempt.stage]!.containerId = cid;
533
- await startWatchdog(attempt.executor, attempt.id, attempt.stage, remainingWallSeconds(dir, attempt, ctx), ctx.runner ?? spawnRunner, cid);
539
+ await startWatchdog(attempt.executor, attemptContainerName(attempt), remainingWallSeconds(dir, attempt, ctx), ctx.runner ?? spawnRunner, cid);
534
540
  const state = await inspect(dir, attempt, ctx); if (!state) throw hostError(attempt, "container start verification");
535
541
  return recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.started");
536
542
  } catch {
@@ -539,7 +545,7 @@ async function launch(dir: string, attempt: Attempt, user: string, ctx: AttemptC
539
545
  // A lost response is not proof that Docker rejected the start. Adopt only a verified owned container.
540
546
  const state = await inspect(dir, attempt, ctx);
541
547
  if (state) {
542
- if (state.running) await startWatchdog(attempt.executor, attempt.id, attempt.stage, remainingWallSeconds(dir, attempt, ctx), ctx.runner ?? spawnRunner, state.id);
548
+ if (state.running) await startWatchdog(attempt.executor, attemptContainerName(attempt), remainingWallSeconds(dir, attempt, ctx), ctx.runner ?? spawnRunner, state.id);
543
549
  return recordVerifiedStage(dir, attempt, state, ctx, "attempt.stage.recovered");
544
550
  }
545
551
  } catch {
@@ -604,6 +610,17 @@ export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: A
604
610
  validateContainerInputSources(protocol, { snapshot: posix.join(inputRoot, "snapshot"), output: posix.join(inputRoot, "output"), evaluator: posix.join(inputRoot, "task", "evaluator"), result: posix.join(inputRoot, "result") });
605
611
  const existingAttempt = await withLock(dir, () => load(dir).find(a => a.id === wanted)), existing = existingAttempt !== undefined;
606
612
  if (existingAttempt) existingReuseControls(existingAttempt, options);
613
+ // The screen runs before any budget, record or container exists, so a hit costs nothing but the read.
614
+ let screened: ScreenSummary | undefined;
615
+ if (!existing && definition.screen !== undefined) {
616
+ const { hits, summary } = await screenCandidate(options.repo, snapshot.commit, definition.screen, protocol.inputs ?? {}, executor, ctx.runner ?? spawnRunner);
617
+ if (hits.length) {
618
+ // Ledger only: the rule and the candidate path stay, the matched text never does.
619
+ await withLock(dir, () => commit(dir, [], [{ actor: ctx.actor, type: "attempt.screen.refused", data: { commit: snapshot.commit, hits } }]));
620
+ throw new Error(`attempt screen: candidate commit ${snapshot.commit} carries material held out from the candidate (${hits.map(hit => `${hit.rule} ${hit.path}${hit.line === undefined ? "" : `:${hit.line}`}`).join(", ")}); remove that material from the candidate commit, or change the screen through an approved design change, then retry ares attempt run`);
621
+ }
622
+ screened = summary;
623
+ }
607
624
  const verifiedInputs = !existing && protocol.inputs !== undefined ? await verifyExecutorInputs(executor, protocol, ctx.runner ?? spawnRunner) : undefined;
608
625
  let gpuDevices: string[] | undefined;
609
626
  if (!existing && executor.gpu && protocol.limits.gpus > 0) {
@@ -635,7 +652,7 @@ export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: A
635
652
  if (record.pipeline) record.paths = pipelinePaths(record);
636
653
  if (approval.length) record.pendingAutoApproval = binding!;
637
654
  if (finalAuthorization) { record.finalBinding = finalAuthorization.binding; record.finalWinner = finalAuthorization.winner; if (finalAuthorization.auto) record.pendingFinalApproval = finalAuthorization.binding; }
638
- commit(dir, [[file(dir, record), JSON.stringify(record, null, 2) + "\n", ATTEMPT_BYTES]], [{ actor: ctx.actor, type: "attempt.started", data: { id: wanted, run, seed, commit: record.commit, treeId: record.treeId } }]);
655
+ commit(dir, [[file(dir, record), JSON.stringify(record, null, 2) + "\n", ATTEMPT_BYTES]], [{ actor: ctx.actor, type: "attempt.started", data: { id: wanted, run, seed, commit: record.commit, treeId: record.treeId, ...(screened === undefined ? {} : { screen: screened }) } }]);
639
656
  created = true; return record;
640
657
  }); } catch (error) {
641
658
  if (reserved) await withLock(dir, async () => {
@@ -0,0 +1,125 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { commit, openStudy, plain, readLedger, readTextBounded, requireExperiment, sha256, type Actor } from "../study.ts";
4
+ import { listAttempts, type Attempt } from "./attempts.ts";
5
+ import { readFinalSeeds } from "./final.ts";
6
+ import { protocolHash, readProtocol, type ProtocolDefinition } from "./protocol.ts";
7
+ import { observedMetric, readSelection, type Selection } from "./selection.ts";
8
+
9
+ export interface CalibrationOptions { fromRun: string; nullCommit?: string; z?: number }
10
+ interface CalibrationReceipt {
11
+ v: 1; method: "seed-sd" | "aa"; metric: string; commit: string; null?: string;
12
+ seeds: number[]; attempts: string[]; n: number; sd: number; z: number;
13
+ minSeeds: number; recommendedMinDelta: number;
14
+ }
15
+ const CALIBRATION_BYTES = 65_536;
16
+ const RUN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
17
+ const COMMIT = /^[a-f0-9]{40}$/;
18
+ const HASH = /^[a-f0-9]{64}$/;
19
+
20
+ function invalid(cause: string): never {
21
+ throw new Error(`selection calibrate: ${cause}; inspect the selected run and retry ares selection calibrate <dir> --from-run RUN`);
22
+ }
23
+
24
+ function receiptPath(dir: string, run: string, hash?: string): string {
25
+ return hash === undefined ? join(dir, "runs", run, "calibration.json")
26
+ : join(dir, "runs", run, "calibrations", `${hash}.json`);
27
+ }
28
+
29
+ function sampleSd(values: number[]): number {
30
+ const scale = Math.max(...values.map(Math.abs));
31
+ if (scale === 0) return 0;
32
+ const scaled = values.map(value => value / scale);
33
+ const mean = scaled.reduce((sum, value) => sum + value, 0) / scaled.length;
34
+ return Math.sqrt(scaled.reduce((sum, value) => sum + (value - mean) ** 2, 0) / (scaled.length - 1)) * scale;
35
+ }
36
+
37
+ export function readBoundCalibration(dir: string, rule: Extract<Selection, { v: 2 }>, protocol: ProtocolDefinition) {
38
+ const hash = rule.calibration?.sha256;
39
+ if (!hash) return undefined;
40
+ const event = readLedger(dir).findLast(entry => entry.type === "selection.calibrated" && entry.data.sha256 === hash);
41
+ const run = event?.data.run;
42
+ const fix = "run ares selection calibrate <dir> --from-run RUN and bind the resulting sha256 in ares selection";
43
+ if (typeof run !== "string" || !RUN.test(run)) throw new Error(`selection.calibration.sha256: no recorded calibration for this digest; ${fix}`);
44
+ if (event?.data.protocolHash !== protocolHash(protocol)) throw new Error(`selection.calibration: protocol differs from the recorded calibration; ${fix}`);
45
+ let text: string, receipt: unknown;
46
+ try {
47
+ text = readTextBounded(receiptPath(dir, run, hash), CALIBRATION_BYTES);
48
+ receipt = JSON.parse(text);
49
+ } catch { throw new Error(`selection.calibration: recorded receipt is unreadable or invalid; restore the bounded receipt or ${fix}`); }
50
+ if (sha256(text) !== hash || !plain(receipt) || receipt.v !== 1) throw new Error(`selection.calibration: receipt bytes do not match the recorded calibration; restore the original receipt or ${fix}`);
51
+ if (receipt.metric !== rule.metric || receipt.commit !== rule.baseline.commit || receipt.minSeeds !== rule.minSeeds) throw new Error(`selection.calibration: the metric, baseline or minimum seed count differs from the recorded calibration; ${fix}`);
52
+ const recommendation = receipt.recommendedMinDelta;
53
+ if (typeof recommendation !== "number" || !Number.isFinite(recommendation) || recommendation < 0) throw new Error(`selection.calibration: recorded recommendation is invalid; ${fix}`);
54
+ return { recommendedMinDelta: recommendation, minDelta: rule.minDelta, belowNoise: rule.minDelta < recommendation };
55
+ }
56
+
57
+ export function validateCalibrationOptions(options: CalibrationOptions) {
58
+ const fromRun = options.fromRun, nullCommit = options.nullCommit?.toLowerCase(), z = options.z ?? 2;
59
+ if (typeof fromRun !== "string" || !RUN.test(fromRun)) invalid("from-run must be a valid run name");
60
+ if (nullCommit !== undefined && !COMMIT.test(nullCommit)) invalid("null commit must be a full 40-hex commit");
61
+ if (typeof z !== "number" || !Number.isFinite(z) || z <= 0) invalid("z must be a finite positive number");
62
+ return { fromRun, ...(nullCommit === undefined ? {} : { nullCommit }), z };
63
+ }
64
+
65
+ /** Caller holds the study lock. Only current-protocol, non-reserved earliest successes count. */
66
+ export function calibrateSelection(dirArg: string, options: CalibrationOptions, actor: Actor) {
67
+ const { dir, study } = openStudy(dirArg);
68
+ requireExperiment(study);
69
+ const { fromRun: run, nullCommit: other, z } = validateCalibrationOptions(options);
70
+ const protocol = readProtocol(dir), rule = protocol && readSelection(dir, protocol);
71
+ if (!protocol || !rule) invalid("define a protocol and selection rule first");
72
+ if (other === rule.baseline.commit) invalid("null commit must differ from the baseline commit");
73
+ const hash = protocolHash(protocol), metric = protocol.metrics.find(entry => entry.name === rule.metric)!;
74
+ const reserved = new Set(readFinalSeeds(dir, protocol)?.seeds), seeds = new Set(protocol.seeds);
75
+ const attempts = listAttempts(dir, { run, status: "succeeded" }).attempts;
76
+ const events = readLedger(dir);
77
+ const byId = new Map(attempts.map(attempt => [attempt.id, attempt]));
78
+ const started = new Set<string>();
79
+ const baseline = new Map<number, Attempt>(), nullArm = new Map<number, Attempt>();
80
+ for (const event of events) {
81
+ const { id } = event.data;
82
+ if (event.type !== "attempt.started" || typeof id !== "string") continue;
83
+ const attempt = byId.get(id);
84
+ if (!attempt || attempt.protocolHash !== hash || (attempt.commit !== rule.baseline.commit && attempt.commit !== other)
85
+ || !seeds.has(attempt.seed) || reserved.has(attempt.seed)) continue;
86
+ if (started.has(id) || attempt.studyId !== study.id || event.data.run !== run || event.data.commit !== attempt.commit || event.data.seed !== attempt.seed) invalid(`attempt ${id} has a duplicate or mismatched start receipt`);
87
+ started.add(id);
88
+ const arm = attempt.commit === rule.baseline.commit ? baseline : nullArm;
89
+ if (!arm.has(attempt.seed)) arm.set(attempt.seed, attempt);
90
+ }
91
+
92
+ if (baseline.size < 3) invalid("at least three non-reserved baseline seeds are required");
93
+ const pairedSeeds = [...baseline.keys()].filter(seed => other === undefined || nullArm.has(seed)).sort((a, b) => a - b);
94
+ if (pairedSeeds.length < 3) invalid("at least three non-reserved paired A/A seeds are required");
95
+ if (other !== undefined) {
96
+ const trees = new Set([...baseline.values(), ...nullArm.values()].map(attempt => attempt.treeId));
97
+ if (trees.size !== 1 || !COMMIT.test(trees.values().next().value ?? "")) invalid("A/A arms must have the same recorded task tree id");
98
+ }
99
+ const evidence: string[] = [];
100
+ const measured = (attempt: Attempt) => {
101
+ const value = observedMetric(attempt, metric);
102
+ if (value === undefined) invalid(`attempt ${attempt.id} lacks the validated primary metric`);
103
+ evidence.push(attempt.id);
104
+ return value;
105
+ };
106
+ const scores = pairedSeeds.map(seed => {
107
+ const value = measured(baseline.get(seed)!);
108
+ return other === undefined ? value : measured(nullArm.get(seed)!) - value;
109
+ });
110
+ if (scores.some(score => !Number.isFinite(score))) invalid("paired deltas overflow; rescale the primary metric");
111
+ const sd = sampleSd(scores), method = other === undefined ? "seed-sd" : "aa";
112
+ const recommendedMinDelta = (sd / Math.sqrt(rule.minSeeds)) * (method === "seed-sd" ? Math.SQRT2 : 1) * z;
113
+ if (!Number.isFinite(sd) || !Number.isFinite(recommendedMinDelta)) invalid("calibration overflows; rescale the metric or reduce z");
114
+ const receipt: CalibrationReceipt = { v: 1, method, metric: rule.metric, commit: rule.baseline.commit, ...(other === undefined ? {} : { null: other }),
115
+ seeds: pairedSeeds, attempts: evidence, n: pairedSeeds.length, sd, z, minSeeds: rule.minSeeds, recommendedMinDelta };
116
+ const text = JSON.stringify(receipt, null, 2) + "\n", sha = sha256(text);
117
+ const latest = receiptPath(dir, run), archived = receiptPath(dir, run, sha);
118
+ const previous = existsSync(latest) ? readTextBounded(latest, CALIBRATION_BYTES) : undefined;
119
+ const recorded = events.some(event => event.type === "selection.calibrated" && event.data.run === run && event.data.sha256 === sha && event.data.protocolHash === hash);
120
+ if (existsSync(archived) && readTextBounded(archived, CALIBRATION_BYTES) !== text) invalid("immutable calibration receipt differs from its digest; restore the original receipt");
121
+ if (previous !== text || !recorded || !existsSync(archived)) {
122
+ commit(dir, [[latest, text, CALIBRATION_BYTES], [archived, text, CALIBRATION_BYTES]], [{ actor, type: "selection.calibrated", data: { run, sha256: sha, protocolHash: hash } }]);
123
+ }
124
+ return { ...receipt, sha256: sha, ...(method === "seed-sd" ? { assumption: "Assumes independent arms. This is conservative when pairing by seed removes shared variance." } : {}) };
125
+ }