import path from "node:path"; import { buildAutoresearchCandidateDecisionWorkbench } from "./runtime-candidate-decision.ts"; import { AUTORESEARCH_CANDIDATE_DECISION_TOOL_NAME, AUTORESEARCH_STATUS_TOOL_NAME, } from "./runtime-constants.ts"; import { computeAutoresearchDashboardImprovement, cssClassToken, escapeHtml, escapeScriptJson, formatAutoresearchDashboardNumber, renderAutoresearchDashboardShareSvg, } from "./runtime-dashboard-format.ts"; import { formatAutoresearchAuthorityHandoffLines, formatAutoresearchDashboardMode, formatAutoresearchGuidedCandidateJourneyLines, formatAutoresearchSetupGuideLines, } from "./runtime-dashboard-guidance.ts"; import { formatMetricThresholdValue } from "./runtime-format.ts"; import type { AutoresearchDashboardChartPoint, AutoresearchMatrixCampaignArtifactSummary, } from "./runtime-matrix.ts"; import { buildAutoresearchMetricReadinessReview } from "./runtime-metric-readiness.ts"; import type { AutoresearchRuntimeStatus, AutoresearchSegmentCloseout } from "./runtime-model.ts"; import { buildAutoresearchResumeApplyPlan, buildAutoresearchResumePlanFromStatus, } from "./runtime-resume-plan.ts"; export function renderAutoresearchDashboardHtml( status: AutoresearchRuntimeStatus, closeout: AutoresearchSegmentCloseout, matrixSummary: AutoresearchMatrixCampaignArtifactSummary, ): string { const segment = status.currentSegment; const candidateDecision = buildAutoresearchCandidateDecisionWorkbench({ cwd: closeout.cwd }); const candidateDecisionLabel = candidateDecision.candidate?.label ?? "no candidate bound yet"; const metricReadiness = candidateDecision.metricReadiness ?? buildAutoresearchMetricReadinessReview(status); const metricReadinessBlockers = metricReadiness.blockedReasons.length > 0 ? metricReadiness.blockedReasons.join("; ") : "none"; const metricReadinessChecklist = metricReadiness.checklist .slice(0, 4) .map((item) => `
✓ ${escapeHtml(item)}
`) .join("\n"); const resumePlan = buildAutoresearchResumePlanFromStatus(closeout.cwd, status); const resumePlanBlockers = resumePlan.blockingReasons.length > 0 ? resumePlan.blockingReasons.join("; ") : "none"; const resumeApplyPlan = buildAutoresearchResumeApplyPlan(closeout.cwd); const resumeApplyPlanBlockers = resumeApplyPlan.blockedReasons.length > 0 ? resumeApplyPlan.blockedReasons.join("; ") : "none"; const learningExportCall = `${AUTORESEARCH_STATUS_TOOL_NAME}({ cwd: ${JSON.stringify(closeout.cwd)}, action: "learning_export" })`; const learningKesAdapterCall = 'autoresearch_learning_kes_adapter({ action: "plan", packetPath: "" })'; const setupGuideLines = formatAutoresearchSetupGuideLines(closeout.cwd); const guidedCandidateJourneyLines = formatAutoresearchGuidedCandidateJourneyLines(closeout.cwd); const authorityHandoffLines = formatAutoresearchAuthorityHandoffLines(closeout.cwd); const generatedAt = new Date().toLocaleString(); const metricUnit = closeout.metricUnit || segment.metricUnit || ""; const metricName = closeout.metricName ?? segment.metricName ?? "metric"; const baselineMetric = closeout.baselineMetric ?? segment.baselineMetric; const bestMetric = closeout.bestMetric ?? segment.bestMetric; const direction = closeout.direction ?? segment.direction; const improvement = computeAutoresearchDashboardImprovement({ baseline: baselineMetric, best: bestMetric, direction, }); const rows = closeout.runs.slice(-80); const tableRows = rows .slice() .reverse() .map((run) => { const statusClass = cssClassToken(run.status); const decisionClass = cssClassToken(run.empiricalDecisionClass); return `${escapeHtml(String(run.iteration ?? "-"))}${escapeHtml(run.status)}${escapeHtml(run.runKind)}${escapeHtml(formatAutoresearchDashboardNumber(run.metric, metricUnit))}${escapeHtml(run.empiricalDecisionClass)}${escapeHtml(run.description)}`; }) .join("\n"); const runtimeChartPoints: AutoresearchDashboardChartPoint[] = rows.map((run) => ({ iteration: run.iteration, label: run.iteration === null ? run.runKind : `run ${run.iteration}`, status: run.status, runKind: run.runKind, decision: run.empiricalDecisionClass, metric: run.metric, description: run.description, source: "runtime_receipt", })); const matrixCellRows = matrixSummary.cells .map( (cell) => `${escapeHtml(cell.cellId)}${escapeHtml(cell.posture)}${escapeHtml(cell.laneProgress)}${escapeHtml(cell.selectedLaneId ?? "—")}${escapeHtml(cell.packetInventory.slice(0, 3).join(", ") || cell.selectedPacketPath || "—")}${escapeHtml(cell.nextLegalAction)}`, ) .join("\n"); const matrixNextLegalActions = matrixSummary.nextLegalActions .slice(0, 5) .map((action) => `
${escapeHtml(action)}
`) .join("\n"); const dashboardMode = formatAutoresearchDashboardMode(matrixSummary); const matrixMode = dashboardMode === "matrix_campaign"; const chartPoints = matrixMode ? matrixSummary.chart.points : runtimeChartPoints; const chartMode = matrixMode ? "matrix_campaign" : "runtime_segment"; const chartMetricName = matrixMode ? matrixSummary.chart.metricName : metricName; const chartMetricUnit = matrixMode ? matrixSummary.chart.metricUnit : metricUnit; const chartDirection = matrixMode ? matrixSummary.chart.direction : direction; const chartTitle = matrixMode ? "Matrix progress trajectory" : "Metric trajectory"; const chartSourceDescription = matrixMode ? matrixSummary.chart.sourceDescription : "Derived from local autoresearch runtime receipts for this cwd."; const chartEmptyMessage = matrixMode ? matrixSummary.chart.emptyMessage : "No local runtime metric data yet."; const matrixProgressCards = `
Matrix cells
${escapeHtml(`${matrixSummary.completedCellCount}/${matrixSummary.cellCount}`)}
Selected lanes
${escapeHtml(String(matrixSummary.selectedCellCount))}
Open review cells
${escapeHtml(String(matrixSummary.openCandidateReview.openCellCount))}
Exported packets
${escapeHtml(String(matrixSummary.exportedPacketCount))}
Visibility blockers
${escapeHtml(String(matrixSummary.exportVisibilityBlockers.value))}
`; const runtimeProgressCards = `
Baseline → Best
${escapeHtml(formatAutoresearchDashboardNumber(baselineMetric, metricUnit))} → ${escapeHtml(formatAutoresearchDashboardNumber(bestMetric, metricUnit))}
Improvement
${escapeHtml(improvement.label)}
Runs
${closeout.runCount}
Confidence
${escapeHtml(segment.confidence === null ? "—" : `${segment.confidence.toFixed(1)}×`)}
`; const shareSvg = renderAutoresearchDashboardShareSvg({ metricName, posture: status.empiricalPosture.classification, improvement: improvement.label, baseline: formatAutoresearchDashboardNumber(baselineMetric, metricUnit), best: formatAutoresearchDashboardNumber(bestMetric, metricUnit), recommendedNext: status.empiricalPosture.recommendedNextAction, }); return ` pi-autoresearch dashboard

🔬 pi-autoresearch live dashboard${segment.name ? `: ${escapeHtml(segment.name)}` : ""}

Auto-refreshes every 2s while Pi rewrites this file. Generated ${escapeHtml(generatedAt)}.
mode: ${escapeHtml(dashboardMode)} machine: ${escapeHtml(status.runtimeProjection.state)} promotion: ${status.empiricalPosture.promotionReady ? "ready" : "not ready"} posture: ${escapeHtml(status.empiricalPosture.classification)} cwd: ${escapeHtml(path.basename(closeout.cwd))}
Dashboard mode
${escapeHtml(dashboardMode)}
${matrixMode ? "Matrix campaign artifacts are the primary visible-progress source. Empty local runtime fields are auxiliary and do not mean the matrix has no progress." : "Local runtime receipts are the primary visible-progress source."}
${matrixMode ? matrixProgressCards : runtimeProgressCards} ${ matrixMode ? `
Matrix campaign progress
${escapeHtml(matrixSummary.metricName ?? "matrix campaign")}
cells=${escapeHtml(`${matrixSummary.completedCellCount}/${matrixSummary.cellCount}`)} · selected=${escapeHtml(String(matrixSummary.selectedCellCount))} · lanes=${escapeHtml(String(matrixSummary.candidateLaneCount))} · packets=${escapeHtml(String(matrixSummary.exportedPacketCount))}
latest=${escapeHtml(matrixSummary.latestArtifactPath ?? "none")}
${matrixNextLegalActions || '
No matrix next legal actions discovered yet.
'}
` : "" }
Open candidate review posture
${escapeHtml(String(matrixSummary.openCandidateReview.openCellCount))} open review cell(s)
${escapeHtml(matrixSummary.openCandidateReview.summary)}
${escapeHtml(matrixSummary.openCandidateReview.nextLegalAction)}
${escapeHtml(matrixSummary.openCandidateReview.boundary)}
Recommended next
${escapeHtml(matrixMode ? (matrixSummary.nextLegalActions[0] ?? "Review matrix campaign artifacts before acting.") : status.empiricalPosture.recommendedNextAction)}
${escapeHtml(matrixMode ? "Matrix-mode recommendation is derived from discovered local matrix artifacts; durable authority still requires owner review/evidence handoff." : status.empiricalPosture.summary)}
Candidate decision
${escapeHtml(candidateDecision.recommendedDecision)}
${escapeHtml(candidateDecisionLabel)} — ${escapeHtml(candidateDecision.recommendationReason)}
${escapeHtml(candidateDecision.exactNextCalls[0] ?? `${AUTORESEARCH_CANDIDATE_DECISION_TOOL_NAME}({ cwd: ${JSON.stringify(closeout.cwd)}, action: "status" })`)}
Metric readiness / trust
${escapeHtml(metricReadiness.classification)}
${escapeHtml(metricReadiness.summary)}
metric readiness blockers=${escapeHtml(String(metricReadiness.blockedReasons.length))}; ${escapeHtml(metricReadinessBlockers)}
${metricReadinessChecklist || '
No metric readiness checklist items recorded.
'}
Resume plan
${resumePlan.reusable ? "reusable foreground plan" : "blocked until reviewed"}
${escapeHtml(resumePlan.packetKind)} · snapshot=${escapeHtml(resumePlan.snapshotReuse)} · control=${escapeHtml(resumePlan.controlState)} · blockers=${escapeHtml(resumePlanBlockers)}
${escapeHtml(resumePlan.wouldRun ?? `${AUTORESEARCH_STATUS_TOOL_NAME}({ cwd: ${JSON.stringify(closeout.cwd)}, action: "resume_plan" })`)}
Read-only: no benchmark run, resume_apply, daemon, peer launch, candidate mutation, or external evidence/learning write.
Resume apply plan-only proposal
${resumeApplyPlan.planReady ? "proposal ready, execution not authorized" : "proposal blocked"}
${escapeHtml(resumeApplyPlan.packetKind)} · execution authorized=${resumeApplyPlan.executionAuthorized ? "yes" : "no"} · blockers=${escapeHtml(resumeApplyPlanBlockers)}
${escapeHtml(resumeApplyPlan.futureForegroundCall ?? `${AUTORESEARCH_STATUS_TOOL_NAME}({ cwd: ${JSON.stringify(closeout.cwd)}, action: "resume_apply_plan" })`)}
Plan-only: execution is not authorized here; use autoresearch_runtime_resume_apply only with exact foreground confirmation and explicit budgets.
Authority handoff
closeout → AK evidence → learning/KES → Oracle-ready DSPx preflight
${authorityHandoffLines.map((line) => `
${escapeHtml(line.replace(/^- /u, ""))}
`).join("\n")}
Learning handoff
export → owner adapter
${escapeHtml(learningExportCall)}
${escapeHtml(learningKesAdapterCall)}
Boundary: export is local only; KES/notes/KMS adapters own persistence and promotion.
Setup guide
configure a bounded segment
${setupGuideLines.map((line) => `
${escapeHtml(line.replace(/^- /u, ""))}
`).join("\n")}
Bind → measure → candidate_result_export journey
export inspects measured packet inventory before owner review
${guidedCandidateJourneyLines.map((line) => `
${escapeHtml(line.replace(/^- /u, ""))}
`).join("\n")}
Measured packet inventory before owner review
export_visibility_blockers=${matrixSummary.exportVisibilityBlockers.value}
campaigns=${matrixSummary.campaignCount} · cells=${matrixSummary.completedCellCount}/${matrixSummary.cellCount} · selected=${matrixSummary.selectedCellCount} · open review cells=${matrixSummary.openCandidateReview.openCellCount} · lanes=${matrixSummary.candidateLaneCount} · exported packets=${matrixSummary.exportedPacketCount}
${escapeHtml(matrixSummary.openCandidateReview.summary)}
metric=${escapeHtml(matrixSummary.metricName ?? "(unknown)")} (${escapeHtml(matrixSummary.metricDirection ?? "unknown")} is better; target=${escapeHtml(String(matrixSummary.metricTarget ?? "none"))}) · latest=${escapeHtml(matrixSummary.latestArtifactPath ?? "none")}
${escapeHtml(matrixSummary.boundary)}
${matrixNextLegalActions || '
No matrix next legal actions discovered yet.
'}
${matrixCellRows || ``}
CellPostureLanesSelectedPacket inventoryNext legal action
No matrix campaign artifacts discovered under .autoresearch/campaigns or .autoresearch/matrix-campaign.
${matrixMode ? "Local runtime segment snapshot" : "Runtime segment"}
${matrixMode ? "Auxiliary single-segment state for this cwd. Matrix progress above is authoritative for dashboard visibility; blank runtime fields here usually mean the matrix is driven by orchestrator/candidate-wave artifacts instead of one local autoresearch.jsonl segment." : "Primary local runtime segment state for this cwd."}
Campaign
${escapeHtml(segment.name ?? "unconfigured")}
Metric
★ ${escapeHtml(metricName)} ${escapeHtml(direction ?? "")} ${metricUnit ? `(${escapeHtml(metricUnit)})` : ""}
Success threshold
${escapeHtml(formatMetricThresholdValue(segment.metricThreshold, metricUnit))}
Benchmark
${escapeHtml(segment.benchmarkCommand ?? "(unset)")}
Checks
${escapeHtml(segment.checksCommand ?? "(none)")}
${escapeHtml(chartTitle)}${escapeHtml(chartMetricName)} / ${escapeHtml(chartDirection ?? "direction unset")}
${escapeHtml(chartSourceDescription)}
${tableRows || ``}
#StatusKind★ ${escapeHtml(metricName)}DecisionDescription
No runs recorded yet.
\n`; }