@staix/agent-research 0.3.1 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -0
- package/README.md +84 -19
- package/package.json +4 -1
- package/src/cli-output.ts +446 -0
- package/src/cli.ts +208 -66
- package/src/commands-table.ts +213 -93
- package/src/commands.ts +75 -13
- package/src/exp/attempts.ts +13 -1
- package/src/exp/calibrate.ts +125 -0
- package/src/exp/executor.ts +98 -13
- package/src/exp/final.ts +12 -3
- package/src/exp/idea-report.ts +97 -0
- package/src/exp/ideas.ts +90 -6
- package/src/exp/investigate.ts +25 -22
- package/src/exp/protocol.ts +26 -1
- package/src/exp/screen.ts +83 -0
- package/src/exp/selection.ts +110 -4
- package/src/exp/stages.ts +3 -1
- package/src/harness/transitions.ts +37 -5
- package/src/manifest.ts +13 -5
- package/src/mcp-tools.ts +67 -14
- package/src/memory/archive.ts +8 -3
- package/src/paper/build.ts +39 -25
- package/src/paper/check.ts +46 -15
- package/src/paper/dependencies.ts +47 -0
- package/src/paper/document.ts +19 -0
- package/src/paper/figures.ts +152 -0
- package/src/paper/hygiene.ts +16 -5
- package/src/paper/plan.ts +71 -29
- package/src/paper/point-evidence.ts +27 -12
- package/src/paper/render.ts +113 -0
- package/src/paper/renderer.ts +128 -0
- package/src/paper/review.ts +41 -5
- package/src/plan/definition.ts +6 -1
- package/src/playbook.ts +20 -10
- package/src/provenance.ts +4 -3
- package/src/study-export.ts +7 -4
- package/src/study.ts +9 -4
- package/src/ui/plugin.ts +3 -1
package/src/exp/attempts.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { boundedText, commit, openStudy, plain, readJsonFile, readTextBounded, r
|
|
|
14
14
|
import { canonical, designBinding, sameProtocolInputs, frozenProtocol, validateStoredProtocol, protocolHash, readProtocol, readDesign, type Protocol } from "./protocol.ts";
|
|
15
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";
|
|
@@ -609,6 +610,17 @@ export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: A
|
|
|
609
610
|
validateContainerInputSources(protocol, { snapshot: posix.join(inputRoot, "snapshot"), output: posix.join(inputRoot, "output"), evaluator: posix.join(inputRoot, "task", "evaluator"), result: posix.join(inputRoot, "result") });
|
|
610
611
|
const existingAttempt = await withLock(dir, () => load(dir).find(a => a.id === wanted)), existing = existingAttempt !== undefined;
|
|
611
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
|
+
}
|
|
612
624
|
const verifiedInputs = !existing && protocol.inputs !== undefined ? await verifyExecutorInputs(executor, protocol, ctx.runner ?? spawnRunner) : undefined;
|
|
613
625
|
let gpuDevices: string[] | undefined;
|
|
614
626
|
if (!existing && executor.gpu && protocol.limits.gpus > 0) {
|
|
@@ -640,7 +652,7 @@ export async function runAttempt(dirArg: string, options: AttemptOptions, ctx: A
|
|
|
640
652
|
if (record.pipeline) record.paths = pipelinePaths(record);
|
|
641
653
|
if (approval.length) record.pendingAutoApproval = binding!;
|
|
642
654
|
if (finalAuthorization) { record.finalBinding = finalAuthorization.binding; record.finalWinner = finalAuthorization.winner; if (finalAuthorization.auto) record.pendingFinalApproval = finalAuthorization.binding; }
|
|
643
|
-
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 }) } }]);
|
|
644
656
|
created = true; return record;
|
|
645
657
|
}); } catch (error) {
|
|
646
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
|
+
}
|
package/src/exp/executor.ts
CHANGED
|
@@ -231,7 +231,10 @@ export const INPUT_MANIFEST_FILES = 100_000, INPUT_MANIFEST_TIMEOUT_MS = 300_000
|
|
|
231
231
|
// ponytail: ceiling 100,000 files/directories, depth 64 and 5 minutes; bytes stream in 1 MiB chunks, never into the study.
|
|
232
232
|
export const INPUT_MANIFEST_SCRIPT = String.raw`import os,sys,stat,hashlib,json
|
|
233
233
|
MAX=100000
|
|
234
|
+
mode=sys.argv[2] if len(sys.argv)>2 else 'manifest'
|
|
235
|
+
cap=int(sys.argv[3]) if len(sys.argv)>3 else MAX
|
|
234
236
|
records=[]
|
|
237
|
+
blobs=[]
|
|
235
238
|
entries=0
|
|
236
239
|
directories=0
|
|
237
240
|
total=0
|
|
@@ -257,12 +260,14 @@ def walk(fd,prefix,depth):
|
|
|
257
260
|
walk(child,name,depth+1)
|
|
258
261
|
finally: os.close(child)
|
|
259
262
|
elif stat.S_ISREG(info.st_mode):
|
|
260
|
-
if len(records)>=MAX or info.st_size>9007199254740991-total: raise ValueError()
|
|
263
|
+
if len(records)>=(cap if mode=='hashes' else MAX) or info.st_size>9007199254740991-total: raise ValueError()
|
|
261
264
|
child=os.open(item.name,os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK,dir_fd=fd)
|
|
262
265
|
try:
|
|
263
266
|
opened=os.fstat(child)
|
|
264
267
|
if not stat.S_ISREG(opened.st_mode) or identity(opened)!=identity(info): raise ValueError()
|
|
265
268
|
digest=hashlib.sha256()
|
|
269
|
+
blob=hashlib.sha1()
|
|
270
|
+
if mode=='hashes': blob.update(('blob %d\0' % info.st_size).encode('utf-8'))
|
|
266
271
|
size=0
|
|
267
272
|
while True:
|
|
268
273
|
chunk=os.read(child,1048576)
|
|
@@ -270,10 +275,12 @@ def walk(fd,prefix,depth):
|
|
|
270
275
|
size+=len(chunk)
|
|
271
276
|
if size>info.st_size: raise ValueError()
|
|
272
277
|
digest.update(chunk)
|
|
278
|
+
if mode=='hashes': blob.update(chunk)
|
|
273
279
|
if size!=info.st_size or identity(os.fstat(child))!=identity(opened): raise ValueError()
|
|
274
280
|
finally: os.close(child)
|
|
275
281
|
total+=size
|
|
276
282
|
records.append((name,size,digest.hexdigest()))
|
|
283
|
+
if mode=='hashes': blobs.append(blob.hexdigest())
|
|
277
284
|
else: raise ValueError()
|
|
278
285
|
if identity(os.fstat(fd))!=identity(before): raise ValueError()
|
|
279
286
|
try:
|
|
@@ -289,10 +296,13 @@ try:
|
|
|
289
296
|
fd=child
|
|
290
297
|
walk(fd,'',0)
|
|
291
298
|
finally: os.close(fd)
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
299
|
+
if mode=='hashes':
|
|
300
|
+
print(json.dumps({'files':len(records),'bytes':total,'blobs':sorted(set(blobs))},separators=(',',':')))
|
|
301
|
+
else:
|
|
302
|
+
digest=hashlib.sha256()
|
|
303
|
+
for row in sorted(records,key=lambda row:row[0].encode('utf-8')):
|
|
304
|
+
digest.update((json.dumps(row,ensure_ascii=False,separators=(',',':'))+'\n').encode('utf-8'))
|
|
305
|
+
print(json.dumps({'sha256':digest.hexdigest(),'files':len(records),'bytes':total},separators=(',',':')))
|
|
296
306
|
except Exception:
|
|
297
307
|
sys.stderr.write('input manifest refused\n')
|
|
298
308
|
sys.exit(1)
|
|
@@ -309,6 +319,20 @@ export async function hashExecutorInput(executorArg: Executor, path: string, run
|
|
|
309
319
|
if (!plain(raw) || Object.keys(raw).some(key => !["sha256", "files", "bytes"].includes(key)) || typeof raw.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(raw.sha256) || !Number.isSafeInteger(raw.files) || Number(raw.files)<0 || Number(raw.files)>INPUT_MANIFEST_FILES || !Number.isSafeInteger(raw.bytes) || Number(raw.bytes)<0) throw refuse();
|
|
310
320
|
return {sha256: raw.sha256, files: raw.files as number, bytes: raw.bytes as number};
|
|
311
321
|
}
|
|
322
|
+
export const SCREEN_INPUT_BLOB_BYTES = 1_048_576;
|
|
323
|
+
/** A pre-execution screen reads the same hardened walk, but reports blob ids only: no names, no contents. */
|
|
324
|
+
export async function hashExecutorInputBlobs(executorArg: Executor, path: string, maxFiles: number, runner: ProcessRunner = spawnRunner): Promise<{ files: number; bytes: number; blobs: string[] }> {
|
|
325
|
+
const executor = validateExecutor(executorArg), source = directory(path, "executor input path");
|
|
326
|
+
if (!Number.isSafeInteger(maxFiles) || maxFiles < 1 || maxFiles > INPUT_MANIFEST_FILES) throw new Error(`executor screen: invalid file limit; choose 1..${INPUT_MANIFEST_FILES} files`);
|
|
327
|
+
const refuse = () => new Error(`executor screen: blob list failed; check Python3 and a stable readable regular directory of at most ${maxFiles} files without special files or symlinked ancestors on the executor, or stop screening evaluator inputs through a design change`);
|
|
328
|
+
let result: ProcessResult;
|
|
329
|
+
try {result = await runOnExecutor(executor, "python3", ["-I", "-S", "-c", INPUT_MANIFEST_SCRIPT, source, "hashes", String(maxFiles)], runner, {timeoutMs: INPUT_MANIFEST_TIMEOUT_MS, maxOutputBytes: SCREEN_INPUT_BLOB_BYTES});}
|
|
330
|
+
catch {throw refuse();}
|
|
331
|
+
if (result.exitCode !== 0 || result.timedOut || result.truncated || Buffer.byteLength(result.stdout) > SCREEN_INPUT_BLOB_BYTES) throw refuse();
|
|
332
|
+
let raw: unknown; try {raw = JSON.parse(result.stdout);} catch {throw refuse();}
|
|
333
|
+
if (!plain(raw) || Object.keys(raw).some(key => !["files", "bytes", "blobs"].includes(key)) || !Number.isSafeInteger(raw.files) || Number(raw.files)<0 || Number(raw.files)>maxFiles || !Number.isSafeInteger(raw.bytes) || Number(raw.bytes)<0 || !Array.isArray(raw.blobs) || raw.blobs.length>maxFiles || raw.blobs.some(blob => typeof blob !== "string" || !/^[a-f0-9]{40}$/.test(blob))) throw refuse();
|
|
334
|
+
return {files: raw.files as number, bytes: raw.bytes as number, blobs: raw.blobs as string[]};
|
|
335
|
+
}
|
|
312
336
|
/** Verify every declared input without persisting its host locator or manifest rows. */
|
|
313
337
|
export async function verifyExecutorInputs(executor: Executor, protocol: Protocol, runner: ProcessRunner = spawnRunner): Promise<Record<string, string>> {
|
|
314
338
|
const inputs = validateProtocol(protocol).inputs ?? {}, verified: [string, string][] = [];
|
|
@@ -341,21 +365,82 @@ export async function checkExecutor(dir: string, runner: ProcessRunner = spawnRu
|
|
|
341
365
|
}
|
|
342
366
|
return checkExecutorInputs(executor, protocol, runner);
|
|
343
367
|
}
|
|
344
|
-
|
|
345
|
-
export async function checkExecutorInputs(executor: Executor, protocol: Protocol, runner: ProcessRunner = spawnRunner): Promise<ExecutorCheck> {
|
|
346
|
-
if (Object.keys(protocol.inputs ?? {}).length) await step(executor, "Python3 input manifest runtime", "python3", ["-I", "-S", "-c", "import sys; assert sys.version_info.major == 3"], runner);
|
|
368
|
+
async function dockerVersion(executor: Executor, runner: ProcessRunner): Promise<string> {
|
|
347
369
|
const version = (await step(executor, "Docker server version", "docker", ["version", "--format", "{{.Server.Version}}"], runner)).stdout.trim();
|
|
348
370
|
if (!/^[0-9]+\.[0-9]+(?:\.[0-9]+)?[A-Za-z0-9.+_-]*$/.test(version) || version.length > 128) throw failed(executor, "Docker server version");
|
|
371
|
+
return version;
|
|
372
|
+
}
|
|
373
|
+
async function ensureImage(executor: Executor, image: string, runner: ProcessRunner): Promise<void> {
|
|
374
|
+
let present: ProcessResult;
|
|
375
|
+
try { present = await runOnExecutor(executor, "docker", ["image", "inspect", "--format", "{{.Id}}", image], runner); }
|
|
376
|
+
catch { throw failed(executor, "image availability"); }
|
|
377
|
+
if (present.timedOut || present.truncated) throw failed(executor, "image availability");
|
|
378
|
+
if (present.exitCode !== 0) await step(executor, "image pull", "docker", ["pull", image], runner, { timeoutMs: 300_000 });
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
export interface ExecutorCheckRow { name: string; state: "ok" | "failed" | "skipped"; detail: string }
|
|
382
|
+
export interface ExecutorCheckReport { checks: ExecutorCheckRow[] }
|
|
383
|
+
const PYTHON_RUNTIME = ["-I", "-S", "-c", "import sys; assert sys.version_info.major == 3"];
|
|
384
|
+
|
|
385
|
+
export async function checkExecutorReport(dir: string, runner: ProcessRunner = spawnRunner): Promise<ExecutorCheckReport> {
|
|
386
|
+
const checks: ExecutorCheckRow[] = [];
|
|
387
|
+
const check = async (name: string, operation: () => unknown | Promise<unknown>, prerequisite?: string): Promise<boolean> => {
|
|
388
|
+
if (prerequisite) { checks.push({ name, state: "skipped", detail: prerequisite }); return false; }
|
|
389
|
+
try {
|
|
390
|
+
const detail = await operation();
|
|
391
|
+
checks.push({ name, state: "ok", detail: typeof detail === "string" ? detail : "" });
|
|
392
|
+
return true;
|
|
393
|
+
} catch (error) {
|
|
394
|
+
checks.push({ name, state: "failed", detail: error instanceof Error ? error.message : "Check failed" });
|
|
395
|
+
return false;
|
|
396
|
+
}
|
|
397
|
+
};
|
|
398
|
+
requireExperiment(openStudy(dir).study);
|
|
399
|
+
const config: { executor?: Executor; protocol?: NonNullable<ReturnType<typeof readProtocol>> } = {};
|
|
400
|
+
await check("Executor configuration", () => {
|
|
401
|
+
const executor = readExecutor(dir);
|
|
402
|
+
if (!executor) throw new Error("Configure the executor with ares executor set <dir>");
|
|
403
|
+
config.executor = executor;
|
|
404
|
+
return executor.kind;
|
|
405
|
+
});
|
|
406
|
+
await check("Protocol", () => {
|
|
407
|
+
const protocol = readProtocol(dir);
|
|
408
|
+
if (!protocol) throw new Error("Set the protocol with ares protocol <dir> --file PATH");
|
|
409
|
+
config.protocol = protocol;
|
|
410
|
+
});
|
|
411
|
+
const { executor, protocol } = config;
|
|
412
|
+
const connected = !!executor && (executor.kind !== "ssh" || await check("SSH connection", () => step(executor!, "SSH connection", "true", [], runner, { timeoutMs: 10_000 })));
|
|
413
|
+
const unavailable = connected ? undefined : "Executor unavailable";
|
|
414
|
+
if (protocol && (protocol.v === 1 ? Object.keys(protocol.inputs ?? {}).length > 0 : protocol.candidate.stages.some(stage => Object.keys(stage.inputs).length > 0))) {
|
|
415
|
+
await check("Python 3", () => step(executor!, "Python3 input manifest runtime", "python3", PYTHON_RUNTIME, runner), unavailable);
|
|
416
|
+
}
|
|
417
|
+
const docker = await check("Docker server version", () => dockerVersion(executor!, runner), unavailable);
|
|
418
|
+
for (const [name, flag] of [["UID", "-u"], ["GID", "-g"]] as const) {
|
|
419
|
+
await check(name, async () => {
|
|
420
|
+
const value = (await step(executor!, `host ${name.toLowerCase()}`, "id", [flag], runner)).stdout.trim();
|
|
421
|
+
if (!/^[1-9][0-9]{0,9}$/.test(value)) throw failed(executor!, `non-root host ${name.toLowerCase()}`);
|
|
422
|
+
return value;
|
|
423
|
+
}, unavailable);
|
|
424
|
+
}
|
|
425
|
+
if (protocol) {
|
|
426
|
+
const candidates = protocol.v === 1 ? [protocol.candidate.image] : protocol.candidate.stages.map(stage => stage.image);
|
|
427
|
+
for (const image of new Set([...candidates, protocol.evaluator.image])) {
|
|
428
|
+
await check(`Image ${image}`, () => ensureImage(executor!, image, runner), docker ? undefined : "Docker unavailable");
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return { checks };
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** Check a frozen attempt's configuration rather than mutable study files. */
|
|
435
|
+
export async function checkExecutorInputs(executor: Executor, protocol: Protocol, runner: ProcessRunner = spawnRunner): Promise<ExecutorCheck> {
|
|
436
|
+
if (Object.keys(protocol.inputs ?? {}).length) await step(executor, "Python3 input manifest runtime", "python3", PYTHON_RUNTIME, runner);
|
|
437
|
+
const version = await dockerVersion(executor, runner);
|
|
349
438
|
const uid = (await step(executor, "host uid", "id", ["-u"], runner)).stdout.trim();
|
|
350
439
|
const gid = (await step(executor, "host gid", "id", ["-g"], runner)).stdout.trim();
|
|
351
440
|
if (!/^[1-9][0-9]{0,9}$/.test(uid) || !/^[1-9][0-9]{0,9}$/.test(gid)) throw failed(executor, "non-root host uid:gid");
|
|
352
441
|
const images: ExecutorCheck["images"] = [];
|
|
353
442
|
for (const image of new Set([protocol.candidate.image, protocol.evaluator.image])) {
|
|
354
|
-
|
|
355
|
-
try { present = await runOnExecutor(executor, "docker", ["image", "inspect", "--format", "{{.Id}}", image], runner); }
|
|
356
|
-
catch { throw failed(executor, "image availability"); }
|
|
357
|
-
if (present.timedOut || present.truncated) throw failed(executor, "image availability");
|
|
358
|
-
if (present.exitCode !== 0) await step(executor, "image pull", "docker", ["pull", image], runner, { timeoutMs: 300_000 });
|
|
443
|
+
await ensureImage(executor, image, runner);
|
|
359
444
|
images.push({ image, available: true });
|
|
360
445
|
}
|
|
361
446
|
return { ...(Object.keys(protocol.inputs ?? {}).length ? { inputRuntime: "python3" as const } : {}), executor, serverVersion: version, user: `${uid}:${gid}`, images, pull: "missing" };
|
package/src/exp/final.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { readDesign, readProtocol, type ProtocolDefinition as Protocol } from ".
|
|
|
5
5
|
import { listAttempts, type Attempt, type AttemptStatus } from "./attempts.ts";
|
|
6
6
|
import { ablateResultPath, ABLATE_BYTES, foldAblations, readClosedAblate } from "./ablate.ts";
|
|
7
7
|
import { INVESTIGATE_BYTES, investigateResultPath, metricValue, pairSamples, readClosedInvestigation, type PairedSamples, type Sample } from "./investigate.ts";
|
|
8
|
-
import { readSelection } from "./selection.ts";
|
|
8
|
+
import { evaluateSelectionConstraints, readSelection, type ConstraintResult } from "./selection.ts";
|
|
9
9
|
|
|
10
10
|
export interface FinalSeeds { v: 1; seeds: number[] }
|
|
11
11
|
export const FINAL_SEEDS_BYTES = 65_536;
|
|
@@ -115,7 +115,7 @@ export function authorizeFinalAttempt(dir: string, commit: string, seed: number)
|
|
|
115
115
|
return { binding: input.binding, auto: approvals.length > 0, winner: input.winner };
|
|
116
116
|
}
|
|
117
117
|
interface FinalAttempt { id: string; commit: string; seed: number; status: AttemptStatus; decisive: boolean; reason?: string; retryOf?: string }
|
|
118
|
-
export interface FinalResult {
|
|
118
|
+
export interface FinalResult extends Omit<ConstraintResult, "reason"> {
|
|
119
119
|
v: 1; status: "qualified" | "not_qualified"; reason?: string; winner: string; baseline: string; seeds: number[];
|
|
120
120
|
pairs: PairedSamples["pairs"]; mean: number | null; baselineMean: number | null; delta: number | null;
|
|
121
121
|
decisive: FinalAttempt[]; attempts: FinalAttempt[]; investigateSha256: string; ablateSha256?: string; sealBinding: string; inputsSha256: string;
|
|
@@ -154,11 +154,20 @@ function calculateFinal(input: ReturnType<typeof requireFinalInputs>): FinalResu
|
|
|
154
154
|
return [{ seed, attempt: a.id, value: metricValue(a, input.investigate.result.metric) }];
|
|
155
155
|
});
|
|
156
156
|
const paired = pairSamples(samples(input.winner), samples(input.baseline), input.investigate.result.metric.direction, input.winner);
|
|
157
|
+
let details: Omit<ConstraintResult, "reason"> = {};
|
|
157
158
|
if (!reason) {
|
|
158
159
|
if (paired.delta === null || paired.delta <= 0 || paired.delta < input.rule.minDelta) reason = "below-margin";
|
|
160
|
+
else if (input.rule.v === 2 && (input.rule.guards?.length || input.rule.cost)) {
|
|
161
|
+
const evaluation = evaluateSelectionConstraints(input.rule, input.design.protocol, paired.pairedSeeds.map(seed => ({
|
|
162
|
+
attempt: chosen.get(`${input.winner}:${seed}`)!, baseline: chosen.get(`${input.baseline}:${seed}`)!,
|
|
163
|
+
})), paired.delta);
|
|
164
|
+
const { reason: rejected, ...measurements } = evaluation;
|
|
165
|
+
reason = rejected;
|
|
166
|
+
details = measurements;
|
|
167
|
+
}
|
|
159
168
|
}
|
|
160
169
|
const result: FinalResult = { v: 1, status: reason ? "not_qualified" : "qualified", ...(reason ? { reason } : {}), winner: input.winner, baseline: input.baseline, seeds: input.final.seeds, pairs: paired.pairs, mean: paired.mean, baselineMean: paired.referenceMean, delta: paired.delta, decisive, attempts: rows, investigateSha256: input.investigate.sha256, ...(input.ablate ? { ablateSha256: input.ablate.sha256 } : {}), sealBinding: input.design.binding,
|
|
161
|
-
inputsSha256: sha256(canonical({ binding: input.binding, attempts: ordered.map(a => ({ record: sha256(canonical(a)), start: starts.get(a.id)?.index ?? null })) })) };
|
|
170
|
+
inputsSha256: sha256(canonical({ binding: input.binding, attempts: ordered.map(a => ({ record: sha256(canonical(a)), start: starts.get(a.id)?.index ?? null })) })), ...details };
|
|
162
171
|
const text = JSON.stringify(result, null, 2) + "\n"; assertWritable(text, FINAL_RESULT_BYTES, "final result; archive the study and start a new bounded run");
|
|
163
172
|
return result;
|
|
164
173
|
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { calculate, inputs, type CommitResult } from "./investigate.ts";
|
|
2
|
+
import { foldIdeas, readCategories, type Expectation, type Idea } from "./ideas.ts";
|
|
3
|
+
import { observedMetric, sampleMean } from "./selection.ts";
|
|
4
|
+
import type { Attempt, AttemptStatus } from "./attempts.ts";
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_WINDOW = 5, MAX_WINDOW = 1000;
|
|
7
|
+
export type Outcome = "hit" | "miss" | "unmeasured";
|
|
8
|
+
export interface ReportCommit { commit: string; delta: number | null; pairedSeeds: number; measured: boolean; eligible: boolean; reason: string }
|
|
9
|
+
export interface ReportPrediction { metric: string; expect: Expectation; minDelta?: number; delta: number | null; outcome?: Outcome }
|
|
10
|
+
export interface ReportIdea {
|
|
11
|
+
id: string; category?: string; bundle: number; confounded: boolean; state: Idea["state"]; commits: ReportCommit[];
|
|
12
|
+
attempts: Record<AttemptStatus, number>; timing: "prospective" | "post-hoc"; measuredCommit: string | null; primaryDelta: number | null;
|
|
13
|
+
predictions: ReportPrediction[]; unpredictedRegressions: string[];
|
|
14
|
+
}
|
|
15
|
+
export interface ReportCategory { name: string; ideas: number; measured: number; hits: number; bestRecentDelta: number | null; noRecentGain: boolean }
|
|
16
|
+
export interface IdeaReport {
|
|
17
|
+
v: 1; advisory: true; run: string; metric: { name: string; unit: string; direction: "max" | "min" }; baseline: string; minSeeds: number; minDelta: number;
|
|
18
|
+
window: number; inputsSha256: string; ideas: ReportIdea[]; categories: ReportCategory[]; confounded: string[];
|
|
19
|
+
search: { measured: number; bestDelta: number | null; stalled: boolean; untried: string[] };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function bad(reason: string): never { throw new Error(`idea report: ${reason}`); }
|
|
23
|
+
const best = (values: (number | null)[]) => values.reduce<number | null>((top, v) => v === null ? top : top === null || v > top ? v : top, null);
|
|
24
|
+
|
|
25
|
+
/** Direction-adjusted paired mean delta for any declared metric over the investigation's own pairs. */
|
|
26
|
+
function metricDelta(row: CommitResult, metric: { name: string; unit: string; direction: "max" | "min" }, byId: Map<string, Attempt>): number | null {
|
|
27
|
+
if (!row.pairs.length) return null;
|
|
28
|
+
const values: number[] = [], reference: number[] = [];
|
|
29
|
+
for (const pair of row.pairs) {
|
|
30
|
+
const a = byId.get(pair.attempt), b = byId.get(pair.baselineAttempt);
|
|
31
|
+
const x = a && observedMetric(a, metric), y = b && observedMetric(b, metric);
|
|
32
|
+
if (x === undefined || y === undefined) return null;
|
|
33
|
+
values.push(x); reference.push(y);
|
|
34
|
+
}
|
|
35
|
+
const mean = sampleMean(values)!, ref = sampleMean(reference)!, delta = metric.direction === "max" ? mean - ref : ref - mean;
|
|
36
|
+
return Number.isFinite(delta) ? delta : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Read-only, advisory fold over the ledger and the investigation pairing; it writes nothing and gates nothing. */
|
|
40
|
+
export function ideaReport(dirArg: string, options: { run?: string; window?: number } = {}): IdeaReport {
|
|
41
|
+
const window = options.window ?? DEFAULT_WINDOW;
|
|
42
|
+
if (!Number.isSafeInteger(window) || window < 1 || window > MAX_WINDOW) bad(`window: integer in 1..${MAX_WINDOW} required; pass --window N`);
|
|
43
|
+
const input = inputs(dirArg), { rule, protocol, events, attempts, dir } = input;
|
|
44
|
+
if (options.run !== undefined && options.run !== rule.run) bad(`run ${options.run} is not the selection run ${rule.run}; pass --run ${rule.run} or set a selection for that run`);
|
|
45
|
+
const result = calculate(input), primary = result.metric, byId = new Map(attempts.map(a => [a.id, a]));
|
|
46
|
+
const rows = new Map([result.baseline, ...result.candidates].map(row => [row.commit, row]));
|
|
47
|
+
const baselineReady = result.baseline.eligible;
|
|
48
|
+
const firstStart = new Map<string, number>(), added = new Map<string, number>();
|
|
49
|
+
events.forEach((event, index) => {
|
|
50
|
+
if (event.type === "attempt.started" && typeof event.data.commit === "string" && !firstStart.has(event.data.commit)) firstStart.set(event.data.commit, index);
|
|
51
|
+
if (event.type === "idea.added" && event.data.idea && typeof (event.data.idea as { id?: unknown }).id === "string") added.set((event.data.idea as { id: string }).id, index);
|
|
52
|
+
});
|
|
53
|
+
const ideas = foldIdeas(events).map((idea): ReportIdea => {
|
|
54
|
+
const commits = idea.commits.map((commit): ReportCommit => {
|
|
55
|
+
const row = rows.get(commit), pairs = row?.pairs.length ?? 0, measured = !!row && commit !== rule.baseline.commit && baselineReady && pairs >= rule.minSeeds && row.delta !== null;
|
|
56
|
+
return { commit, delta: row && commit !== rule.baseline.commit ? row.delta : null, pairedSeeds: pairs, measured, eligible: !!row?.eligible && commit !== rule.baseline.commit, reason: row ? row.reason : "no-attempts" };
|
|
57
|
+
});
|
|
58
|
+
const totals = { running: 0, succeeded: 0, failed: 0, cancelled: 0, unknown: 0 };
|
|
59
|
+
for (const commit of idea.commits) { const row = rows.get(commit); if (row) for (const status of Object.keys(totals) as AttemptStatus[]) totals[status] += row.attempts[status].length; }
|
|
60
|
+
const starts = idea.commits.map(c => firstStart.get(c)).filter((i): i is number => i !== undefined);
|
|
61
|
+
const timing = starts.length && Math.min(...starts) < added.get(idea.id)! ? "post-hoc" : "prospective";
|
|
62
|
+
const latest = [...commits].reverse().find(c => c.measured), row = latest ? rows.get(latest.commit)! : undefined;
|
|
63
|
+
const deltaFor = (name: string): number | null => {
|
|
64
|
+
if (!row) return null;
|
|
65
|
+
const metric = protocol.metrics.find(m => m.name === name);
|
|
66
|
+
return !metric ? null : name === primary.name ? row.delta : metricDelta(row, metric, byId);
|
|
67
|
+
};
|
|
68
|
+
const predictions = (idea.predicts ?? []).map((p): ReportPrediction => {
|
|
69
|
+
const delta = deltaFor(p.metric), threshold = p.metric === primary.name && p.expect === "no-change" ? rule.minDelta : p.minDelta ?? 0;
|
|
70
|
+
const hit = delta === null ? undefined : p.expect === "improve" ? delta > 0 && delta >= threshold : p.expect === "regress" ? delta < 0 && -delta >= (p.minDelta ?? 0) : Math.abs(delta) < threshold;
|
|
71
|
+
const outcome: Outcome | undefined = timing === "post-hoc" ? undefined : hit === undefined ? "unmeasured" : hit ? "hit" : "miss";
|
|
72
|
+
return { metric: p.metric, expect: p.expect, ...(p.minDelta !== undefined ? { minDelta: p.minDelta } : {}), delta, ...(outcome ? { outcome } : {}) };
|
|
73
|
+
});
|
|
74
|
+
const regressAllowed = new Set((idea.predicts ?? []).filter(p => p.expect === "regress").map(p => p.metric));
|
|
75
|
+
const unpredictedRegressions = row ? protocol.metrics.filter(m => !regressAllowed.has(m.name)).filter(m => { const d = deltaFor(m.name); return d !== null && d < 0; }).map(m => m.name) : [];
|
|
76
|
+
const bundle = idea.bundle ?? 1;
|
|
77
|
+
return { id: idea.id, ...(idea.category !== undefined ? { category: idea.category } : {}), bundle, confounded: bundle > 1, state: idea.state, commits, attempts: totals, timing,
|
|
78
|
+
measuredCommit: latest?.commit ?? null, primaryDelta: row ? row.delta : null, predictions, unpredictedRegressions };
|
|
79
|
+
});
|
|
80
|
+
const clean = ideas.filter(i => !i.confounded), measured = clean.filter(i => i.measuredCommit !== null);
|
|
81
|
+
const names = [...new Set(clean.flatMap(i => i.category === undefined ? [] : [i.category]))].sort();
|
|
82
|
+
const categories = names.map((name): ReportCategory => {
|
|
83
|
+
const members = clean.filter(i => i.category === name), done = members.filter(i => i.measuredCommit !== null);
|
|
84
|
+
const recent = best(done.slice(-window).map(i => i.primaryDelta));
|
|
85
|
+
return { name, ideas: members.length, measured: done.length, hits: members.reduce((n, i) => n + i.predictions.filter(p => p.outcome === "hit").length, 0),
|
|
86
|
+
bestRecentDelta: recent, noRecentGain: done.length > 0 && recent !== null && recent <= 0 };
|
|
87
|
+
});
|
|
88
|
+
const eligibleDelta = (i: ReportIdea) => i.commits.find(c => c.commit === i.measuredCommit)?.eligible ? i.primaryDelta : null;
|
|
89
|
+
const before = best(measured.slice(0, -window).map(eligibleDelta)), last = best(measured.slice(-window).map(eligibleDelta));
|
|
90
|
+
const stalled = measured.length >= window && (last === null || last <= Math.max(before ?? 0, 0));
|
|
91
|
+
const declared = readCategories(dir), tried = new Set(measured.map(i => i.category));
|
|
92
|
+
return {
|
|
93
|
+
v: 1, advisory: true, run: rule.run, metric: primary, baseline: rule.baseline.commit, minSeeds: rule.minSeeds, minDelta: rule.minDelta, window,
|
|
94
|
+
inputsSha256: result.inputsSha256, ideas, categories, confounded: ideas.filter(i => i.confounded).map(i => i.id),
|
|
95
|
+
search: { measured: measured.length, bestDelta: best(measured.map(eligibleDelta)), stalled, untried: (declared ?? []).filter(c => !tried.has(c)) },
|
|
96
|
+
};
|
|
97
|
+
}
|
package/src/exp/ideas.ts
CHANGED
|
@@ -1,10 +1,18 @@
|
|
|
1
|
-
import { boundedText, commit, onlyKeys, openStudy, plain, readLedger, requireExperiment, type Actor, type LedgerEvent } from "../study.ts";
|
|
1
|
+
import { boundedText, commit, onlyKeys, openStudy, plain, readLedger, readTextBounded, requireExperiment, sha256, type Actor, type LedgerEvent } from "../study.ts";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
2
4
|
import { listAttempts } from "./attempts.ts";
|
|
5
|
+
import { readProtocol } from "./protocol.ts";
|
|
6
|
+
import { readSelection } from "./selection.ts";
|
|
3
7
|
|
|
4
8
|
export const MAX_IDEAS = 1000, MAX_DECISION_ATTEMPTS = 200;
|
|
5
|
-
export
|
|
9
|
+
export const MAX_PREDICTIONS = 4, MAX_BUNDLE = 16, MAX_CATEGORIES = 32, CATEGORIES_BYTES = 8192;
|
|
10
|
+
export type Expectation = "improve" | "no-change" | "regress";
|
|
11
|
+
export interface Prediction { metric: string; expect: Expectation; minDelta?: number }
|
|
12
|
+
export interface IdeaPlanning { category?: string; bundle?: number; predicts?: Prediction[] }
|
|
13
|
+
export interface IdeaInput extends IdeaPlanning { id: string; title: string; hypothesis: string; parent?: string; commit?: string }
|
|
6
14
|
export interface IdeaDecision { decision: "refine" | "pivot"; reason: string; attempts: string[]; commit?: string; cause?: string; retryWhen?: string }
|
|
7
|
-
export interface Idea { id: string; title: string; hypothesis: string; parent?: string; commits: string[]; state: "open" | "pivoted"; decisions: IdeaDecision[] }
|
|
15
|
+
export interface Idea extends IdeaPlanning { id: string; title: string; hypothesis: string; parent?: string; commits: string[]; state: "open" | "pivoted"; decisions: IdeaDecision[] }
|
|
8
16
|
const recovery = "; correct the idea input and retry ares idea add or ares idea decide";
|
|
9
17
|
function bad(reason: string): never { throw new Error(`idea: ${reason}${recovery}`); }
|
|
10
18
|
function name(raw: unknown, field: string): string {
|
|
@@ -15,11 +23,84 @@ function commitId(raw: unknown): string {
|
|
|
15
23
|
if (typeof raw !== "string" || !/^[a-fA-F0-9]{40}$/.test(raw)) bad("commit: full 40-hex SHA required");
|
|
16
24
|
return raw.toLowerCase();
|
|
17
25
|
}
|
|
26
|
+
function prediction(raw: unknown, strict: boolean): Prediction {
|
|
27
|
+
if (!plain(raw)) bad("predicts: objects with metric and expect required");
|
|
28
|
+
if (strict) onlyKeys(raw, ["metric", "expect", "minDelta"], "idea prediction");
|
|
29
|
+
const metric = boundedText(raw.metric, "idea prediction metric", 128);
|
|
30
|
+
if (raw.expect !== "improve" && raw.expect !== "no-change" && raw.expect !== "regress") bad("predicts.expect: use improve, no-change or regress");
|
|
31
|
+
if (raw.minDelta !== undefined && (typeof raw.minDelta !== "number" || !Number.isFinite(raw.minDelta) || raw.minDelta < 0)) bad("predicts.minDelta: finite number >= 0 required in the metric's unit");
|
|
32
|
+
return { metric, expect: raw.expect, ...(raw.minDelta !== undefined ? { minDelta: raw.minDelta as number } : {}) };
|
|
33
|
+
}
|
|
34
|
+
/** Optional planning fields; absent fields are omitted so older ideas fold to identical objects. */
|
|
35
|
+
function planning(raw: Record<string, unknown>, strict: boolean): IdeaPlanning {
|
|
36
|
+
const out: IdeaPlanning = {};
|
|
37
|
+
if (raw.category !== undefined) out.category = name(raw.category, "category");
|
|
38
|
+
if (raw.bundle !== undefined) {
|
|
39
|
+
if (!Number.isSafeInteger(raw.bundle) || (raw.bundle as number) < 1 || (raw.bundle as number) > MAX_BUNDLE) bad(`bundle: integer in 1..${MAX_BUNDLE} required (independent changes in the commit)`);
|
|
40
|
+
out.bundle = raw.bundle as number;
|
|
41
|
+
}
|
|
42
|
+
if (raw.predicts !== undefined) {
|
|
43
|
+
if (!Array.isArray(raw.predicts) || !raw.predicts.length || raw.predicts.length > MAX_PREDICTIONS) bad(`predicts: 1..${MAX_PREDICTIONS} predictions required`);
|
|
44
|
+
const predicts = raw.predicts.map(p => prediction(p, strict));
|
|
45
|
+
if (new Set(predicts.map(p => p.metric)).size !== predicts.length) bad("predicts: one prediction per metric");
|
|
46
|
+
out.predicts = predicts;
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
18
50
|
function validateIdea(raw: unknown, strict: boolean): IdeaInput {
|
|
19
51
|
if (!plain(raw)) bad("JSON object required");
|
|
20
|
-
if (strict) onlyKeys(raw, ["id", "title", "hypothesis", "parent", "commit"], "idea");
|
|
52
|
+
if (strict) onlyKeys(raw, ["id", "title", "hypothesis", "parent", "commit", "category", "bundle", "predicts"], "idea");
|
|
21
53
|
return { id: name(raw.id, "id"), title: boundedText(raw.title, "idea.title", 500), hypothesis: boundedText(raw.hypothesis, "idea.hypothesis", 4000),
|
|
22
|
-
...(raw.parent !== undefined ? { parent: name(raw.parent, "parent") } : {}), ...(raw.commit !== undefined ? { commit: commitId(raw.commit) } : {}) };
|
|
54
|
+
...(raw.parent !== undefined ? { parent: name(raw.parent, "parent") } : {}), ...(raw.commit !== undefined ? { commit: commitId(raw.commit) } : {}), ...planning(raw, strict) };
|
|
55
|
+
}
|
|
56
|
+
export function categoriesPath(dir: string): string { return join(dir, "design", "idea-categories.json"); }
|
|
57
|
+
function validateCategories(raw: unknown): { v: 1; categories: string[] } {
|
|
58
|
+
if (!plain(raw)) bad("categories: JSON object {v:1,categories:[...]} required");
|
|
59
|
+
onlyKeys(raw, ["v", "categories"], "idea categories");
|
|
60
|
+
if (raw.v !== 1) bad("categories.v: 1 required");
|
|
61
|
+
if (!Array.isArray(raw.categories) || !raw.categories.length || raw.categories.length > MAX_CATEGORIES) bad(`categories: 1..${MAX_CATEGORIES} names required`);
|
|
62
|
+
const categories = raw.categories.map(c => name(c, "category"));
|
|
63
|
+
if (new Set(categories).size !== categories.length) bad("categories: duplicate name; list each category once");
|
|
64
|
+
return { v: 1, categories };
|
|
65
|
+
}
|
|
66
|
+
/** The study-local vocabulary, or undefined when none is declared. It is a planning aid outside the design seal. */
|
|
67
|
+
export function readCategories(dir: string): string[] | undefined {
|
|
68
|
+
const file = categoriesPath(dir);
|
|
69
|
+
if (!existsSync(file)) return undefined;
|
|
70
|
+
let text: string;
|
|
71
|
+
try { text = readTextBounded(file, CATEGORIES_BYTES); }
|
|
72
|
+
catch { bad(`design/idea-categories.json: unreadable, non-regular, invalid UTF-8 or larger than ${CATEGORIES_BYTES} bytes; restore a valid file within that bound`); }
|
|
73
|
+
let raw: unknown;
|
|
74
|
+
try { raw = JSON.parse(text); } catch { bad("design/idea-categories.json: invalid JSON; restore the last valid vocabulary"); }
|
|
75
|
+
return validateCategories(raw).categories;
|
|
76
|
+
}
|
|
77
|
+
/** Caller holds the study lock; identical bytes record nothing. */
|
|
78
|
+
export function setCategories(dir: string, raw: unknown, actor: Actor): { categories: string[]; sha256: string; changed: boolean } {
|
|
79
|
+
return safe(() => {
|
|
80
|
+
requireExperiment(openStudy(dir).study);
|
|
81
|
+
const value = validateCategories(raw), text = JSON.stringify(value, null, 2) + "\n", hash = sha256(text), file = categoriesPath(dir);
|
|
82
|
+
let previous: string | undefined;
|
|
83
|
+
// A valid new vocabulary may replace an unreadable or invalid one.
|
|
84
|
+
if (existsSync(file)) { try { previous = readTextBounded(file, CATEGORIES_BYTES); } catch { previous = undefined; } }
|
|
85
|
+
const changed = previous !== text;
|
|
86
|
+
if (changed) commit(dir, [[file, text, CATEGORIES_BYTES]], [{ actor, type: "idea.categories.set", data: { sha256: hash, count: value.categories.length } }]);
|
|
87
|
+
return { categories: value.categories, sha256: hash, changed };
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
function checkPlanning(dir: string, input: IdeaInput): void {
|
|
91
|
+
if (input.category !== undefined) {
|
|
92
|
+
const declared = readCategories(dir);
|
|
93
|
+
if (declared && !declared.includes(input.category)) bad(`category ${input.category} is not declared; use one of ${declared.join(", ")}`);
|
|
94
|
+
}
|
|
95
|
+
if (input.predicts) {
|
|
96
|
+
const protocol = readProtocol(dir);
|
|
97
|
+
if (!protocol) bad("predicts: protocol missing; run ares protocol before predicting metrics, or omit predicts");
|
|
98
|
+
const names = protocol.metrics.map(m => m.name);
|
|
99
|
+
for (const p of input.predicts) if (!names.includes(p.metric)) bad(`predicts.metric ${p.metric} is not declared; use one of ${names.join(", ")}`);
|
|
100
|
+
// Only the primary metric has a selection margin; elsewhere no-change needs its own tolerance or it can never hit.
|
|
101
|
+
const primary = readSelection(dir, protocol)?.metric;
|
|
102
|
+
for (const p of input.predicts) if (p.expect === "no-change" && p.minDelta === undefined && p.metric !== primary) bad(`predicts ${p.metric}: no-change on a non-primary metric needs minDelta; add minDelta in that metric's unit`);
|
|
103
|
+
}
|
|
23
104
|
}
|
|
24
105
|
function pivotContext(raw: Record<string, unknown>, strict: boolean): Pick<IdeaDecision, "cause" | "retryWhen"> {
|
|
25
106
|
if (strict && raw.decision !== "pivot" && (raw.cause !== undefined || raw.retryWhen !== undefined)) bad("cause and retryWhen are pivot-only; omit --cause and --retry-when for refine");
|
|
@@ -66,7 +147,9 @@ export function foldIdeas(events: LedgerEvent[]): Idea[] {
|
|
|
66
147
|
if (ideas.size >= MAX_IDEAS) bad(`limit ${MAX_IDEAS} reached; start a new study for more ideas`);
|
|
67
148
|
if (input.parent !== undefined && !ideas.has(input.parent)) bad(`parent ${input.parent} does not exist; add its parent idea first`);
|
|
68
149
|
claim(ideas.values(), input.id, input.commit);
|
|
69
|
-
|
|
150
|
+
const { category, bundle, predicts } = input;
|
|
151
|
+
ideas.set(input.id, { id: input.id, title: input.title, hypothesis: input.hypothesis, ...(input.parent !== undefined ? { parent: input.parent } : {}), commits: input.commit ? [input.commit] : [], state: "open", decisions: [],
|
|
152
|
+
...(category !== undefined ? { category } : {}), ...(bundle !== undefined ? { bundle } : {}), ...(predicts !== undefined ? { predicts } : {}) });
|
|
70
153
|
} else if (event.type === "idea.decided") {
|
|
71
154
|
const id = name(event.data.id, "id"), input = validateDecision(event.data, false), target = ideas.get(id);
|
|
72
155
|
if (!target) bad(`unknown id ${id}; add the idea before deciding`);
|
|
@@ -90,6 +173,7 @@ export function addIdea(dir: string, raw: unknown, actor: Actor): Idea {
|
|
|
90
173
|
if (ideas.length >= MAX_IDEAS) bad(`limit ${MAX_IDEAS} reached; start a new study for more ideas`);
|
|
91
174
|
if (input.parent !== undefined && !ideas.some(i => i.id === input.parent)) bad(`parent ${input.parent} does not exist; add its parent idea first`);
|
|
92
175
|
claim(ideas, input.id, input.commit);
|
|
176
|
+
checkPlanning(dir, input);
|
|
93
177
|
const added = commit(dir, [], [{ actor, type: "idea.added", data: { idea: input } }]);
|
|
94
178
|
return foldIdeas([...events, ...added]).find(i => i.id === input.id)!;
|
|
95
179
|
});
|