@staix/agent-research 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +70 -0
- package/README.md +93 -22
- package/package.json +4 -1
- package/src/cli-output.ts +446 -0
- package/src/cli.ts +208 -66
- package/src/commands-table.ts +213 -93
- package/src/commands.ts +86 -17
- package/src/exp/artifacts.ts +20 -2
- package/src/exp/attempts.ts +26 -9
- package/src/exp/calibrate.ts +125 -0
- package/src/exp/executor.ts +130 -21
- package/src/exp/final.ts +12 -3
- package/src/exp/idea-report.ts +97 -0
- package/src/exp/ideas.ts +90 -6
- package/src/exp/investigate.ts +25 -22
- package/src/exp/metrics.ts +3 -5
- package/src/exp/protocol.ts +28 -3
- package/src/exp/reuse-admission.ts +3 -1
- package/src/exp/reuse-runtime.ts +5 -1
- package/src/exp/screen.ts +83 -0
- package/src/exp/selection.ts +110 -4
- package/src/exp/snapshot.ts +28 -8
- package/src/exp/stages.ts +3 -1
- package/src/harness/transitions.ts +37 -5
- package/src/manifest.ts +13 -5
- package/src/mcp-tools.ts +67 -14
- package/src/memory/archive.ts +8 -3
- package/src/paper/build.ts +39 -25
- package/src/paper/check.ts +46 -15
- package/src/paper/dependencies.ts +47 -0
- package/src/paper/document.ts +19 -0
- package/src/paper/figures.ts +152 -0
- package/src/paper/hygiene.ts +16 -5
- package/src/paper/plan.ts +71 -29
- package/src/paper/point-evidence.ts +27 -12
- package/src/paper/render.ts +113 -0
- package/src/paper/renderer.ts +128 -0
- package/src/paper/review.ts +41 -5
- package/src/plan/definition.ts +6 -1
- package/src/playbook.ts +21 -11
- package/src/provenance.ts +4 -3
- package/src/study-export.ts +7 -4
- package/src/study.ts +9 -4
- package/src/ui/plugin.ts +3 -1
package/src/exp/executor.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { existsSync } from "node:fs";
|
|
3
3
|
import { join, posix } from "node:path";
|
|
4
|
-
import { commit, openStudy, plain, readJsonFile, requireExperiment, type Actor } from "../study.ts";
|
|
4
|
+
import { commit, openStudy, plain, readJsonFile, requireExperiment, sha256, type Actor } from "../study.ts";
|
|
5
5
|
import { readProtocol, canonicalExecutorPath, validateProtocol, type Protocol } from "./protocol.ts";
|
|
6
6
|
|
|
7
7
|
export interface ExecutorGpu { devices: (number | string)[]; minFreeMemoryMb: number; maxLoadRatio: number }
|
|
@@ -14,6 +14,8 @@ export interface ProcessRequest {
|
|
|
14
14
|
export interface ProcessResult { exitCode: number; stdout: string; stderr: string; timedOut?: boolean; truncated?: boolean }
|
|
15
15
|
export type ProcessRunner = (request: ProcessRequest) => Promise<ProcessResult>;
|
|
16
16
|
export const EXECUTOR_BYTES = 8192, PROCESS_OUTPUT_BYTES = 65_536;
|
|
17
|
+
// Domain tag keeps a container-name digest from ever being confused with another ares hash.
|
|
18
|
+
const CONTAINER_NAME_DOMAIN = "ares-container-name-v1";
|
|
17
19
|
|
|
18
20
|
/** Opt-in context for native CLI attribution and config discovery; no API credentials. */
|
|
19
21
|
export const PROCESS_CONTEXT_ENV_KEYS = ["AGENTHUB_PEER_ID", "CLAUDECODE", "CLAUDE_CODE_SESSION_ID", "CODEX_THREAD_ID", "PI_SESSION_ID",
|
|
@@ -142,6 +144,14 @@ export function setExecutor(dir: string, raw: unknown, actor: Actor): Executor {
|
|
|
142
144
|
return executor;
|
|
143
145
|
}
|
|
144
146
|
|
|
147
|
+
/**
|
|
148
|
+
* The one tar-create rule for archives ares reads or extracts elsewhere: content only. macOS bsdtar otherwise adds
|
|
149
|
+
* extended-attribute PAX records and AppleDouble `._*` members, which a Linux GNU tar extracts as regular files.
|
|
150
|
+
* COPYFILE_DISABLE suppresses AppleDouble members and --no-xattrs the attribute records. Used as a `sh -c` prefix
|
|
151
|
+
* because executor children get a minimal environment that would drop COPYFILE_DISABLE.
|
|
152
|
+
* ponytail: requires GNU tar >= 1.27 or bsdtar with --no-xattrs; unsupported tar (e.g. BusyBox) fails closed.
|
|
153
|
+
*/
|
|
154
|
+
export const PORTABLE_TAR_CREATE = "COPYFILE_DISABLE=1 tar --no-xattrs";
|
|
145
155
|
/** SSH concatenates its remote command argv into a shell command, so quote every unsafe byte. */
|
|
146
156
|
export function shellQuote(value: string): string {
|
|
147
157
|
return /^[A-Za-z0-9_./:@=+-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
|
|
@@ -221,7 +231,10 @@ export const INPUT_MANIFEST_FILES = 100_000, INPUT_MANIFEST_TIMEOUT_MS = 300_000
|
|
|
221
231
|
// ponytail: ceiling 100,000 files/directories, depth 64 and 5 minutes; bytes stream in 1 MiB chunks, never into the study.
|
|
222
232
|
export const INPUT_MANIFEST_SCRIPT = String.raw`import os,sys,stat,hashlib,json
|
|
223
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
|
|
224
236
|
records=[]
|
|
237
|
+
blobs=[]
|
|
225
238
|
entries=0
|
|
226
239
|
directories=0
|
|
227
240
|
total=0
|
|
@@ -247,12 +260,14 @@ def walk(fd,prefix,depth):
|
|
|
247
260
|
walk(child,name,depth+1)
|
|
248
261
|
finally: os.close(child)
|
|
249
262
|
elif stat.S_ISREG(info.st_mode):
|
|
250
|
-
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()
|
|
251
264
|
child=os.open(item.name,os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK,dir_fd=fd)
|
|
252
265
|
try:
|
|
253
266
|
opened=os.fstat(child)
|
|
254
267
|
if not stat.S_ISREG(opened.st_mode) or identity(opened)!=identity(info): raise ValueError()
|
|
255
268
|
digest=hashlib.sha256()
|
|
269
|
+
blob=hashlib.sha1()
|
|
270
|
+
if mode=='hashes': blob.update(('blob %d\0' % info.st_size).encode('utf-8'))
|
|
256
271
|
size=0
|
|
257
272
|
while True:
|
|
258
273
|
chunk=os.read(child,1048576)
|
|
@@ -260,10 +275,12 @@ def walk(fd,prefix,depth):
|
|
|
260
275
|
size+=len(chunk)
|
|
261
276
|
if size>info.st_size: raise ValueError()
|
|
262
277
|
digest.update(chunk)
|
|
278
|
+
if mode=='hashes': blob.update(chunk)
|
|
263
279
|
if size!=info.st_size or identity(os.fstat(child))!=identity(opened): raise ValueError()
|
|
264
280
|
finally: os.close(child)
|
|
265
281
|
total+=size
|
|
266
282
|
records.append((name,size,digest.hexdigest()))
|
|
283
|
+
if mode=='hashes': blobs.append(blob.hexdigest())
|
|
267
284
|
else: raise ValueError()
|
|
268
285
|
if identity(os.fstat(fd))!=identity(before): raise ValueError()
|
|
269
286
|
try:
|
|
@@ -279,10 +296,13 @@ try:
|
|
|
279
296
|
fd=child
|
|
280
297
|
walk(fd,'',0)
|
|
281
298
|
finally: os.close(fd)
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
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=(',',':')))
|
|
286
306
|
except Exception:
|
|
287
307
|
sys.stderr.write('input manifest refused\n')
|
|
288
308
|
sys.exit(1)
|
|
@@ -299,6 +319,20 @@ export async function hashExecutorInput(executorArg: Executor, path: string, run
|
|
|
299
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();
|
|
300
320
|
return {sha256: raw.sha256, files: raw.files as number, bytes: raw.bytes as number};
|
|
301
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
|
+
}
|
|
302
336
|
/** Verify every declared input without persisting its host locator or manifest rows. */
|
|
303
337
|
export async function verifyExecutorInputs(executor: Executor, protocol: Protocol, runner: ProcessRunner = spawnRunner): Promise<Record<string, string>> {
|
|
304
338
|
const inputs = validateProtocol(protocol).inputs ?? {}, verified: [string, string][] = [];
|
|
@@ -331,21 +365,82 @@ export async function checkExecutor(dir: string, runner: ProcessRunner = spawnRu
|
|
|
331
365
|
}
|
|
332
366
|
return checkExecutorInputs(executor, protocol, runner);
|
|
333
367
|
}
|
|
334
|
-
|
|
335
|
-
export async function checkExecutorInputs(executor: Executor, protocol: Protocol, runner: ProcessRunner = spawnRunner): Promise<ExecutorCheck> {
|
|
336
|
-
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> {
|
|
337
369
|
const version = (await step(executor, "Docker server version", "docker", ["version", "--format", "{{.Server.Version}}"], runner)).stdout.trim();
|
|
338
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);
|
|
339
438
|
const uid = (await step(executor, "host uid", "id", ["-u"], runner)).stdout.trim();
|
|
340
439
|
const gid = (await step(executor, "host gid", "id", ["-g"], runner)).stdout.trim();
|
|
341
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");
|
|
342
441
|
const images: ExecutorCheck["images"] = [];
|
|
343
442
|
for (const image of new Set([protocol.candidate.image, protocol.evaluator.image])) {
|
|
344
|
-
|
|
345
|
-
try { present = await runOnExecutor(executor, "docker", ["image", "inspect", "--format", "{{.Id}}", image], runner); }
|
|
346
|
-
catch { throw failed(executor, "image availability"); }
|
|
347
|
-
if (present.timedOut || present.truncated) throw failed(executor, "image availability");
|
|
348
|
-
if (present.exitCode !== 0) await step(executor, "image pull", "docker", ["pull", image], runner, { timeoutMs: 300_000 });
|
|
443
|
+
await ensureImage(executor, image, runner);
|
|
349
444
|
images.push({ image, available: true });
|
|
350
445
|
}
|
|
351
446
|
return { ...(Object.keys(protocol.inputs ?? {}).length ? { inputRuntime: "python3" as const } : {}), executor, serverVersion: version, user: `${uid}:${gid}`, images, pull: "missing" };
|
|
@@ -357,10 +452,24 @@ export function executionPathsOverlap(left: string, right: string): boolean {
|
|
|
357
452
|
}
|
|
358
453
|
export type Stage = "candidate" | "evaluator";
|
|
359
454
|
export interface ContainerPaths { snapshot: string; output: string; evaluator: string; result: string }
|
|
360
|
-
export interface ContainerOptions { protocol: Protocol; stage: Stage; studyId: string; attemptId: string; user: string; paths: ContainerPaths; seed?: number; gpuDevices?: string[]; pipeline?: { name: string; inputRoot: string; seed: boolean } }
|
|
361
|
-
export function containerName(attemptId: string, stage: Stage): string {
|
|
455
|
+
export interface ContainerOptions { protocol: Protocol; stage: Stage; studyId: string; attemptId: string; user: string; paths: ContainerPaths; seed?: number; gpuDevices?: string[]; name?: string; pipeline?: { name: string; inputRoot: string; seed: boolean } }
|
|
456
|
+
export function containerName(studyId: string, attemptId: string, stage: Stage): string {
|
|
362
457
|
if (!/^[a-f0-9]{16}$/.test(attemptId) || !["candidate", "evaluator"].includes(stage)) throw new Error("container identity: invalid attempt or stage; use a 16-hex attempt id and candidate or evaluator stage");
|
|
363
|
-
|
|
458
|
+
if (!/^[A-Za-z0-9_-]{1,80}$/.test(studyId)) throw new Error("container identity: invalid study id; use the id from study.json");
|
|
459
|
+
// An attempt id is study-local, so the name must carry the study too or two studies collide on one executor host.
|
|
460
|
+
return `ares-${sha256(`${CONTAINER_NAME_DOMAIN}\0${studyId}\0${attemptId}`).slice(0, 16)}-${stage}`;
|
|
461
|
+
}
|
|
462
|
+
/** The pipeline stage suffix is part of the launched name; one place keeps the argv and the attempt record identical. */
|
|
463
|
+
export function stageContainerName(studyId: string, attemptId: string, stage: Stage, pipelineStage?: string): string {
|
|
464
|
+
const name = containerName(studyId, attemptId, stage);
|
|
465
|
+
if (pipelineStage === undefined) return name;
|
|
466
|
+
if (stage !== "candidate" || !/^[a-z][a-z0-9_-]{0,31}$/.test(pipelineStage)) throw new Error("pipeline container: invalid stage name");
|
|
467
|
+
return `${name}-${pipelineStage}`;
|
|
468
|
+
}
|
|
469
|
+
/** A stage that was already recorded keeps its own launched name, pipeline suffix included. */
|
|
470
|
+
function recordedContainerName(name: string): string {
|
|
471
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(name)) throw new Error("container identity: invalid recorded name; use the name stored on the attempt stage");
|
|
472
|
+
return name;
|
|
364
473
|
}
|
|
365
474
|
/** Pure preflight for host input isolation; no hashing, transport or attempt side effects. */
|
|
366
475
|
export function validateContainerInputSources(protocol: Protocol, pathsArg: ContainerPaths): void {
|
|
@@ -375,8 +484,7 @@ export function validateContainerInputSources(protocol: Protocol, pathsArg: Cont
|
|
|
375
484
|
}
|
|
376
485
|
/** Mounts are fixed by stage, never supplied as free-form Docker options. */
|
|
377
486
|
export function buildContainerArgs(options: ContainerOptions): string[] {
|
|
378
|
-
const p = validateProtocol(options.protocol), name =
|
|
379
|
-
if (options.pipeline && (options.stage !== "candidate" || !/^[a-z][a-z0-9_-]{0,31}$/.test(options.pipeline.name))) throw new Error("pipeline container: invalid stage name");
|
|
487
|
+
const p = validateProtocol(options.protocol), name = options.name === undefined ? stageContainerName(options.studyId, options.attemptId, options.stage, options.pipeline?.name) : recordedContainerName(options.name);
|
|
380
488
|
const seed = options.seed === undefined ? p.seeds[0]! : options.seed;
|
|
381
489
|
if (!Number.isSafeInteger(seed) || !p.seeds.includes(seed)) throw new Error("container seed: undeclared or non-integer; choose a seed from protocol.seeds for ares attempt run --seed N");
|
|
382
490
|
if (!/^[A-Za-z0-9_-]{1,80}$/.test(options.studyId)) throw new Error("study id: invalid label; use the id from study.json");
|
|
@@ -421,8 +529,9 @@ export function buildContainerArgs(options: ContainerOptions): string[] {
|
|
|
421
529
|
}
|
|
422
530
|
|
|
423
531
|
/** Launch on the executor host; stdio is detached so SSH returns immediately. T3 reconciles deadlines as a backstop. */
|
|
424
|
-
export async function startWatchdog(executor: Executor,
|
|
425
|
-
|
|
532
|
+
export async function startWatchdog(executor: Executor, name: string, wallSeconds: number, runner: ProcessRunner = spawnRunner, containerId?: string): Promise<void> {
|
|
533
|
+
// The caller passes the name the container was launched with, which is the recorded one for older attempts.
|
|
534
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(name)) throw new Error("watchdog container name: invalid; pass the launched container name");
|
|
426
535
|
if (containerId !== undefined && !/^[a-f0-9]{64}$/.test(containerId)) throw new Error("watchdog container id: invalid; use the full id returned by the verified container start");
|
|
427
536
|
if (!Number.isSafeInteger(wallSeconds) || wallSeconds < 1 || wallSeconds > 604_800) throw new Error("watchdog deadline: invalid wallSeconds; use the validated protocol limit (1..604800 seconds)");
|
|
428
537
|
const script = `nohup sh -c ${shellQuote(`sleep ${wallSeconds}; docker kill ${containerId ?? name}`)} </dev/null >/dev/null 2>&1 &`;
|
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
|
});
|