import { createHash } from "node:crypto"; import { appendFileSync, chmodSync, existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs"; import { segmentsOf, streamEnd } from "./log-rotation.ts"; import { join } from "node:path"; import { isModelEvidence, MODEL_EVIDENCE, parseEventLine, turnEdits, type TurnEdits, readEvents, scanEventLines, type ModelEvidence, type RoleIdentity, type StampedEvent } from "./events.ts"; import { safeModelLabel } from "../omniroute/usage.ts"; import { hubHome } from "./project.ts"; import { ADDONS, addonState, type Addon, type AddonName } from "./tooling.ts"; import { MIN_ATTEMPTS, mulberry32 } from "./bench.ts"; import { UNKNOWN_MEMORY_FIGURES } from "./research-memory.ts"; import { addPersonEvent, emptyPersonCounts, isPersonEvent, personCoverage, personFigures, personTask, startsAttribution, type PersonCounts } from "./person-figures.ts"; import { closedId, journalFigures, mergeBlock, NO_EVIDENCE, reviewBlock, specsBlock, type CancelCause, type CohortKind, type DeliveryBlock, type EditGovernanceBlock, editGovernanceBlock, type HandoffsBlock, type MemoryBlock, type MergeBlock, type PersonBlock, type ResearchEvidence, type ReviewBlock, type SpecsBlock, cancelCauseOf } from "./research-record.ts"; export type { CancelCause, CohortKind, DeliveryBlock, EditGovernanceBlock, HandoffsBlock, MemoryBlock, MergeBlock, PersonBlock, ResearchEvidence, ReviewBlock, SpecsBlock } from "./research-record.ts"; /** * #247: opt-in research records of how tasks went, built only from `events.jsonl` (ids, states, counts, tokens), so the * live writer and `ahub research backfill` produce the same records. Never a title, detail, plan, note, path, message * body or check output: the events carry none of those. */ /** v1 rows (approved tasks only, no review, delivery, merge, specs, memory or person block) stay readable; every row written now is v2 (#1277). */ export const RESEARCH_SCHEMA_V1 = "agent-hub.research/v1"; export const RESEARCH_SCHEMA = "agent-hub.research/v2"; export type ResearchSchema = typeof RESEARCH_SCHEMA | typeof RESEARCH_SCHEMA_V1; const SCHEMAS: readonly string[] = [RESEARCH_SCHEMA_V1, RESEARCH_SCHEMA]; export const LABELS = ["ok", "regressed", "reverted", "incomplete", "wrong", "abandoned"] as const; export type Label = (typeof LABELS)[number]; /** A person's later verdict that turns an approved task into a failure. */ const FAILED: ReadonlySet = new Set(["regressed", "reverted", "incomplete", "wrong", "abandoned"]); export interface OwnerModel { model: string; evidence: ModelEvidence } export interface PeerUsage { input: number | null; output: number | null; cacheRead: number | null; total: number | null } export interface TaskRecord { schema: ResearchSchema; kind: "task"; project: string; task: number; profile?: string; profileClass?: string; release?: number | null; priority?: number | null; plannedStart?: number | null; due?: number | null; role?: string; roleIdentity?: { id: string; layer: "shipped" | "project"; hash: string }; /** Native preamble preparations frozen at each attributed turn's start, never proof of model consumption. */ sessionRoles?: { peer: string; turn: string; roles: RoleIdentity[] | null }[]; class: string | null; pii: boolean; /** #1277 AC6: every task in a terminal board state has a record. A v1 row is always `approved`. Statistics about approved tasks filter on this. */ outcome: "approved" | "cancelled"; /** The proposal time also tells a task from an earlier one with the same id after `ahub reset --all`. */ createdAt: string | null; startedAt: string | null; /** Null on a cancelled record. */ approvedAt: string | null; /** When the task reached its terminal state (v2); a v1 row reads as its `approvedAt`. */ closedAt?: string; /** From the first `in_progress` to the terminal state; null when the start is not in the events. */ wallMs: number | null; /** Sum of the attributed turns' durations, the turns still open at the approval included. */ activeMs: number; /** Owners in the order they held the task. */ owners: string[]; reviewer: string | null; /** Times the task went to review, was sent back, passed or failed its check, was reported done. */ reviewRounds: number; changesRequested: number; checkPassed: number; checkFailed: number; dones: number; /** Owner changes after the first owner, and the same counted by the board's move reason. */ reassignments: number; reassignedBy: Record; /** Approved on its first review with no failed check. */ firstPass: boolean; stuck: number; overlaps: number; conflicts: number; tests: { pass: number; fail: number }; /** Attributed tokens per peer and per #200 attribution rule; unattributed tokens are in no record. */ tokens: { total: number; byPeer: Record; byAttribution: Record }; usage: Record; /** Provider-reported total tokens per served (else requested) model. */ usageByModel: Record; turns: number; filesChanged: number; /** Model routes and served models seen for the task's attributed requests. */ models: string[]; /** * #1402: the models of the turns attributed to the task's owners (the owner's own `turn_end` model, then the `servedModel` / `requestedModel` of its `usage` events), each with its * strongest evidence grade for this task. A reviewer's model is never in it. Absent on a record written before #1402, which reads as unknown; `[]` when nothing was observed. */ ownerModels?: OwnerModel[]; writer: { version: string; source: "live" | "backfill" }; /** #248: the add-ons each peer that worked on the task had at its latest attach; a peer missing here is unknown. */ tooling?: Record; /** #248, with `tooling`: every peer with an event attributed to the task, fingerprinted or not. */ peers?: string[]; /** #258 AC11: task briefs handed over for it, and how many of them carried a hub-memory fail note; absent without briefs. */ briefs?: { delivered: number; withFail: number }; /** #1277 (v2). Every block is a count, a duration or a closed value; a value that cannot be derived is null and counted as unknown by the quality report, never 0. */ /** Only on a cancelled record: an explicit closed cause the board retains, else `unknown`. Never inferred from a decline, an escalation or the cancellation note. */ cancelCause?: CancelCause; /** Intermediate declines and escalations (history events, not terminal), counted on every record next to `reassignments`. */ declines?: number; escalations?: number; review?: ReviewBlock; delivery?: DeliveryBlock; merge?: MergeBlock; specs?: SpecsBlock; memory?: MemoryBlock; person?: PersonBlock; /** Persisted idle-ladder entries on the task's board history (the stall table itself is cleared when a task closes); null without the board. */ stalls?: number | null; handoffs?: HandoffsBlock; cohort?: CohortKind; /** #1556 T2: text-free edit governance counts folded from `turn_end.edits`; a row written before it has none and reads as unknown. */ edits?: EditGovernanceBlock; } /** A record carries merge figures when any of them is known. */ const mergeKnown = (r: TaskRecord): boolean => !!r.merge && (r.merge.ciRuns !== null || r.merge.ciReruns !== null || r.merge.githubReviews !== null || r.merge.approvedToMergedMs !== null); /** True when `next` has merge figures the held record of the same task lacks. */ export const fillsMerge = (held: TaskRecord, next: TaskRecord): boolean => next.schema === RESEARCH_SCHEMA && !mergeKnown(held) && mergeKnown(next); /** #1402: a held v2 row written before `ownerModels` existed has no such field; a rebuilt row that can prove an owner model from the surviving events replaces it (a held row that has the field is final). */ export const fillsOwnerModels = (held: TaskRecord, next: TaskRecord): boolean => next.schema === RESEARCH_SCHEMA && held.ownerModels === undefined && (next.ownerModels?.length ?? 0) > 0; /** The latest record of each task (a later row of the same task replaces an earlier one), in order of first appearance. */ export function latestTaskRecords(records: readonly ResearchRecord[]): TaskRecord[] { const latest = new Map(); for (const r of records) if (r.kind === "task") latest.set(recordKey(r), r); return [...latest.values()]; } /** A person's later verdict on one task record: `createdAt` binds it to that task, not a later one with the same id. `by`: the agent that labelled its own task (#933); absent for the person. */ export interface LabelRecord { schema: ResearchSchema; kind: "label"; project: string; task: number; createdAt: string; label: Label; at: string; by?: string } export type ResearchRecord = TaskRecord | LabelRecord; /** The store name for a project: a hash of its id, never its path. */ export const projectKey = (projectId: string): string => createHash("sha256").update(projectId).digest("hex").slice(0, 16); export const researchDir = (home = hubHome()): string => join(home, "research"); export const researchFile = (projectId: string, home = hubHome()): string => join(researchDir(home), `${projectKey(projectId)}.jsonl`); /** One task across every record about it: a task id is reused after `ahub reset --all`, its proposal time is not. */ export const recordKey = (r: { project: string; task: number; createdAt: string | null; approvedAt?: string | null; closedAt?: string }): string => `${r.project}#${r.task}@${r.createdAt ?? r.approvedAt ?? r.closedAt ?? ""}`; /** When a record's task closed: v2 says so, a v1 row is approved-only and closed at its approval. */ export const closedAtOf = (r: TaskRecord): string | null => r.closedAt ?? r.approvedAt; type V2Fields = "closedAt" | "cancelCause" | "declines" | "escalations" | "review" | "delivery" | "merge" | "specs" | "memory" | "person" | "stalls" | "handoffs" | "cohort" | "edits"; type Acc = Omit & { models: Set; /** #1402: peer -> model -> strongest grade, every peer that worked on the task; the owners are picked at the end. */ observed: Map>; approvedAt: string | null; lastState: string | null; tooling: Record; peers: Map; briefs: { delivered: number; withFail: number }; /** #1278: the counts of the four attributed person events; joined with whether the log covers the task at the end. */ person: PersonCounts; /** #1277: what the events alone say; the board and journal evidence is joined at the end. */ cancelledAt: string | null; declines: number; escalations: number; lastDoneMs: number | null; envelopes: number; dropped: { fyi: number; hop: number }; briefNotes: number; briefFails: number; cohort: "silent" | "advisory" | null; /** #1556 T2: each attributed, non-private turn's validated `edits`, in log order. */ editTurns: TurnEdits[]; }; /** Keyed by peer ids, model names and reasons, any of which may be `constructor` or `__proto__`: no prototype to inherit from. */ const keyed = (): Record => Object.create(null) as Record; const blank = (task: number): Acc => ({ task, class: null, pii: false, createdAt: null, startedAt: null, activeMs: 0, owners: [], reviewer: null, reviewRounds: 0, changesRequested: 0, checkPassed: 0, checkFailed: 0, dones: 0, reassignments: 0, reassignedBy: keyed(), stuck: 0, overlaps: 0, conflicts: 0, tests: { pass: 0, fail: 0 }, tokens: { total: 0, byPeer: keyed(), byAttribution: keyed() }, usage: keyed(), usageByModel: keyed(), turns: 0, filesChanged: 0, models: new Set(), observed: new Map(), approvedAt: null, lastState: null, tooling: keyed(), peers: new Map(), briefs: { delivered: 0, withFail: 0 }, person: emptyPersonCounts(), cancelledAt: null, declines: 0, escalations: 0, lastDoneMs: null, envelopes: 0, dropped: { fyi: 0, hop: 0 }, briefNotes: 0, briefFails: 0, cohort: null, editTurns: [] }); const add = (current: number | null, value: unknown): number | null => typeof value === "number" && Number.isFinite(value) ? (current ?? 0) + value : current; /** Strongest grade first: `served`, `session`, `configured`. */ const gradeRank = (grade: ModelEvidence): number => MODEL_EVIDENCE.indexOf(grade); /** Keep the strongest grade seen for a peer's model. A label `safeModelLabel` refuses or an unknown grade is ignored, never repaired. */ function observeModel(a: { observed: Map> }, peer: string, model: unknown, grade: unknown): void { const label = safeModelLabel(model); // "unknown" is the placeholder some adapters write when a request named no model, not a model: it stays an unobserved turn, so it can never merge with the no-model row. if (label === undefined || label.toLowerCase() === "unknown" || !isModelEvidence(grade)) return; const models = a.observed.get(peer) ?? new Map(); const held = models.get(label); if (held === undefined || gradeRank(grade) < gradeRank(held)) models.set(label, grade); a.observed.set(peer, models); } const bump = (counts: Record, key: string, n = 1) => { counts[key] = (counts[key] ?? 0) + n; }; /** * One record per task that reached a terminal board state in `events`: approved, or cancelled (#1277 AC6). Approval is final on the board, so everything attributed to the task * counts, also after the approval: the turn that approved it ends later, and its usage arrives after that. The live * writer therefore waits for those turns (daemon `recordResearch`); backfill reads to the end of the file. `evidence` (the board's history and the delivery journal, * read-only and closed fields only, `readEvidence`) fills the review, merge, spec and delivery-state blocks; without it those fields are null, not 0. A task that was approved * and later reopened keeps its approved record, as before. */ export function taskRecords(events: StampedEvent[], projectId: string, writer: TaskRecord["writer"], evidence: ResearchEvidence = NO_EVIDENCE, start?: FoldStart): TaskRecord[] { const tasks = new Map(), earlier: Acc[] = []; // #1555 AC5: a fold over a slice of the log starts from what the events before the slice said (`ResearchTail`); a fold over the whole log starts empty and is the reference a slice must equal. const carry = start ? start.carry.clone() : new FoldCarry(); const acc = (id: number) => { let a = tasks.get(id); if (!a) tasks.set(id, a = blank(id)); return a; }; const seenUsage = new Set(); // The cross-task state is `carry`: whether briefs and person attribution are reported at all (#1278: a task that began before the first attributing hub run has an unknown person block), and the // fingerprints. A fingerprint belongs to one attachment of its peer: from a state event that brings it online to the next offline. Detection settles in the background, so it can arrive after the peer's first work in that attachment. const { attach, tooling } = carry; /** A peer that worked on the task carries the fingerprint of the attachment it worked in. */ /** * `acted`: the peer did something for the task (an attributed turn, tokens, the actor of a board move). A peer only * named on a move (the owner or reviewer an approval lists) joins the task once and never moves to a later * attachment, where it did no work. */ const involve = (a: Acc, peer: string | null | undefined, acted = true) => { if (!peer || peer === "hub" || peer === "user" || (!acted && a.peers.has(peer))) return; const now = attach.get(peer) ?? 0, f = tooling.get(peer); a.peers.set(peer, now); if (f?.attach === now) a.tooling[peer] = f.addons; else delete a.tooling[peer]; // a fingerprint of an earlier attachment does not describe this work: unknown until one comes }; for (const e of events) { if (e.type === "route" && e.decisionTarget === "judge") continue; carry.observe(e); if (e.type === "hub_start" || e.type === "state") continue; if (e.type === "tooling") { const now = attach.get(e.peer) ?? 0; for (const a of tasks.values()) if (a.peers.get(e.peer) === now) a.tooling[e.peer] = e.addons; continue; } if (e.type === "envelope") { // An envelope names its task as a string; a count of them, and of the ones the bus dropped, is all the record keeps. if (typeof e.task === "string" && /^[1-9]\d{0,9}$/.test(e.task)) { const a = acc(Number(e.task)); a.envelopes++; if (e.dropped === "fyi" || e.dropped === "hop") a.dropped[e.dropped]++; } continue; } if (e.type === "cohort") { for (const id of e.tasks) if (Number.isSafeInteger(id) && id > 0) { const a = acc(id); if (e.silent) a.cohort = "silent"; else a.cohort ??= "advisory"; } continue; } if (e.type === "task") { const proposed = e.event === "proposed" || e.event === "backlog pulled"; // Ids restart after `ahub reset --all` archives the events, but a file that kept both starts the task anew. if ((e.event === "proposed" && tasks.has(e.id)) || (e.event === "backlogged" && tasks.has(e.id))) { earlier.push(tasks.get(e.id)!); tasks.delete(e.id); } const a = acc(e.id); for (const field of ["release", "priority", "plannedStart", "due"] as const) if (Object.hasOwn(e, field)) a[field] = e[field]; a.class = e.class; if (e.role && a.role === undefined) { a.role = e.role; if (e.event === "proposed" && e.roleIdentity) a.roleIdentity = e.roleIdentity; } if (e.profile) { a.profile = e.profile; a.profileClass = e.profileClass; } if (e.pii) a.pii = true; if (proposed && e.role === a.role && e.roleIdentity && a.roleIdentity === undefined) a.roleIdentity = e.roleIdentity; if (e.owner && e.owner !== a.owners.at(-1)) { if (a.owners.length) { a.reassignments++; bump(a.reassignedBy, e.reason ?? "none"); } a.owners.push(e.owner); } if (e.reviewer) a.reviewer = e.reviewer; if (proposed) a.createdAt ??= e.at; if (e.state === "in_progress") a.startedAt ??= e.at; if (e.event === "done") { a.dones++; if (a.approvedAt === null) a.lastDoneMs = Date.parse(e.at); } if (e.event === "declined") a.declines++; if (e.event === "escalated") a.escalations++; if (e.event === "check passed") a.checkPassed++; if (e.event === "check failed") a.checkFailed++; if (e.state === "in_review" && a.lastState !== "in_review") a.reviewRounds++; if (e.state === "changes_requested" && a.lastState !== "changes_requested") a.changesRequested++; if (e.state === "approved") a.approvedAt ??= e.at; if (e.state === "cancelled" && a.lastState !== "cancelled") a.cancelledAt = e.at; a.lastState = e.state; involve(a, e.by); involve(a, e.owner, false); involve(a, e.reviewer, false); continue; } if (isPersonEvent(e)) { // Before the generic path on purpose: a permission or a question does not make its peer a worker on the task (`peers`, `tooling`). const owner = personTask(e); if (owner !== undefined) { const a = acc(owner); if (e.pii) a.pii = true; addPersonEvent(a.person, e); } continue; } const task = "task" in e && typeof e.task === "number" ? e.task : undefined; if (task === undefined) continue; const a = acc(task); if ("pii" in e && e.pii === true) a.pii = true; if ("peer" in e && typeof e.peer === "string") involve(a, e.peer); if (e.type === "tokens") { a.tokens.total += e.n; bump(a.tokens.byPeer, e.peer, e.n); bump(a.tokens.byAttribution, e.attribution ?? "unknown", e.n); } else if (e.type === "turn_end") { a.turns++; a.activeMs += e.ms; a.filesChanged += e.files ?? 0; if (e.model !== undefined) observeModel(a, e.peer, e.model, e.modelEvidence); if (e.edits !== undefined && e.pii !== true) { const edits = turnEdits(e.edits); if (edits) a.editTurns.push(edits); } // a PII turn contributes nothing if (e.preparedRoles !== undefined) (a.sessionRoles ??= []).push({ peer: e.peer, turn: e.turn, roles: e.preparedRoles?.map(role => ({ id: role.id, layer: role.layer, hash: role.hash })) ?? null }); } else if (e.type === "usage") { const key = usageKey(e); if (seenUsage.has(key) || start?.usageSeenBefore?.(key)) continue; seenUsage.add(key); const u = a.usage[e.peer] ??= { input: null, output: null, cacheRead: null, total: null }; u.input = add(u.input, e.inputTokens); u.output = add(u.output, e.outputTokens); u.cacheRead = add(u.cacheRead, e.cacheReadTokens); u.total = add(u.total, e.totalTokens); const model = e.servedModel ?? e.requestedModel; // The provider named the served model for these responses; the requested one is only what the hub asked for. if (e.servedModel) observeModel(a, e.peer, e.servedModel, "served"); else observeModel(a, e.peer, e.requestedModel, "configured"); if (model) a.models.add(String(model)); if (typeof e.totalTokens === "number" && Number.isFinite(e.totalTokens)) bump(a.usageByModel, String(model ?? "unknown"), e.totalTokens); } else if (e.type === "route") a.models.add(e.route); else if (e.type === "route_outcome") { if (e.next?.tests === "pass") a.tests.pass++; if (e.next?.tests === "fail") a.tests.fail++; } else if (e.type === "memory_brief") { a.briefs.delivered++; if (e.fails > 0) a.briefs.withFail++; a.briefNotes += (Number.isSafeInteger(e.native) ? e.native : 0) + (Number.isSafeInteger(e.claudeMem) ? e.claudeMem : 0); a.briefFails += Number.isSafeInteger(e.fails) ? e.fails : 0; } else if (e.type === "stuck") a.stuck++; else if (e.type === "overlap") a.overlaps++; else if (e.type === "conflict") a.conflicts++; } const out: TaskRecord[] = []; for (const a of [...earlier, ...tasks.values()]) { // Approved wins over a later reopening (the record the live writer stored at the approval); otherwise the task must end cancelled. const outcome: "approved" | "cancelled" | undefined = a.approvedAt ? "approved" : a.lastState === "cancelled" && a.cancelledAt ? "cancelled" : undefined; if (!outcome) continue; const { person, approvedAt, lastState: _state, models, observed, tooling: fingerprints, peers, briefs, cancelledAt, declines, escalations, lastDoneMs, envelopes, dropped, briefNotes, briefFails, cohort, editTurns, ...rest } = a; const closedAt = (outcome === "approved" ? approvedAt : cancelledAt)!; const start = a.startedAt ? Date.parse(a.startedAt) : NaN, end = Date.parse(closedAt); const task = evidence.tasks.get(a.task), board = evidence.board; const began = a.createdAt ? Date.parse(a.createdAt) : a.startedAt ? Date.parse(a.startedAt) : NaN; const covered = personCoverage(carry.personReportingSince, began); const ownerFamily = closedId(a.owners.at(-1) ? evidence.familyOf?.(a.owners.at(-1)!) : undefined); const approvedMs = outcome === "approved" ? Date.parse(approvedAt!) : null; const created = a.createdAt ? Date.parse(a.createdAt) : NaN; const journal = journalFigures(evidence, a.task, Number.isFinite(created) ? created : null, Number.isFinite(end) ? end : 0); const review = reviewBlock(task, board, ownerFamily, a.pii); // The events say whether the task went to review at all; a board that cannot say leaves the round count unknown. out.push({ schema: RESEARCH_SCHEMA, kind: "task", project: projectKey(projectId), ...rest, outcome, approvedAt: approvedAt ?? null, closedAt, wallMs: Number.isFinite(start) && Number.isFinite(end) && end >= start ? end - start : null, firstPass: outcome === "approved" && a.changesRequested === 0 && a.checkFailed === 0 && a.reviewRounds <= 1, models: [...models].sort(), ownerModels: ownerModelsOf(observed, a.owners), writer, ...(Object.keys(fingerprints).length ? { tooling: fingerprints, peers: [...peers.keys()].sort() } : {}), ...(briefs.delivered ? { briefs } : {}), ...(outcome === "cancelled" ? { cancelCause: task?.history.findLast(entry => entry.event === "cancelled")?.cause ?? "unknown" } : {}), declines, escalations, review, delivery: { count: envelopes, ...journal, dropped: { fyi: dropped.fyi, hop: dropped.hop } }, merge: mergeBlock(task, lastDoneMs, approvedMs), specs: specsBlock(task, a.pii), // A task with no brief is a known 0 only when the log shows briefs were being reported at all (memory on); otherwise nothing says whether one was built. memory: { briefs: briefs.delivered || (carry.briefReporting ? 0 : null), briefNotes: briefs.delivered ? briefNotes : carry.briefReporting ? 0 : null, fails: briefs.delivered ? briefFails : carry.briefReporting ? 0 : null, ...(evidence.memory?.(a.task) ?? UNKNOWN_MEMORY_FIGURES) }, person: personFigures(person, covered), stalls: task && board ? task.history.filter(entry => entry.sweep).length : null, handoffs: task?.handoffs ? { in: task.handoffs.in, out: task.handoffs.out } : { in: null, out: null }, cohort: cohort ?? "none", edits: editGovernanceBlock(editTurns) }); } return out.sort((x, y) => closedAtOf(x)!.localeCompare(closedAtOf(y)!) || x.task - y.task); } /** The key one usage row is counted once under, across every task of the log. */ const usageKey = (e: { peer: string; source: string; id: string }): string => `${e.peer}\0${e.source}\0${e.id}`; /** * #1555 AC5: the state `taskRecords` carries from one event to the next across tasks, which a fold over a slice of the log must start with: which peers are attached and their add-on fingerprints, whether the * log reports briefs at all, and the first hub run that attributes person events. Everything else the fold keeps is per task, or per usage key (`FoldStart.usageSeenBefore`). */ export class FoldCarry { attach = new Map(); online = new Set(); tooling = new Map(); briefReporting = false; personReportingSince: number | null = null; /** The only writer: an event that is not one of these changes none of it. */ observe(e: StampedEvent): void { if (e.type === "hub_start") { // A crash writes no offline: a new run is a new attachment, and no fingerprint from before it describes later work. this.online.clear(); this.tooling.clear(); if (startsAttribution(e)) this.personReportingSince ??= Date.parse(e.at); } else if (e.type === "state") { if (e.state === "offline") this.online.delete(e.peer); else if (!this.online.has(e.peer)) { this.online.add(e.peer); this.attach.set(e.peer, (this.attach.get(e.peer) ?? 0) + 1); } } else if (e.type === "tooling") this.tooling.set(e.peer, { attach: this.attach.get(e.peer) ?? 0, addons: e.addons }); // A brief counts once it names a task, as the fold's own task-attributed path does. else if (e.type === "memory_brief" && typeof e.task === "number") this.briefReporting = true; } clone(): FoldCarry { const c = new FoldCarry(); c.attach = new Map(this.attach); c.online = new Set(this.online); c.tooling = new Map(this.tooling); c.briefReporting = this.briefReporting; c.personReportingSince = this.personReportingSince; return c; } } /** Where a fold over a slice starts: the carry as of the slice's first byte, and whether a usage key was already counted before it. */ export interface FoldStart { carry: FoldCarry; usageSeenBefore?: (key: string) => boolean } /** The type of a line the hub wrote (`{"v":1,"at":"...","type":"x",...`), read without parsing it; undefined for any other shape, which is then parsed. */ const lineType = (line: string): string | undefined => /^\{"v":\d+,"at":"[^"]*","type":"([a-z_]+)"/.exec(line)?.[1]; /** The types whose events change what a later slice must start with, or where a task's current incarnation begins. Every other line is skipped unparsed while the tail catches up. */ const TRACKED = new Set(["hub_start", "state", "tooling", "memory_brief", "task", "usage"]); /** * #1555 AC5: the live writer's reader of `events.jsonl`. `taskRecords` over the whole file and over the slice from a task's first event give the same record for that task, so the live writer reads * only that slice. What a slice cannot see is carried: one catch-up pass over the bytes appended since the last closure (the first closure after a start reads the file once) keeps, per task id, the * byte offset of its latest proposal and the `FoldCarry` as of that offset, plus the offset each usage key was first counted at. A task the tail has no start for (its proposal is not in the file, or it * was evicted) is read whole, which is also what `ahub research backfill` does. * ponytail: `firstUsage` holds one entry per usage row of the log (about 74 000 rows in a 180 MB log), `starts` at most `maxTasks` carries; `events.jsonl` rotates by size (#1546), which bounds both; the upgrade path past that is to keep the keys in `hub.db`. */ export class ResearchTail { private carry = new FoldCarry(); private scanned = 0; private firstUsage = new Map(); private starts = new Map(); /** Ids the log starts more than once (`ahub reset --all` kept both): `taskRecords` also returns the earlier incarnation's record, so such an id is read whole, exactly as before. */ private restarted = new Set(); /** Every id the log has started, however many tasks the carry map keeps: an evicted start must not hide that a later one is a restart. One small integer per task. */ private started = new Set(); /** The byte range the last `events` call parsed, for tests and diagnostics: `from` 0 means a whole-file read. */ lastRead: { from: number; to: number } = { from: 0, to: 0 }; constructor(readonly file: string, readonly maxTasks = 512) {} private reset(): void { this.carry = new FoldCarry(); this.scanned = 0; this.firstUsage.clear(); this.starts.clear(); this.restarted.clear(); this.started.clear(); } private catchUp(): void { const segments = segmentsOf(this.file); // #1546: an offset is a position in the stream of rotated segments plus the live file, so a rotation moves no offset if (!segments.length) { this.reset(); return; } if (streamEnd(segments) < this.scanned) this.reset(); // the log was archived and started again this.scanned = scanEventLines(this.file, this.scanned, (line, offset) => { const type = lineType(line); if (type !== undefined && !TRACKED.has(type)) return; const e = parseEventLine(line); if (e === undefined) return; if (e.type === "task" && (e.event === "proposed" || e.event === "backlogged")) { // The same two events start a task anew in `taskRecords`, so what came before them belongs to an earlier incarnation. if (this.started.has(e.id)) this.restarted.add(e.id); this.started.add(e.id); this.starts.delete(e.id); this.starts.set(e.id, { offset, carry: this.carry.clone() }); if (this.starts.size > this.maxTasks) this.starts.delete(this.starts.keys().next().value!); } else if (e.type === "usage" && typeof e.task === "number") { const key = usageKey(e); if (!this.firstUsage.has(key)) this.firstUsage.set(key, offset); } this.carry.observe(e); }); } /** The events `taskRecords` needs for `taskId`, and where its fold starts (undefined for a whole-file read). A quota row is skipped: no field of a record reads one. */ events(taskId: number): { events: StampedEvent[]; start?: FoldStart } { this.catchUp(); let held = this.restarted.has(taskId) ? undefined : this.starts.get(taskId); // A start whose bytes retention dropped (its segment is gone) cannot be sliced: read what the log still holds, which is what `ahub research backfill` does. if (held && held.offset < (segmentsOf(this.file)[0]?.start ?? 0)) held = undefined; if (!held) { this.lastRead = { from: 0, to: this.scanned }; return { events: readEvents(this.file) }; } const events: StampedEvent[] = []; scanEventLines(this.file, held.offset, line => { if (lineType(line) === "quota") return; const e = parseEventLine(line); if (e !== undefined) events.push(e); }, this.scanned); this.lastRead = { from: held.offset, to: this.scanned }; return { events, start: { carry: held.carry, usageSeenBefore: key => (this.firstUsage.get(key) ?? Infinity) < held.offset } }; } } /** The observations of the peers that held the task, one entry per model with its strongest grade, sorted by model. A peer that only reviewed contributes nothing. */ function ownerModelsOf(observed: Map>, owners: readonly string[]): OwnerModel[] { const out = new Map(); for (const owner of new Set(owners)) for (const [model, grade] of observed.get(owner) ?? []) { const held = out.get(model); if (held === undefined || gradeRank(grade) < gradeRank(held)) out.set(model, grade); } return [...out].map(([model, evidence]) => ({ model, evidence })).sort((x, y) => x.model < y.model ? -1 : x.model > y.model ? 1 : 0); } /** Every record in one store file; a line that does not parse is skipped. */ export function readStore(file: string): ResearchRecord[] { if (!existsSync(file)) return []; return readFileSync(file, "utf8").split("\n").flatMap((line) => { if (!line.trim()) return []; try { const r = JSON.parse(line); return SCHEMAS.includes(r?.schema) ? [normalize(r)] : []; } catch { return []; } }); } /** A v1 task row predates `outcome` and was written only at an approval, so it reads as approved; the file itself is never rewritten. */ function normalize(r: ResearchRecord): ResearchRecord { return r.kind === "task" && r.schema === RESEARCH_SCHEMA_V1 && r.outcome === undefined ? { ...r, outcome: "approved" } : r; } /** This project's store, or every project's with `all`. */ export function readStores(projectId: string | undefined, home = hubHome()): ResearchRecord[] { if (projectId) return readStore(researchFile(projectId, home)); const dir = researchDir(home); if (!existsSync(dir)) return []; return readdirSync(dir).filter((name) => name.endsWith(".jsonl")).sort().flatMap((name) => readStore(join(dir, name))); } /** Append task records the store does not hold yet (same task, by `recordKey`), and labels; returns how many were written. */ export function appendRecords(projectId: string, records: ResearchRecord[], home = hubHome()): number { if (!records.length) return 0; const file = researchFile(projectId, home); mkdirSync(researchDir(home), { recursive: true, mode: 0o700 }); chmodSync(researchDir(home), 0o700); // mkdir's mode applies only when it creates the directory // A v2 row replaces a held v1 row of the same task (readers keep the latest per task). A held v2 row is final, as a held row always was, with one exception: the live writer // records a task at its approval and the guarded merge writes its receipt later, so a later pass may append the same task with the merge figures it could not know then. #1402: likewise a row with no `ownerModels` field, which `ahub research backfill` fills from the events that still carry a model. const held = new Map(readStore(file).flatMap((r) => r.kind === "task" && r.schema === RESEARCH_SCHEMA ? [[recordKey(r), r] as const] : [])); const added = records.filter((r) => r.kind === "label" || r.schema !== RESEARCH_SCHEMA || !held.has(recordKey(r)) || fillsMerge(held.get(recordKey(r))!, r) || fillsOwnerModels(held.get(recordKey(r))!, r)); if (!added.length) return 0; appendFileSync(file, added.map((r) => JSON.stringify(r)).join("\n") + "\n", { mode: 0o600 }); chmodSync(file, 0o600); return added.length; } /** * The record a person's label is for. `created` (a record's `createdAt`, from `ahub research export`) names one exactly. * Otherwise the current board's task with that id, found by its proposal in `events`, so a label never lands on an * earlier task with the same id; an id this hub's events do not have (a task from before `ahub reset --all`) is the * store's only record with that id. Throws why there is none, or which ones to choose from. */ export function labelTarget(records: ResearchRecord[], events: StampedEvent[], task: number, created?: string): TaskRecord { // A record without a proposal time (its proposal was not in the events) cannot be told apart, so it takes no label. // A label is a verdict on an approved task: a cancelled record takes none. // One candidate per task: a later revision of a record (the merge figures filled in, or a v2 row over a v1 one) is the same task, and listing it twice would refuse an unambiguous historical label. const mine = latestTaskRecords(records).filter((r) => r.outcome === "approved" && r.task === task && r.createdAt !== null); if (created !== undefined) { return mine.find((r) => r.createdAt === created) ?? fail(`no research record for task #${task} proposed at ${created}${mine.length ? ` (it has: ${mine.map((r) => r.createdAt).join(", ")})` : ""}`); } const creation = events.findLast(e => e.type === "task" && e.id === task && ["proposed", "backlogged"].includes(e.event)); const proposed = creation?.type === "task" && creation.event === "backlogged" ? events.slice(events.indexOf(creation) + 1).find(e => e.type === "task" && e.id === task && e.event === "backlog pulled") : creation; if (creation?.type === "task" && creation.event === "backlogged" && !proposed) fail(`task #${task} is backlog and has no execution proposal; name an earlier record with --created`); if (proposed) { return mine.find((r) => r.createdAt === proposed.at) ?? fail(`task #${task} has no research record yet: it is not approved, its record still waits for the turns that approved it, or it was approved while research was off (ahub research backfill builds that one)${mine.length ? `; an earlier task #${task} from before a reset is labelled with --created ${mine.map((r) => r.createdAt).join(" or ")}` : ""}`); } if (mine.length === 1) return mine[0]!; if (!mine.length) throw new Error(records.some((r) => r.kind === "task" && r.task === task) ? `task #${task}'s research record has no proposal time (its proposal was not in the events), so it takes no label` : `no research record for task #${task}`); throw new Error(`task #${task} is not on this hub's board and the store has ${mine.length} records with that id; name one with --created