repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/overkill/lib/aftermath-state.ts
RawFile outline
- AftermathManifest line 13
- MiningCheckpoint line 42
- HASH line 48
- UUID line 49
- DIGEST_KEYS line 50
- hash line 62
- exactObject line 68
- text line 84
- fingerprint line 90
- assertManifest line 96
- assertDigest line 228
- assertHarvest line 249
- createAftermathDirectory line 294
- persistAftermathManifest line 301
- readAftermathManifest line 313
- persistHarvest line 323
- readHarvest line 351
- checkpoint line 365
- persistMiningCheckpoint line 404
- readMiningCheckpoint line 420
- persistMiningOutput line 435
- readMiningOutput line 449
- validateFrozen line 463
- taskFingerprint line 522
- persistFrozenTasks line 526
- AftermathCost line 548
- assertAftermathCost line 555
- persistAftermathCost line 572
- readAftermathCost line 584
- JudgeCache line 599
- assertJudgeCache line 604
- persistJudgeCache line 628
- readJudgeCache line 640
- readFrozenTasks line 653
- test line 670
- train line 670
- validation line 670
- train line 681
- validation line 682
- test line 683
import { createHash, randomUUID } from "node:crypto";
import { access, readFile } from "node:fs/promises";
import { isAbsolute, join } from "node:path";
import { type Digest, stableDigestJson } from "./aftermath-harvest.ts";
import {
assignSplits,
canonicalJson,
type FrozenTask,
validateAndFreezeTasks,
} from "./aftermath-mining.ts";
import { createRunDirectory, writePrivateText } from "./run-state.ts";
export type AftermathManifest = {
version: 1;
runId: string;
kind: "aftermath";
source: { path: string; fingerprint: string };
model: { provider: string; id: string; thinking: string };
sessionId: string;
linkEntryId: string | null;
stage: string;
terminal: null | "staged" | "no_improvement" | "failed" | "discarded";
harvestFingerprint?: string;
taskFingerprint?: string;
scores: {
baseline: number | null;
current: number | null;
best: number | null;
test: number | null;
};
calls: { target: number; checker: number; optimizer: number; judge: number };
artifacts: {
baselineSnapshot: "baseline-snapshot.md";
report: "report.json" | null;
staged: "staged-skill.md" | null;
};
target: { name: string; path: string };
scorers?: Array<{ id: string; kind: "deterministic" | "rubric" }>;
splits?: { train: string[]; validation: string[]; test: string[] };
};
export type MiningCheckpoint = {
attemptedCalls: number;
completedChunks: number[];
completedLevels: Array<{ level: number; index: number }>;
};
const HASH = /^[a-f0-9]{64}$/;
const UUID = /^[0-9a-f-]{36}$/i;
const DIGEST_KEYS = [
"sessionId",
"cwd",
"leafId",
"userPrompts",
"assistantResponses",
"toolNames",
"touchedPaths",
"skillActivations",
"followUps",
] as const;
function hash(value: unknown): string {
return createHash("sha256")
.update(canonicalJson(value), "utf8")
.digest("hex");
}
function exactObject(
value: unknown,
keys: readonly string[],
label: string,
): Record<string, unknown> {
if (typeof value !== "object" || value === null || Array.isArray(value))
throw new Error(`${label} must be an object`);
const record = value as Record<string, unknown>;
if (
Object.keys(record).length !== keys.length ||
Object.keys(record).some((key) => !keys.includes(key))
)
throw new Error(`${label} has invalid fields`);
return record;
}
function text(value: unknown, label: string, allowEmpty = false): string {
if (typeof value !== "string" || (!allowEmpty && value.length === 0))
throw new Error(`${label} must be a nonempty string`);
return value;
}
function fingerprint(value: unknown, label: string): string {
const result = text(value, label);
if (!HASH.test(result)) throw new Error(`${label} is invalid`);
return result;
}
function assertManifest(value: unknown): asserts value is AftermathManifest {
const record = exactObject(
value,
[
"version",
"runId",
"kind",
"source",
"model",
"sessionId",
"linkEntryId",
"stage",
"terminal",
"harvestFingerprint",
"taskFingerprint",
"scores",
"calls",
"artifacts",
"target",
"scorers",
"splits",
].filter(
(key) =>
(value as Record<string, unknown> | null)?.[key] !== undefined ||
![
"harvestFingerprint",
"taskFingerprint",
"scorers",
"splits",
].includes(key),
),
"aftermath manifest",
);
if (
record.version !== 1 ||
record.kind !== "aftermath" ||
!UUID.test(text(record.runId, "run ID"))
)
throw new Error("invalid aftermath manifest");
const source = exactObject(
record.source,
["path", "fingerprint"],
"manifest source",
);
if (!isAbsolute(text(source.path, "source path")))
throw new Error("source path must be absolute");
fingerprint(source.fingerprint, "source fingerprint");
const model = exactObject(
record.model,
["provider", "id", "thinking"],
"manifest model",
);
text(model.provider, "model provider");
text(model.id, "model ID");
text(model.thinking, "model thinking", true);
text(record.sessionId, "session ID");
text(record.stage, "manifest stage");
if (record.linkEntryId !== null) text(record.linkEntryId, "manifest link");
if (
![null, "staged", "no_improvement", "failed", "discarded"].includes(
record.terminal as null,
)
)
throw new Error("invalid manifest terminal");
if (record.harvestFingerprint !== undefined)
fingerprint(record.harvestFingerprint, "harvest fingerprint");
if (record.taskFingerprint !== undefined)
fingerprint(record.taskFingerprint, "task fingerprint");
const scores = exactObject(
record.scores,
["baseline", "current", "best", "test"],
"manifest scores",
);
for (const [label, score] of Object.entries(scores))
if (score !== null) {
if (
typeof score !== "number" ||
!Number.isFinite(score) ||
score < 0 ||
score > 1
)
throw new Error(`invalid manifest ${label} score`);
}
const calls = exactObject(
record.calls,
["target", "checker", "optimizer", "judge"],
"manifest calls",
);
for (const [label, count] of Object.entries(calls))
if (!Number.isInteger(count) || (count as number) < 0)
throw new Error(`invalid manifest ${label} calls`);
const artifacts = exactObject(
record.artifacts,
["baselineSnapshot", "report", "staged"],
"manifest artifacts",
);
if (
artifacts.baselineSnapshot !== "baseline-snapshot.md" ||
(artifacts.report !== null && artifacts.report !== "report.json") ||
(artifacts.staged !== null && artifacts.staged !== "staged-skill.md")
)
throw new Error("invalid manifest artifacts");
const target = exactObject(
record.target,
["name", "path"],
"manifest target",
);
text(target.name, "manifest target name");
if (!isAbsolute(text(target.path, "manifest target path")))
throw new Error("manifest target path must be absolute");
if (record.scorers !== undefined) {
if (!Array.isArray(record.scorers))
throw new Error("invalid manifest scorers");
for (const scorer of record.scorers) {
const item = exactObject(scorer, ["id", "kind"], "manifest scorer");
text(item.id, "manifest scorer ID");
if (item.kind !== "deterministic" && item.kind !== "rubric")
throw new Error("invalid manifest scorer");
}
}
if (record.splits !== undefined) {
const splits = exactObject(
record.splits,
["train", "validation", "test"],
"manifest splits",
);
for (const values of Object.values(splits))
if (!Array.isArray(values) || values.some((id) => typeof id !== "string"))
throw new Error("invalid manifest splits");
}
}
function assertDigest(value: unknown): asserts value is Digest {
const record = exactObject(value, DIGEST_KEYS, "digest");
for (const key of ["sessionId", "cwd", "leafId"] as const) {
const item = text(record[key], `digest ${key}`, key === "leafId");
if (Buffer.byteLength(item, "utf8") > 4 * 1024)
throw new Error("digest string is oversized");
}
for (const key of DIGEST_KEYS.slice(3)) {
if (!Array.isArray(record[key]) || record[key].length > 32)
throw new Error("digest array is invalid");
for (const item of record[key])
if (
typeof item !== "string" ||
Buffer.byteLength(item, "utf8") > 4 * 1024
)
throw new Error("digest string is invalid");
}
if (Buffer.byteLength(stableDigestJson(record as Digest), "utf8") > 16 * 1024)
throw new Error("digest exceeds cap");
}
function assertHarvest(value: unknown): asserts value is {
digests: Digest[];
unreadable: number;
total: number;
evidence: Record<string, number>;
fingerprint: string;
} {
const record = exactObject(
value,
["digests", "unreadable", "total", "evidence", "fingerprint"],
"harvest snapshot",
);
if (!Array.isArray(record.digests))
throw new Error("invalid harvest digests");
for (const digest of record.digests) assertDigest(digest);
const ids = record.digests.map((digest) => digest.sessionId);
if (
new Set(ids).size !== ids.length ||
ids.some((id, index) => {
const previous = ids[index - 1];
return previous !== undefined && previous >= id;
})
)
throw new Error("harvest digests are not sorted");
for (const key of ["unreadable", "total"] as const)
if (!Number.isInteger(record[key]) || (record[key] as number) < 0)
throw new Error("invalid harvest count");
if ((record.total as number) < record.digests.length)
throw new Error("invalid harvest total");
if (
typeof record.evidence !== "object" ||
record.evidence === null ||
Array.isArray(record.evidence)
)
throw new Error("invalid harvest evidence");
for (const count of Object.values(record.evidence as Record<string, unknown>))
if (typeof count !== "number" || !Number.isInteger(count) || count < 0)
throw new Error("invalid harvest evidence");
if (
fingerprint(record.fingerprint, "harvest fingerprint") !==
hash(record.digests)
)
throw new Error("harvest fingerprint mismatch");
}
export async function createAftermathDirectory(
agentDir: string,
): Promise<{ directory: string; runId: string }> {
const runId = randomUUID();
return { runId, directory: await createRunDirectory(agentDir, runId) };
}
export async function persistAftermathManifest(
directory: string,
manifest: AftermathManifest,
): Promise<void> {
assertManifest(manifest);
await writePrivateText(
directory,
"manifest.json",
`${JSON.stringify(manifest)}\n`,
);
}
export async function readAftermathManifest(
directory: string,
): Promise<AftermathManifest> {
const value: unknown = JSON.parse(
await readFile(join(directory, "manifest.json"), "utf8"),
);
assertManifest(value);
return value;
}
export async function persistHarvest(
directory: string,
value: Omit<
Parameters<typeof assertHarvest>[0] extends never
? never
: {
digests: Digest[];
unreadable: number;
total: number;
evidence: Record<string, number>;
},
"fingerprint"
>,
): Promise<{ fingerprint: string; path: string }> {
const digests = [...value.digests].sort((left, right) =>
left.sessionId.localeCompare(right.sessionId),
);
const fingerprintValue = hash(digests);
const stored = { ...value, digests, fingerprint: fingerprintValue };
assertHarvest(stored);
const path = await writePrivateText(
directory,
"harvest.json",
`${canonicalJson(stored)}\n`,
);
return { fingerprint: fingerprintValue, path };
}
export async function readHarvest(directory: string): Promise<{
digests: Digest[];
unreadable: number;
total: number;
evidence: Record<string, number>;
fingerprint: string;
}> {
const value: unknown = JSON.parse(
await readFile(join(directory, "harvest.json"), "utf8"),
);
assertHarvest(value);
return value;
}
function checkpoint(value: unknown): asserts value is MiningCheckpoint {
const record = exactObject(
value,
["attemptedCalls", "completedChunks", "completedLevels"],
"mining checkpoint",
);
if (
!Number.isInteger(record.attemptedCalls) ||
(record.attemptedCalls as number) < 0 ||
!Array.isArray(record.completedChunks) ||
!Array.isArray(record.completedLevels)
)
throw new Error("invalid mining checkpoint");
const chunks = record.completedChunks as unknown[];
if (
chunks.some((item) => !Number.isInteger(item) || (item as number) < 0) ||
new Set(chunks).size !== chunks.length
)
throw new Error("invalid mining checkpoint");
const groups = record.completedLevels as unknown[];
const seen = new Set<string>();
for (const group of groups) {
const item = exactObject(
group,
["level", "index"],
"mining checkpoint group",
);
if (
!Number.isInteger(item.level) ||
(item.level as number) < 0 ||
!Number.isInteger(item.index) ||
(item.index as number) < 0 ||
seen.has(`${item.level}:${item.index}`)
)
throw new Error("invalid mining checkpoint");
seen.add(`${item.level}:${item.index}`);
}
}
export async function persistMiningCheckpoint(
directory: string,
value: MiningCheckpoint,
): Promise<void> {
checkpoint(value);
const completedChunks = [...value.completedChunks].sort((a, b) => a - b);
const completedLevels = [...value.completedLevels].sort(
(a, b) => a.level - b.level || a.index - b.index,
);
await writePrivateText(
directory,
"mining-checkpoint.json",
`${canonicalJson({ attemptedCalls: value.attemptedCalls, completedChunks, completedLevels })}\n`,
);
}
export async function readMiningCheckpoint(
directory: string,
): Promise<MiningCheckpoint | undefined> {
try {
const value: unknown = JSON.parse(
await readFile(join(directory, "mining-checkpoint.json"), "utf8"),
);
checkpoint(value);
return value;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
throw error;
}
}
export async function persistMiningOutput(
directory: string,
filename: string,
output: unknown[],
): Promise<void> {
if (!/^(?:miner-chunk-[0-9]+|aggregate-[0-9]+-[0-9]+)\.json$/.test(filename))
throw new Error("invalid mining output filename");
await writePrivateText(
directory,
filename,
`${canonicalJson({ tasks: output })}\n`,
);
}
export async function readMiningOutput(
directory: string,
filename: string,
): Promise<unknown[]> {
if (!/^(?:miner-chunk-[0-9]+|aggregate-[0-9]+-[0-9]+)\.json$/.test(filename))
throw new Error("invalid mining output filename");
const value: unknown = JSON.parse(
await readFile(join(directory, filename), "utf8"),
);
const record = exactObject(value, ["tasks"], "mining output");
if (!Array.isArray(record.tasks)) throw new Error("invalid mining output");
return record.tasks;
}
function validateFrozen(
tasks: FrozenTask[],
splits: { train: string[]; validation: string[]; test: string[] },
): FrozenTask[] {
const fields = [
"id",
"intent",
"context",
"sourceSessionIds",
"observedOutcome",
"checks",
"rubric",
];
for (const task of tasks) {
const record = task as unknown as Record<string, unknown>;
for (const key of Object.keys(record))
if (!fields.includes(key)) throw new Error("invalid frozen task");
}
const sourceIds = new Set(tasks.flatMap((task) => task.sourceSessionIds));
const frozen = validateAndFreezeTasks({
proposals: tasks.map(({ id: _id, ...task }) => task),
harvestedSessionIds: sourceIds,
maximum: tasks.length,
});
if (
frozen.length !== tasks.length ||
canonicalJson(frozen) !==
canonicalJson([...tasks].sort((a, b) => a.id.localeCompare(b.id)))
)
throw new Error("invalid frozen task");
const splitRecord = exactObject(
splits,
["train", "validation", "test"],
"task splits",
);
const taskIds = new Set(tasks.map((task) => task.id));
const assigned: string[] = [];
for (const group of [
splitRecord.train,
splitRecord.validation,
splitRecord.test,
]) {
if (
!Array.isArray(group) ||
group.some((id) => typeof id !== "string" || !taskIds.has(id))
)
throw new Error("invalid task split");
assigned.push(...group);
}
if (
assigned.length !== taskIds.size ||
new Set(assigned).size !== taskIds.size
)
throw new Error("task splits must be complete and disjoint");
if (canonicalJson(splits) !== canonicalJson(assignSplits(frozen)))
throw new Error("task splits are not deterministic");
return frozen;
}
function taskFingerprint(tasks: readonly FrozenTask[]): string {
return hash(tasks);
}
export async function persistFrozenTasks(
directory: string,
tasks: FrozenTask[],
splits: { train: string[]; validation: string[]; test: string[] },
): Promise<{ fingerprint: string; path: string }> {
const destination = join(directory, "tasks.json");
try {
await access(destination);
throw new Error("frozen task records are immutable");
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
}
const sorted = validateFrozen(tasks, splits);
const fingerprintValue = taskFingerprint(sorted);
const path = await writePrivateText(
directory,
"tasks.json",
`${canonicalJson({ version: 1, fingerprint: fingerprintValue, tasks: sorted, splits })}\n`,
);
return { fingerprint: fingerprintValue, path };
}
export type AftermathCost = {
targetMaximum: number;
judgeMaximum: number;
targetConsumed: number;
judgeConsumed: number;
};
function assertAftermathCost(value: unknown): asserts value is AftermathCost {
const record = exactObject(
value,
["targetMaximum", "judgeMaximum", "targetConsumed", "judgeConsumed"],
"aftermath cost",
);
for (const key of Object.keys(record))
if (!Number.isInteger(record[key]) || (record[key] as number) < 0)
throw new Error("invalid aftermath cost");
const cost = record as unknown as AftermathCost;
if (
cost.targetConsumed > cost.targetMaximum ||
cost.judgeConsumed > cost.judgeMaximum
)
throw new Error("aftermath cost exceeds maximum");
}
export async function persistAftermathCost(
directory: string,
cost: AftermathCost,
): Promise<void> {
assertAftermathCost(cost);
await writePrivateText(
directory,
"aftermath-cost.json",
`${canonicalJson(cost)}\n`,
);
}
export async function readAftermathCost(
directory: string,
): Promise<AftermathCost | undefined> {
try {
const value: unknown = JSON.parse(
await readFile(join(directory, "aftermath-cost.json"), "utf8"),
);
assertAftermathCost(value);
return value;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
throw error;
}
}
export type JudgeCache = Record<
string,
{ score: number; passed: boolean; rationale: string }
>;
function assertJudgeCache(value: unknown): asserts value is JudgeCache {
if (typeof value !== "object" || value === null || Array.isArray(value))
throw new Error("judge cache must be an object");
for (const [key, result] of Object.entries(value)) {
if (!/^task-[a-f0-9]{64}:[a-f0-9]{64}$/.test(key))
throw new Error("judge cache key is invalid");
const record = exactObject(
result,
["score", "passed", "rationale"],
"judge cache result",
);
if (
typeof record.score !== "number" ||
!Number.isFinite(record.score) ||
record.score < 0 ||
record.score > 1 ||
typeof record.passed !== "boolean" ||
typeof record.rationale !== "string" ||
Buffer.byteLength(record.rationale, "utf8") > 4096
)
throw new Error("judge cache result is invalid");
}
}
export async function persistJudgeCache(
directory: string,
cache: JudgeCache,
): Promise<void> {
assertJudgeCache(cache);
await writePrivateText(
directory,
"judge-cache.json",
`${canonicalJson(cache)}\n`,
);
}
export async function readJudgeCache(directory: string): Promise<JudgeCache> {
try {
const cache: unknown = JSON.parse(
await readFile(join(directory, "judge-cache.json"), "utf8"),
);
assertJudgeCache(cache);
return cache;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
throw error;
}
}
export async function readFrozenTasks(directory: string): Promise<{
fingerprint: string;
tasks: FrozenTask[];
splits: { train: string[]; validation: string[]; test: string[] };
}> {
const value: unknown = JSON.parse(
await readFile(join(directory, "tasks.json"), "utf8"),
);
const record = exactObject(
value,
["version", "fingerprint", "tasks", "splits"],
"frozen tasks",
);
if (record.version !== 1 || !Array.isArray(record.tasks))
throw new Error("invalid frozen tasks");
const tasks = validateFrozen(
record.tasks as FrozenTask[],
record.splits as { train: string[]; validation: string[]; test: string[] },
);
if (
fingerprint(record.fingerprint, "task fingerprint") !==
taskFingerprint(tasks)
)
throw new Error("task fingerprint mismatch");
return {
fingerprint: record.fingerprint as string,
tasks,
splits: record.splits as {
train: string[];
validation: string[];
test: string[];
},
};
}