repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/iq/storage.ts
RawFile outline
- LoadedRecords line 15
- records line 16
- errors line 17
- DimensionNameSchema line 20
- DimensionScoreSchema line 28
- DimensionsSchema line 38
- SourceSchema line 49
- ObservationSchema line 69
- UsageSchema line 82
- RecordSchema line 96
- iqStateDirectory line 120
- recordsDirectory line 138
- parseRecord line 142
- loadRecords line 148
- recordIdentity line 179
- saveRecord line 194
- recordMatches line 224
- recordsForJudge line 239
- acquireScanLock line 258
- readLockOwner line 302
- processExists line 319
- isNodeError line 328
- boundedError line 332
import { createHash, randomUUID } from "node:crypto";
import { mkdir, open, readdir, readFile, rename, rm } from "node:fs/promises";
import { homedir } from "node:os";
import { join, posix, win32 } from "node:path";
import { Type } from "typebox";
import { Value } from "typebox/value";
import {
PROMPT_VERSION,
RECORD_VERSION,
RUBRIC_VERSION,
type SessionScoreRecord,
type SourceSignature,
} from "./core.js";
export interface LoadedRecords {
records: SessionScoreRecord[];
errors: string[];
}
const DimensionNameSchema = Type.Union([
Type.Literal("comprehension_judgment"),
Type.Literal("reasoning_adaptation"),
Type.Literal("context_management"),
Type.Literal("execution_reliability"),
Type.Literal("collaboration_steerability"),
]);
const DimensionScoreSchema = Type.Object(
{
score: Type.Union([Type.Number(), Type.Null()]),
meanRating: Type.Union([Type.Number(), Type.Null()]),
evidence: Type.Integer({ minimum: 0 }),
evidenceWeight: Type.Number({ minimum: 0 }),
},
{ additionalProperties: false },
);
const DimensionsSchema = Type.Object(
{
comprehension_judgment: DimensionScoreSchema,
reasoning_adaptation: DimensionScoreSchema,
context_management: DimensionScoreSchema,
execution_reliability: DimensionScoreSchema,
collaboration_steerability: DimensionScoreSchema,
},
{ additionalProperties: false },
);
const SourceSchema = Type.Object(
{
path: Type.String({ minLength: 1 }),
size: Type.Number({ minimum: 0 }),
mtimeMs: Type.Number({ minimum: 0 }),
sha256: Type.String({ pattern: "^[0-9a-f]{64}$" }),
sessionId: Type.String(),
name: Type.String(),
cwd: Type.String(),
startedAt: Type.Optional(Type.String()),
endedAt: Type.Optional(Type.String()),
model: Type.Optional(Type.String({ minLength: 1 })),
userMessages: Type.Integer({ minimum: 0 }),
assistantMessages: Type.Integer({ minimum: 0 }),
toolResults: Type.Integer({ minimum: 0 }),
models: Type.Array(Type.String({ minLength: 1 })),
},
{ additionalProperties: false },
);
const ObservationSchema = Type.Object(
{
dimension: DimensionNameSchema,
rating: Type.Integer({ minimum: 1, maximum: 5 }),
importance: Type.Integer({ minimum: 1, maximum: 3 }),
confidence: Type.Number({ minimum: 0.25, maximum: 1 }),
eventIds: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
observation: Type.String({ minLength: 1 }),
sourceChunk: Type.Integer({ minimum: 1 }),
},
{ additionalProperties: false },
);
const UsageSchema = Type.Object(
{
input: Type.Number({ minimum: 0 }),
output: Type.Number({ minimum: 0 }),
cacheRead: Type.Number({ minimum: 0 }),
cacheWrite: Type.Number({ minimum: 0 }),
totalTokens: Type.Number({ minimum: 0 }),
cost: Type.Number({ minimum: 0 }),
calls: Type.Integer({ minimum: 0 }),
retries: Type.Integer({ minimum: 0 }),
},
{ additionalProperties: false },
);
const RecordSchema = Type.Object(
{
version: Type.Literal(RECORD_VERSION),
rubricVersion: Type.Literal(RUBRIC_VERSION),
promptVersion: Type.Literal(PROMPT_VERSION),
source: SourceSchema,
judge: Type.String({ minLength: 1 }),
score: Type.Object(
{
overall: Type.Union([Type.Number(), Type.Null()]),
observedDimensionWeight: Type.Number({ minimum: 0, maximum: 1 }),
dimensions: DimensionsSchema,
},
{ additionalProperties: false },
),
observations: Type.Array(ObservationSchema),
usage: UsageSchema,
chunkCount: Type.Integer({ minimum: 1 }),
elapsedMs: Type.Number({ minimum: 0 }),
scoredAt: Type.String({ minLength: 1 }),
},
{ additionalProperties: false },
);
export function iqStateDirectory(
env: NodeJS.ProcessEnv = process.env,
platform = process.platform,
home = homedir(),
): string {
if (platform === "win32") {
const base = env.LOCALAPPDATA?.trim() || env.APPDATA?.trim();
return win32.join(base || win32.join(home, "AppData", "Local"), "pi", "iq");
}
if (platform === "darwin")
return posix.join(home, "Library", "Application Support", "pi", "iq");
return posix.join(
env.XDG_STATE_HOME?.trim() || posix.join(home, ".local", "state"),
"pi",
"iq",
);
}
function recordsDirectory(stateDir: string): string {
return join(stateDir, "records");
}
function parseRecord(value: unknown): SessionScoreRecord | undefined {
return Value.Check(RecordSchema, value)
? (value as SessionScoreRecord)
: undefined;
}
export async function loadRecords(
stateDir = iqStateDirectory(),
): Promise<LoadedRecords> {
const directory = recordsDirectory(stateDir);
let files: string[];
try {
files = (await readdir(directory))
.filter((file) => file.endsWith(".json"))
.sort();
} catch (error) {
if (isNodeError(error) && error.code === "ENOENT")
return { records: [], errors: [] };
return { records: [], errors: [boundedError(error)] };
}
const records: SessionScoreRecord[] = [];
const errors: string[] = [];
for (const file of files) {
try {
const parsed: unknown = JSON.parse(
await readFile(join(directory, file), "utf8"),
);
const record = parseRecord(parsed);
if (!record) throw new Error("invalid record schema");
records.push(record);
} catch (error) {
errors.push(`${file}: ${boundedError(error)}`);
}
}
return { records, errors };
}
function recordIdentity(record: SessionScoreRecord): string {
return createHash("sha256")
.update(
[
record.source.path,
record.source.sha256,
record.judge,
record.rubricVersion,
record.promptVersion,
record.scoredAt,
].join("\0"),
)
.digest("hex");
}
export async function saveRecord(
record: SessionScoreRecord,
stateDir = iqStateDirectory(),
): Promise<string> {
if (!Value.Check(RecordSchema, record))
throw new Error("refusing to persist invalid IQ record");
const directory = recordsDirectory(stateDir);
await mkdir(directory, { recursive: true, mode: 0o700 });
const nonce = randomUUID();
const target = join(directory, `${recordIdentity(record)}-${nonce}.json`);
const temporary = join(directory, `.${nonce}.tmp`);
const file = await open(temporary, "wx", 0o600);
try {
await file.writeFile(`${JSON.stringify(record)}\n`, "utf8");
await file.sync();
} catch (error) {
await file.close().catch(() => {});
await rm(temporary, { force: true });
throw error;
}
await file.close();
try {
await rename(temporary, target);
} catch (error) {
await rm(temporary, { force: true });
throw error;
}
return target;
}
export function recordMatches(
record: SessionScoreRecord,
source: SourceSignature,
judge: string,
): boolean {
return (
record.judge === judge &&
record.rubricVersion === RUBRIC_VERSION &&
record.promptVersion === PROMPT_VERSION &&
record.source.path === source.path &&
record.source.size === source.size &&
record.source.mtimeMs === source.mtimeMs
);
}
export function recordsForJudge(
records: readonly SessionScoreRecord[],
judge: string,
): SessionScoreRecord[] {
const latest = new Map<string, SessionScoreRecord>();
for (const record of records) {
if (
record.judge !== judge ||
record.rubricVersion !== RUBRIC_VERSION ||
record.promptVersion !== PROMPT_VERSION
)
continue;
const prior = latest.get(record.source.path);
if (!prior || prior.scoredAt < record.scoredAt)
latest.set(record.source.path, record);
}
return [...latest.values()];
}
export async function acquireScanLock(
stateDir = iqStateDirectory(),
): Promise<() => Promise<void>> {
await mkdir(stateDir, { recursive: true, mode: 0o700 });
const path = join(stateDir, "scan.lock");
for (let attempt = 0; attempt < 2; attempt++) {
const nonce = randomUUID();
try {
const file = await open(path, "wx", 0o600);
await file.writeFile(
`${JSON.stringify({ pid: process.pid, nonce, createdAt: new Date().toISOString() })}\n`,
"utf8",
);
await file.sync();
await file.close();
return async () => {
try {
const current: unknown = JSON.parse(await readFile(path, "utf8"));
if (
typeof current === "object" &&
current !== null &&
"nonce" in current &&
current.nonce === nonce
)
await rm(path, { force: true });
} catch {
// Another process may already have reclaimed the lock.
}
};
} catch (error) {
if (!(isNodeError(error) && error.code === "EEXIST")) throw error;
const owner = await readLockOwner(path);
if (!owner || processExists(owner.pid))
throw new Error(
owner
? `IQ scan already running in process ${owner.pid}`
: "IQ scan lock is unreadable",
);
await rm(path, { force: true });
}
}
throw new Error("Unable to acquire IQ scan lock");
}
async function readLockOwner(
path: string,
): Promise<{ pid: number } | undefined> {
try {
const value: unknown = JSON.parse(await readFile(path, "utf8"));
return typeof value === "object" &&
value !== null &&
"pid" in value &&
typeof value.pid === "number" &&
Number.isInteger(value.pid)
? { pid: value.pid }
: undefined;
} catch {
return undefined;
}
}
function processExists(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (error) {
return !(isNodeError(error) && error.code === "ESRCH");
}
}
function isNodeError(error: unknown): error is NodeJS.ErrnoException {
return error instanceof Error && "code" in error;
}
function boundedError(error: unknown): string {
const message = error instanceof Error ? error.message : String(error);
return message.replaceAll(/\s+/g, " ").slice(0, 240);
}