repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/overkill/lib/aftermath-mining.ts
RawFile outline
- DeterministicCheck line 11
- FrozenTask line 17
- bytes line 27
- exactObject line 31
- boundedText line 44
- canonicalize line 58
- canonicalJson line 68
- validateCheck line 72
- taskPayload line 115
- taskId line 128
- validateAndFreezeTasks line 134
- chunkConsecutively line 213
- estimateMiningCalls line 225
- MiningSession line 239
- StructuredOutputSdkSeam line 256
- defaultStructuredOutputSdk line 267
- miningOutput line 278
- createMiningSession line 297
- structuredTasks line 337
- onAbort line 356
- mineTaskProposals line 385
- assignSplits line 434
import { createHash } from "node:crypto";
import {
createAgentSession,
DefaultResourceLoader,
defineTool,
SessionManager,
SettingsManager,
} from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";
export type DeterministicCheck =
| { type: "contains"; value: string; caseSensitive: boolean }
| { type: "section_present"; heading: string }
| { type: "min_chars"; count: number }
| { type: "max_chars"; count: number };
export type FrozenTask = {
id: string;
intent: string;
context: string;
sourceSessionIds: string[];
observedOutcome?: string;
checks?: DeterministicCheck[];
rubric?: string;
};
function bytes(value: string): number {
return Buffer.byteLength(value, "utf8");
}
function exactObject(
value: unknown,
fields: readonly string[],
label: string,
): Record<string, unknown> {
if (typeof value !== "object" || value === null || Array.isArray(value))
throw new Error(`${label} must be an object`);
for (const field of Object.keys(value))
if (!fields.includes(field))
throw new Error(`${label} has unknown field: ${field}`);
return value as Record<string, unknown>;
}
function boundedText(
value: unknown,
maximum: number,
label: string,
trim = false,
): string {
if (typeof value !== "string") throw new Error(`${label} must be a string`);
const normalized = value.replace(/\r\n?/g, "\n");
const result = trim ? normalized.trim() : normalized;
if (bytes(result) === 0 || bytes(result) > maximum)
throw new Error(`${label} is out of bounds`);
return result;
}
function canonicalize(value: unknown): unknown {
if (Array.isArray(value)) return value.map(canonicalize);
if (typeof value !== "object" || value === null) return value;
return Object.fromEntries(
Object.entries(value as Record<string, unknown>)
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
.map(([key, child]) => [key, canonicalize(child)]),
);
}
export function canonicalJson(value: unknown): string {
return JSON.stringify(canonicalize(value));
}
function validateCheck(value: unknown): DeterministicCheck {
const record = exactObject(
value,
["type", "value", "caseSensitive", "heading", "count"],
"check",
);
if (record.type === "contains") {
for (const key of Object.keys(record))
if (key !== "type" && key !== "value" && key !== "caseSensitive")
throw new Error("contains check has unknown field");
if (typeof record.caseSensitive !== "boolean")
throw new Error("contains case sensitivity is required");
return {
type: "contains",
value: boundedText(record.value, 1024, "contains value", true),
caseSensitive: record.caseSensitive,
};
}
if (record.type === "section_present") {
for (const key of Object.keys(record))
if (key !== "type" && key !== "heading")
throw new Error("section check has unknown field");
return {
type: "section_present",
heading: boundedText(record.heading, 1024, "section heading", true),
};
}
if (record.type === "min_chars" || record.type === "max_chars") {
for (const key of Object.keys(record))
if (key !== "type" && key !== "count")
throw new Error("character check has unknown field");
if (
typeof record.count !== "number" ||
!Number.isInteger(record.count) ||
record.count < 0 ||
record.count > 65_536
)
throw new Error("character count is invalid");
return { type: record.type, count: record.count };
}
throw new Error("unknown deterministic check");
}
function taskPayload(task: Omit<FrozenTask, "id">): Record<string, unknown> {
return {
intent: task.intent,
context: task.context,
sourceSessionIds: [...task.sourceSessionIds].sort(),
...(task.observedOutcome === undefined
? {}
: { observedOutcome: task.observedOutcome }),
...(task.checks === undefined ? {} : { checks: task.checks }),
...(task.rubric === undefined ? {} : { rubric: task.rubric }),
};
}
export function taskId(task: Omit<FrozenTask, "id">): string {
return `task-${createHash("sha256")
.update(canonicalJson(taskPayload(task)), "utf8")
.digest("hex")}`;
}
export function validateAndFreezeTasks(options: {
proposals: readonly unknown[];
harvestedSessionIds: ReadonlySet<string>;
maximum?: number;
}): FrozenTask[] {
const frozen = new Map<string, FrozenTask>();
for (const proposal of options.proposals) {
try {
const record = exactObject(
proposal,
[
"intent",
"context",
"sourceSessionIds",
"observedOutcome",
"checks",
"rubric",
],
"task proposal",
);
const intent = boundedText(record.intent, 512, "intent", true);
const context = boundedText(record.context, 4096, "context", true);
if (!Array.isArray(record.sourceSessionIds))
throw new Error("source session IDs are required");
const sourceSessionIds = record.sourceSessionIds.map((id) => {
const normalized = boundedText(id, 1024, "source session ID", true);
if (!options.harvestedSessionIds.has(normalized))
throw new Error("source session ID is unknown");
return normalized;
});
const uniqueSourceIds = [...new Set(sourceSessionIds)].sort();
if (
sourceSessionIds.length !== uniqueSourceIds.length ||
uniqueSourceIds.length < 2 ||
uniqueSourceIds.length > 32
)
throw new Error("task is not recurring");
const hasChecks = record.checks !== undefined;
const hasRubric = record.rubric !== undefined;
if (hasChecks === hasRubric)
throw new Error("task requires checks xor rubric");
const task: Omit<FrozenTask, "id"> = {
intent,
context,
sourceSessionIds: uniqueSourceIds,
...(record.observedOutcome === undefined
? {}
: {
observedOutcome: boundedText(
record.observedOutcome,
2048,
"observed outcome",
true,
),
}),
};
if (hasChecks) {
if (
!Array.isArray(record.checks) ||
record.checks.length < 1 ||
record.checks.length > 8
)
throw new Error("checks are out of bounds");
task.checks = record.checks.map(validateCheck);
} else task.rubric = boundedText(record.rubric, 8192, "rubric", true);
const id = taskId(task);
frozen.set(id, { id, ...task });
} catch {
// One malformed proposal is discarded; a malformed model response shape
// is rejected before this function is called.
}
}
return [...frozen.values()]
.sort((left, right) =>
left.id < right.id ? -1 : left.id > right.id ? 1 : 0,
)
.slice(0, options.maximum ?? 30);
}
export function chunkConsecutively<T>(
values: readonly T[],
maximum = 20,
): T[][] {
if (!Number.isInteger(maximum) || maximum < 1)
throw new Error("invalid chunk size");
const chunks: T[][] = [];
for (let index = 0; index < values.length; index += maximum)
chunks.push(values.slice(index, index + maximum));
return chunks;
}
export function estimateMiningCalls(readableSessions: number): {
mining: number;
aggregation: number;
total: number;
} {
if (!Number.isInteger(readableSessions) || readableSessions < 0)
throw new Error("readable session count is invalid");
const mining = Math.ceil(readableSessions / 20);
let aggregation = 0;
for (let level = mining; level > 1; level = Math.ceil(level / 20))
aggregation += Math.ceil(level / 20);
return { mining, aggregation, total: mining + aggregation };
}
export type MiningSession = {
prompt: (
text: string,
options?: { expandPromptTemplates?: boolean },
) => Promise<void>;
subscribe: (
listener: (event: {
type: string;
toolName?: string;
result?: { details?: unknown };
isError?: boolean;
}) => void,
) => () => void;
abort: () => Promise<void>;
dispose: () => void | Promise<void>;
};
export type StructuredOutputSdkSeam = {
DefaultResourceLoader: new (
options: Record<string, unknown>,
) => { reload: () => Promise<void> };
SettingsManager: { inMemory: (settings: unknown) => unknown };
SessionManager: { inMemory: (cwd: string) => unknown };
createAgentSession: (
options: Record<string, unknown>,
) => Promise<{ session: MiningSession }>;
};
export const defaultStructuredOutputSdk: StructuredOutputSdkSeam = {
DefaultResourceLoader:
DefaultResourceLoader as unknown as StructuredOutputSdkSeam["DefaultResourceLoader"],
SettingsManager:
SettingsManager as unknown as StructuredOutputSdkSeam["SettingsManager"],
SessionManager:
SessionManager as unknown as StructuredOutputSdkSeam["SessionManager"],
createAgentSession:
createAgentSession as unknown as StructuredOutputSdkSeam["createAgentSession"],
};
const miningOutput = defineTool({
name: "structured_output",
label: "Structured output",
description: "Return task proposals as the final action.",
parameters: Type.Object(
{ tasks: Type.Array(Type.Any()) },
{ additionalProperties: false },
),
async execute(_id, params) {
return {
content: [
{ type: "text" as const, text: "Structured mining output received." },
],
details: params,
terminate: true,
};
},
});
export async function createMiningSession(
options: {
cwd: string;
agentDir: string;
model: { thinking: string };
targetModel: unknown;
modelRegistry: unknown;
},
sdk: StructuredOutputSdkSeam = defaultStructuredOutputSdk,
): Promise<MiningSession> {
const settingsManager = sdk.SettingsManager.inMemory({
compaction: { enabled: false },
retry: { enabled: false },
});
const loader = new sdk.DefaultResourceLoader({
cwd: options.cwd,
agentDir: options.agentDir,
settingsManager,
noExtensions: true,
noSkills: true,
noPromptTemplates: true,
noThemes: true,
noContextFiles: true,
});
await loader.reload();
const result = await sdk.createAgentSession({
cwd: options.cwd,
agentDir: options.agentDir,
model: options.targetModel as never,
modelRegistry: options.modelRegistry as never,
thinkingLevel: options.model.thinking as never,
tools: ["structured_output"],
customTools: [miningOutput],
sessionManager: sdk.SessionManager.inMemory(options.cwd),
settingsManager,
resourceLoader: loader,
});
return result.session as unknown as MiningSession;
}
async function structuredTasks(
session: MiningSession,
prompt: string,
maximum: number,
signal?: AbortSignal,
onCall?: () => Promise<void>,
): Promise<unknown[]> {
let output: unknown;
let outputs = 0;
const unsubscribe = session.subscribe((event) => {
if (
event.type === "tool_execution_end" &&
event.toolName === "structured_output" &&
!event.isError
) {
outputs += 1;
output = event.result?.details;
}
});
const onAbort = () => void session.abort();
signal?.addEventListener("abort", onAbort, { once: true });
try {
if (signal?.aborted) throw new Error("mining cancelled");
await onCall?.();
if (signal?.aborted) throw new Error("mining cancelled");
await session.prompt(prompt, { expandPromptTemplates: false });
if (signal?.aborted) throw new Error("mining cancelled");
if (
outputs !== 1 ||
typeof output !== "object" ||
output === null ||
Array.isArray(output)
)
throw new Error("miner must emit exactly one structured output");
const record = exactObject(output, ["tasks"], "miner output");
if (!Array.isArray(record.tasks) || record.tasks.length > maximum)
throw new Error("miner output task cap exceeded");
const json = canonicalJson(output);
if (bytes(json) > (maximum === 10 ? 64 * 1024 : 128 * 1024))
throw new Error("miner output byte cap exceeded");
return record.tasks;
} finally {
signal?.removeEventListener("abort", onAbort);
unsubscribe();
await Promise.resolve(session.dispose());
}
}
export async function mineTaskProposals(options: {
digests: readonly unknown[];
createSession: () => Promise<MiningSession>;
signal?: AbortSignal;
onChunk?: (index: number, output: unknown[]) => Promise<void>;
onLevel?: (level: number, index: number, output: unknown[]) => Promise<void>;
onCall?: () => Promise<void>;
completedChunks?: ReadonlyMap<number, unknown[]>;
completedLevels?: ReadonlyMap<number, unknown[][]>;
}): Promise<unknown[]> {
let outputs: unknown[][] = [];
for (const [index, group] of chunkConsecutively(
options.digests,
20,
).entries()) {
const saved = options.completedChunks?.get(index);
const output =
saved ??
(await structuredTasks(
await options.createSession(),
`phase:mine\nExtract no more than 10 recurring, checkable task proposals. Return only {"tasks": [...]}.\ndigests:${canonicalJson(group)}`,
10,
options.signal,
options.onCall,
));
if (!saved) await options.onChunk?.(index, output);
outputs.push(output);
}
for (let level = 0; outputs.length > 1; level += 1) {
const next: unknown[][] = [];
for (const [index, group] of chunkConsecutively(outputs, 20).entries()) {
const saved = options.completedLevels?.get(level)?.[index];
const output =
saved ??
(await structuredTasks(
await options.createSession(),
`phase:aggregate\nConsolidate recurring task proposals. Return only {"tasks": [...]}, at most 30.\noutputs:${canonicalJson(group)}`,
30,
options.signal,
options.onCall,
));
if (!saved) await options.onLevel?.(level, index, output);
next.push(output);
}
outputs = next;
}
return outputs[0] ?? [];
}
export function assignSplits(tasks: readonly FrozenTask[]): {
train: string[];
validation: string[];
test: string[];
} {
if (tasks.length === 0) return { train: [], validation: [], test: [] };
const sorted = [...tasks]
.map((task) => ({
id: task.id,
digest: createHash("sha256").update(`split\0${task.id}`, "utf8").digest(),
}))
.sort(
(left, right) =>
Buffer.compare(left.digest, right.digest) ||
(left.id < right.id ? -1 : left.id > right.id ? 1 : 0),
);
const [first, second, third] = sorted;
if (!first) throw new Error("task split is unavailable");
const splits = {
train: [first.id],
validation: second ? [second.id] : [],
test: third ? [third.id] : [],
};
for (const item of sorted.slice(3)) {
const byte = item.digest.at(0);
if (byte === undefined) throw new Error("invalid split digest");
const bucket = byte % 5;
if (bucket <= 2) splits.train.push(item.id);
else if (bucket === 3) splits.validation.push(item.id);
else splits.test.push(item.id);
}
return splits;
}