diff --git a/apps/macos/Sources/RoveApp/HistoryView.swift b/apps/macos/Sources/RoveApp/HistoryView.swift index e922010..2fc13b1 100644 --- a/apps/macos/Sources/RoveApp/HistoryView.swift +++ b/apps/macos/Sources/RoveApp/HistoryView.swift @@ -356,6 +356,9 @@ private struct HistoryDetail: View { openWindow(id: "trace-diagnostics") }.buttonStyle(LabButtonStyle(compact: true)) } + if entry.draft != nil && entry.status != .modelSetup { + RunAssessmentView(workspace: workspace, entry: entry) + } if let draft = entry.draft, draft.settings.chains > 1, entry.status != .modelSetup { ChainResultsView( workspace: workspace, directory: entry.directory, diff --git a/apps/macos/Sources/RoveApp/PredictiveCheckView.swift b/apps/macos/Sources/RoveApp/PredictiveCheckView.swift index c08aa66..915c29a 100644 --- a/apps/macos/Sources/RoveApp/PredictiveCheckView.swift +++ b/apps/macos/Sources/RoveApp/PredictiveCheckView.swift @@ -201,6 +201,7 @@ struct PredictiveReportView: View { } Button(strings("Open folder")) { NSWorkspace.shared.open(prediction.directory) } }.buttonStyle(LabButtonStyle(compact: true)) + PredictiveDistributionView(prediction: prediction, strings: strings) } } diff --git a/apps/macos/Sources/RoveApp/PredictiveDistribution.swift b/apps/macos/Sources/RoveApp/PredictiveDistribution.swift new file mode 100644 index 0000000..6d640b1 --- /dev/null +++ b/apps/macos/Sources/RoveApp/PredictiveDistribution.swift @@ -0,0 +1,136 @@ +import Charts +import SwiftUI + +struct PredictiveDistribution: Sendable { + struct Bin: Identifiable, Sendable { + let id: Int + let lower: Double + let upper: Double + let count: Int + } + let name: String + let differences: [Double] + let undefined: Int + + var bins: [Bin] { + guard let low = differences.min(), let high = differences.max() else { return [] } + let width = high == low ? max(abs(low) * 0.05, 0.1) : (high - low) / 20 + guard width.isFinite && width > 0 else { return [] } + let start = high == low ? low - width / 2 : low + let count = high == low ? 1 : 20 + var totals = [Int](repeating: 0, count: count) + for value in differences { totals[min(count - 1, max(0, Int((value - start) / width)))] += 1 } + return totals.indices.map { + Bin( + id: $0, lower: start + Double($0) * width, + upper: start + Double($0 + 1) * width, count: totals[$0]) + } + } + + static func read(_ prediction: SavedPrediction) throws -> [Self] { + struct Pair: Decodable { + let replicate: Int + let observed: [String: Double?] + let simulated: [String: Double?] + } + let file = prediction.directory.appendingPathComponent("replicates.jsonl") + let info = try file.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) + guard info.isRegularFile == true, (info.fileSize ?? 0) <= 64 * 1024 * 1024 else { + throw RunFailure.invalidCompletion + } + let data = try Data(contentsOf: file) + let pairs = try data.split(separator: 10).map { + try JSONDecoder().decode(Pair.self, from: Data($0)) + } + guard pairs.count == prediction.report.replicates, + Set(pairs.map(\.replicate)) == Set(1...prediction.report.replicates) + else { throw RunFailure.invalidCompletion } + return try PredictiveReport.statistics.map { name in + let differences = try pairs.compactMap { pair -> Double? in + guard pair.observed.keys.contains(name), pair.simulated.keys.contains(name) else { + throw RunFailure.invalidCompletion + } + guard let a = pair.observed[name] ?? nil, let b = pair.simulated[name] ?? nil else { + return nil + } + let difference = b - a + guard a.isFinite, b.isFinite, difference.isFinite else { + throw RunFailure.invalidCompletion + } + return difference + } + guard let tail = prediction.report.global[name], tail.validPairs == differences.count, + tail.undefinedPairs == pairs.count - differences.count, + tail.lowerCount == differences.filter({ $0 <= 0 }).count, + tail.upperCount == differences.filter({ $0 >= 0 }).count, + tail.ties == differences.filter({ $0 == 0 }).count + else { throw RunFailure.invalidCompletion } + return Self(name: name, differences: differences, undefined: pairs.count - differences.count) + } + } +} + +struct PredictiveDistributionView: View { + let prediction: SavedPrediction + let strings: AppStrings + @State private var distributions: [PredictiveDistribution] = [] + @State private var selected = "parsimony_length" + @State private var failed = false + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + Picker(strings("Statistic"), selection: $selected) { + ForEach(PredictiveReport.statistics, id: \.self) { name in + Text(strings(PredictiveReportView.label(name))).tag(name) + } + }.frame(maxWidth: 360) + if let distribution = distributions.first(where: { $0.name == selected }) { + if !distribution.differences.isEmpty { + Chart { + ForEach(distribution.bins) { bin in + RectangleMark( + xStart: .value("Difference", bin.lower), xEnd: .value("Difference", bin.upper), + yStart: .value("Pairs", 0), yEnd: .value("Pairs", bin.count) + ) + .foregroundStyle(Lab.lilac.opacity(0.7)) + } + RuleMark(x: .value("Zero", 0)).lineStyle(StrokeStyle(lineWidth: 1, dash: [4, 3])) + .foregroundStyle(Lab.secondary) + }.frame(height: 180) + .chartXAxisLabel(strings("Simulated − observed")) + .chartYAxisLabel(strings("Valid pairs")) + .accessibilityLabel( + strings( + "Distribution of simulated minus observed paired statistics. Zero is equality.")) + } + Text( + strings( + "%@ valid pairs · %@ undefined", String(distribution.differences.count), + String(distribution.undefined)) + ) + .font(.system(size: 10)).foregroundStyle(Lab.secondary) + } else if failed { + Text( + strings( + "Replicate details are missing or disagree with the check record. The distribution is unavailable." + ) + ) + .font(.system(size: 11)).foregroundStyle(Lab.secondary) + } else { + ProgressView().controlSize(.small) + } + Text( + strings( + "Each difference uses the simulated and observed matrix on the same posterior tree. The observed statistic can change with the tree. Zero means equality; this is a discrepancy plot, not a convergence test." + ) + ) + .font(.system(size: 10)).foregroundStyle(Lab.muted).fixedSize( + horizontal: false, vertical: true) + }.task(id: prediction.id) { + let prediction = prediction + distributions = + (try? await Task.detached { try PredictiveDistribution.read(prediction) }.value) ?? [] + failed = distributions.isEmpty + } + } +} diff --git a/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings b/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings index aeeee12..012f01a 100644 --- a/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings +++ b/apps/macos/Sources/RoveApp/Resources/en.lproj/Localizable.strings @@ -1116,3 +1116,41 @@ "This is a prior preview, before seeing the data. The displayed range is not a credible interval." = "This is a prior preview, before seeing the data. The displayed range is not a credible interval."; "Other %@ terminals" = "Other %@ terminals"; "Constraint diagram. Branch lengths and relationships within the collapsed group are not estimated here." = "Constraint diagram. Branch lengths and relationships within the collapsed group are not estimated here."; + +/* Evidence review and reproducibility exports. */ +"Evidence review" = "Evidence review"; +"What does this run establish?" = "What does this run establish?"; +"Review completion, sampling and available reports separately. This snapshot does not certify convergence or model adequacy." = "Review completion, sampling and available reports separately. This snapshot does not certify convergence or model adequacy."; +"Refresh evidence review" = "Refresh evidence review"; +"Matching tree reports: %@ · Predictive reports: %@" = "Matching tree reports: %@ · Predictive reports: %@"; +"Review record" = "Review record"; +"Include the original matrix in the export" = "Include the original matrix in the export"; +"The local package includes settings, seeds, build identities, samples, diagnostics and derived reports with SHA-256 fingerprints. Recorded paths and taxon names are preserved. Exact resumption still requires the original executable and a valid checkpoint." = "The local package includes settings, seeds, build identities, samples, diagnostics and derived reports with SHA-256 fingerprints. Recorded paths and taxon names are preserved. Exact resumption still requires the original executable and a valid checkpoint."; +"Export reproducibility package…" = "Export reproducibility package…"; +"Choose export folder" = "Choose export folder"; +"Open exported package" = "Open exported package"; +"Run completion" = "Run completion"; +"Scalar sampling" = "Scalar sampling"; +"Independent-chain agreement" = "Independent-chain agreement"; +"Tree evidence" = "Tree evidence"; +"Predictive evidence" = "Predictive evidence"; +"Criteria met" = "Criteria met"; +"Needs attention" = "Needs attention"; +"Interpretation required" = "Interpretation required"; +"Evidence unavailable" = "Evidence unavailable"; +"The original matrix matches the recorded fingerprint." = "The original matrix matches the recorded fingerprint."; +"The original matrix has changed. Matrix inclusion will be refused." = "The original matrix has changed. Matrix inclusion will be refused."; +"The original matrix is unavailable. Records can still be exported without it." = "The original matrix is unavailable. Records can still be exported without it."; +"The review or export was cancelled." = "The review or export was cancelled."; +"The review or export could not be completed." = "The review or export could not be completed."; +"Recorded steps and sample files agree. Completion is not convergence." = "Recorded steps and sample files agree. Completion is not convergence."; +"The run is unfinished, incomplete or inconsistent. Review the source records and errors." = "The run is unfinished, incomplete or inconsistent. Review the source records and errors."; +"Review every sampled scalar: at least 1,000 retained draws and ESS 200 per chain, with no lag truncation. Verified model-fixed values are excluded; stuck sampled values are not." = "Review every sampled scalar: at least 1,000 retained draws and ESS 200 per chain, with no lag truncation. Verified model-fixed values are excluded; stuck sampled values are not."; +"Between-chain assessment requires independent seeds, matching input/model, ESS 200 per chain, at least 1,000 retained draws and rank-normalized split R-hat at most 1.01. These diagnostics do not prove convergence." = "Between-chain assessment requires independent seeds, matching input/model, ESS 200 per chain, at least 1,000 retained draws and rank-normalized split R-hat at most 1.01. These diagnostics do not prove convergence."; +"Review tree summaries and unconstrained clade frequencies. High support or agreement on constant clades does not establish exploration of tree space." = "Review tree summaries and unconstrained clade frequencies. High support or agreement on constant clades does not establish exploration of tree space."; +"Review paired predictive discrepancies, undefined pairs and simulation uncertainty. A saved check alone does not establish model adequacy." = "Review paired predictive discrepancies, undefined pairs and simulation uncertainty. A saved check alone does not establish model adequacy."; +"Simulated − observed" = "Simulated − observed"; +"Distribution of simulated minus observed paired statistics. Zero is equality." = "Distribution of simulated minus observed paired statistics. Zero is equality."; +"%@ valid pairs · %@ undefined" = "%@ valid pairs · %@ undefined"; +"Replicate details are missing or disagree with the check record. The distribution is unavailable." = "Replicate details are missing or disagree with the check record. The distribution is unavailable."; +"Each difference uses the simulated and observed matrix on the same posterior tree. The observed statistic can change with the tree. Zero means equality; this is a discrepancy plot, not a convergence test." = "Each difference uses the simulated and observed matrix on the same posterior tree. The observed statistic can change with the tree. Zero means equality; this is a discrepancy plot, not a convergence test."; diff --git a/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings b/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings index da04537..033c33a 100644 --- a/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings +++ b/apps/macos/Sources/RoveApp/Resources/pt-BR.lproj/Localizable.strings @@ -1116,3 +1116,41 @@ "This is a prior preview, before seeing the data. The displayed range is not a credible interval." = "Esta é uma prévia do prior, antes de observar os dados. O intervalo exibido não é um intervalo de credibilidade."; "Other %@ terminals" = "Outros %@ terminais"; "Constraint diagram. Branch lengths and relationships within the collapsed group are not estimated here." = "Diagrama da restrição. Os comprimentos dos ramos e as relações dentro do grupo recolhido não são estimados aqui."; + +/* Evidence review and reproducibility exports. */ +"Evidence review" = "Revisão das evidências"; +"What does this run establish?" = "O que esta execução permite concluir?"; +"Review completion, sampling and available reports separately. This snapshot does not certify convergence or model adequacy." = "Revise separadamente a conclusão, a amostragem e os relatórios disponíveis. Este registro não certifica convergência nem adequação do modelo."; +"Refresh evidence review" = "Atualizar revisão das evidências"; +"Matching tree reports: %@ · Predictive reports: %@" = "Relatórios de árvores correspondentes: %@ · Relatórios preditivos: %@"; +"Review record" = "Registro da revisão"; +"Include the original matrix in the export" = "Incluir a matriz original na exportação"; +"The local package includes settings, seeds, build identities, samples, diagnostics and derived reports with SHA-256 fingerprints. Recorded paths and taxon names are preserved. Exact resumption still requires the original executable and a valid checkpoint." = "O pacote local inclui configurações, sementes, identificação das compilações, amostras, diagnósticos e relatórios derivados com identificadores SHA-256. Os caminhos registrados e os nomes dos táxons são preservados. A retomada exata ainda exige o executável original e um checkpoint válido."; +"Export reproducibility package…" = "Exportar pacote de reprodução…"; +"Choose export folder" = "Escolher pasta de exportação"; +"Open exported package" = "Abrir pacote exportado"; +"Run completion" = "Conclusão da execução"; +"Scalar sampling" = "Amostragem dos parâmetros"; +"Independent-chain agreement" = "Concordância entre cadeias independentes"; +"Tree evidence" = "Evidências das árvores"; +"Predictive evidence" = "Evidências preditivas"; +"Criteria met" = "Critérios atendidos"; +"Needs attention" = "Precisa de atenção"; +"Interpretation required" = "Requer interpretação"; +"Evidence unavailable" = "Evidência indisponível"; +"The original matrix matches the recorded fingerprint." = "A matriz original corresponde ao identificador registrado."; +"The original matrix has changed. Matrix inclusion will be refused." = "A matriz original foi alterada. Sua inclusão será recusada."; +"The original matrix is unavailable. Records can still be exported without it." = "A matriz original está indisponível. Os registros ainda podem ser exportados sem ela."; +"The review or export was cancelled." = "A revisão ou exportação foi cancelada."; +"The review or export could not be completed." = "Não foi possível concluir a revisão ou exportação."; +"Recorded steps and sample files agree. Completion is not convergence." = "Os passos registrados e os arquivos de amostras correspondem. Concluir a execução não significa convergir."; +"The run is unfinished, incomplete or inconsistent. Review the source records and errors." = "A execução não terminou, está incompleta ou contém inconsistências. Revise os registros de origem e os erros."; +"Review every sampled scalar: at least 1,000 retained draws and ESS 200 per chain, with no lag truncation. Verified model-fixed values are excluded; stuck sampled values are not." = "Revise todos os parâmetros amostrados: pelo menos 1.000 amostras retidas e ESS de 200 por cadeia, sem truncamento das defasagens. Valores comprovadamente fixos pelo modelo são excluídos; parâmetros amostrados que ficaram constantes não são."; +"Between-chain assessment requires independent seeds, matching input/model, ESS 200 per chain, at least 1,000 retained draws and rank-normalized split R-hat at most 1.01. These diagnostics do not prove convergence." = "A avaliação entre cadeias exige sementes independentes, entrada e modelo correspondentes, ESS de 200 por cadeia, pelo menos 1.000 amostras retidas e R-hat dividido e normalizado por postos de no máximo 1,01. Esses diagnósticos não comprovam convergência."; +"Review tree summaries and unconstrained clade frequencies. High support or agreement on constant clades does not establish exploration of tree space." = "Revise os resumos de árvores e as frequências dos clados sem restrição. Suporte alto ou concordância em clados constantes não demonstra exploração do espaço de árvores."; +"Review paired predictive discrepancies, undefined pairs and simulation uncertainty. A saved check alone does not establish model adequacy." = "Revise as discrepâncias preditivas pareadas, os pares indefinidos e a incerteza da simulação. Uma verificação salva, por si só, não demonstra adequação do modelo."; +"Simulated − observed" = "Simulado − observado"; +"Distribution of simulated minus observed paired statistics. Zero is equality." = "Distribuição das diferenças pareadas entre estatísticas simuladas e observadas. Zero indica igualdade."; +"%@ valid pairs · %@ undefined" = "%@ pares válidos · %@ indefinidos"; +"Replicate details are missing or disagree with the check record. The distribution is unavailable." = "Os detalhes das réplicas estão ausentes ou não correspondem ao registro da verificação. A distribuição está indisponível."; +"Each difference uses the simulated and observed matrix on the same posterior tree. The observed statistic can change with the tree. Zero means equality; this is a discrepancy plot, not a convergence test." = "Cada diferença usa a matriz simulada e a observada na mesma árvore posterior. A estatística observada pode variar conforme a árvore. Zero indica igualdade; este é um gráfico de discrepâncias, não um teste de convergência."; diff --git a/apps/macos/Sources/RoveApp/RunAssessment.swift b/apps/macos/Sources/RoveApp/RunAssessment.swift new file mode 100644 index 0000000..95bb550 --- /dev/null +++ b/apps/macos/Sources/RoveApp/RunAssessment.swift @@ -0,0 +1,164 @@ +import Foundation +import Observation + +struct RunAssessment: Decodable, Sendable { + struct Section: Decodable, Sendable, Identifiable { + let id: String + let status: String + let message: String + } + let schemaVersion: Int + let kind: String + let createdUnixSeconds: Double + let source: String + let chainCount: Int + let burninPercent: Int + let originalMatrixStatus: String + let sections: [Section] + let treeReports: [String] + let predictiveReports: [String] + let convergenceCertified: Bool + + static func read(_ directory: URL) throws -> Self { + let file = directory.appendingPathComponent("assessment.json") + let info = try file.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) + guard info.isRegularFile == true, (info.fileSize ?? 0) <= 128 * 1024 * 1024 else { + throw RunFailure.invalidCompletion + } + let decoder = JSONDecoder() + decoder.keyDecodingStrategy = .convertFromSnakeCase + let value = try decoder.decode(Self.self, from: Data(contentsOf: file)) + guard value.schemaVersion == 1, value.kind == "run_assessment", + value.createdUnixSeconds.isFinite, (1...16).contains(value.chainCount), + (0..<100).contains(value.burninPercent), !value.convergenceCertified, + Set(value.sections.map(\.id)) + == Set(["completion", "sampling", "agreement", "trees", "prediction"]), + value.sections.count == 5, + value.sections.allSatisfy({ + ["passed", "attention", "unavailable", "review_required"].contains($0.status) + }) + else { throw RunFailure.invalidCompletion } + return value + } +} + +struct AssessmentOptions: Codable, Sendable { + var burnin = "10" + var includeMatrix = false + var valid: Bool { Int(burnin).map { (0..<100).contains($0) } == true } +} + +struct AssessmentRequest: Sendable { + let entry: HistoryEntry + let executable: URL + let output: URL + let options: AssessmentOptions + let export: Bool + + func execute(with tool: EngineTool) async throws -> RunAssessment { + guard options.valid else { throw ImportError.message("Choose a burn-in from 0 to 99 percent.") } + var arguments = [ + export ? "export-run" : "assess", entry.directory.path, + "--output", output.path, "--burnin-percent", options.burnin, "--cancel-on-stdin-close", + ] + if export && options.includeMatrix { + guard let draft = entry.draft else { throw RunFailure.invalidCompletion } + arguments += ["--include-matrix", draft.matrixPath] + } + let outcome = try await tool.execute( + executable: executable, arguments: arguments, onLine: { _ in }) + guard outcome.status == 0 else { throw ImportError.readerFailed(outcome.log) } + let report = try RunAssessment.read(output) + guard + URL(fileURLWithPath: report.source).standardizedFileURL.resolvingSymlinksInPath().path + == entry.directory.standardizedFileURL.resolvingSymlinksInPath().path + else { throw RunFailure.invalidCompletion } + return report + } +} + +@MainActor @Observable +final class RunAssessmentModel { + let entry: HistoryEntry + let executable: URL + var options = AssessmentOptions() + private(set) var busy = false + private(set) var report: RunAssessment? + private(set) var reportDirectory: URL? + private(set) var exported: URL? + private(set) var error: String? + private(set) var details: String? + private var tool: EngineTool? + private var task: Task? + private var parent: URL { entry.directory.appendingPathComponent("assessments") } + + init(entry: HistoryEntry, executable: URL) { + self.entry = entry + self.executable = executable + } + + func load() async { + guard !busy else { return } + let directory = parent + let loaded = await Task.detached { + let options = try? JSONDecoder().decode( + AssessmentOptions.self, + from: RecordFile.read(directory.appendingPathComponent("options.json"))) + let children = + (try? FileManager.default.contentsOfDirectory( + at: directory, + includingPropertiesForKeys: nil)) ?? [] + let reports = children.compactMap { file -> (URL, RunAssessment)? in + guard let value = try? RunAssessment.read(file) else { return nil } + return (file, value) + }.sorted { $0.1.createdUnixSeconds > $1.1.createdUnixSeconds } + return (options, reports.first) + }.value + if let restored = loaded.0, restored.valid { options = restored } + if let saved = loaded.1, + URL(fileURLWithPath: saved.1.source).standardizedFileURL.resolvingSymlinksInPath().path + == entry.directory.standardizedFileURL.resolvingSymlinksInPath().path + { + reportDirectory = saved.0 + report = saved.1 + } + } + + func start(exportTo destination: URL? = nil) { + guard !busy, options.valid else { return } + busy = true + error = nil + details = nil + exported = nil + let tool = EngineTool() + self.tool = tool + let request = AssessmentRequest( + entry: entry, executable: executable, + output: destination ?? parent.appendingPathComponent("review-\(UUID())"), + options: options, export: destination != nil) + task = Task { + do { + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + try JSONEncoder().encode(request.options).write( + to: parent.appendingPathComponent("options.json"), options: .atomic) + let value = try await request.execute(with: tool) + if destination != nil { + exported = request.output + } else { + report = value + reportDirectory = request.output + } + } catch is CancellationError { + error = "The review or export was cancelled." + } catch { + self.error = "The review or export could not be completed." + details = error.localizedDescription + } + busy = false + self.tool = nil + } + } + + func cancel() { tool?.cancel() } + func waitForExit() async { await task?.value } +} diff --git a/apps/macos/Sources/RoveApp/RunAssessmentView.swift b/apps/macos/Sources/RoveApp/RunAssessmentView.swift new file mode 100644 index 0000000..a67abaf --- /dev/null +++ b/apps/macos/Sources/RoveApp/RunAssessmentView.swift @@ -0,0 +1,131 @@ +import SwiftUI + +struct RunAssessmentView: View { + @Bindable var workspace: Workspace + let entry: HistoryEntry + @State private var model: RunAssessmentModel? + private var strings: AppStrings { workspace.strings } + + var body: some View { + LabPanel { + VStack(alignment: .leading, spacing: 16) { + Eyebrow(text: strings("Evidence review"), color: Lab.lilac) + Text(strings("What does this run establish?")).font(Lab.display(25)) + Text( + strings( + "Review completion, sampling and available reports separately. This snapshot does not certify convergence or model adequacy." + ) + ) + .font(.system(size: 11)).foregroundStyle(Lab.secondary).fixedSize( + horizontal: false, vertical: true) + if let model { content(model) } + } + }.task(id: entry.id) { + let value = workspace.runAssessment(for: entry) + model = value + await value.load() + } + } + + @ViewBuilder private func content(_ model: RunAssessmentModel) -> some View { + @Bindable var model = model + HStack { + Text(strings("Burn-in (%)")) + TextField(strings("Burn-in (%)"), text: $model.options.burnin).textFieldStyle(.roundedBorder) + .frame(width: 70) + Button(strings("Refresh evidence review")) { model.start() } + .buttonStyle(LabButtonStyle(prominent: true)).disabled( + !model.options.valid || model.busy || workspace.isRunning) + if model.busy { + ProgressView().controlSize(.small) + Button(strings("Cancel")) { model.cancel() }.buttonStyle(LabButtonStyle(compact: true)) + } + }.font(.system(size: 11)) + if let report = model.report { + Text( + Date(timeIntervalSince1970: report.createdUnixSeconds).formatted( + .dateTime.day().month().year().hour().minute().locale(strings.locale)) + ) + .font(.system(size: 10)).foregroundStyle(Lab.muted) + ForEach(report.sections) { section in + VStack(alignment: .leading, spacing: 6) { + HStack { + Text(strings(Self.title(section.id))).font(.system(size: 12, weight: .medium)) + Spacer() + Text(strings(Self.status(section.status))).foregroundStyle( + section.status == "passed" ? Lab.accent : Lab.secondary) + } + Text(strings(section.message)).font(.system(size: 10)).foregroundStyle(Lab.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + Text( + strings( + "Matching tree reports: %@ · Predictive reports: %@", String(report.treeReports.count), + String(report.predictiveReports.count)) + ) + .font(.system(size: 10)).foregroundStyle(Lab.muted) + Text(strings(Self.inputStatus(report.originalMatrixStatus))).font(.system(size: 10)) + .foregroundStyle(Lab.secondary) + if let directory = model.reportDirectory { + Button(strings("Review record")) { + NSWorkspace.shared.open(directory.appendingPathComponent("assessment.json")) + } + .buttonStyle(LabButtonStyle(compact: true)) + } + } + Divider().overlay(Lab.border) + Toggle(strings("Include the original matrix in the export"), isOn: $model.options.includeMatrix) + .font(.system(size: 11)).disabled(model.busy) + Text( + strings( + "The local package includes settings, seeds, build identities, samples, diagnostics and derived reports with SHA-256 fingerprints. Recorded paths and taxon names are preserved. Exact resumption still requires the original executable and a valid checkpoint." + ) + ) + .font(.system(size: 10)).foregroundStyle(Lab.secondary).fixedSize( + horizontal: false, vertical: true) + Button(strings("Export reproducibility package…")) { + let panel = NSOpenPanel() + panel.canChooseFiles = false + panel.canChooseDirectories = true + panel.canCreateDirectories = true + panel.allowsMultipleSelection = false + panel.prompt = strings("Choose export folder") + guard panel.runModal() == .OK, let folder = panel.url else { return } + model.start(exportTo: folder.appendingPathComponent("rove-export-\(UUID().uuidString)")) + }.buttonStyle(LabButtonStyle(compact: true)).disabled( + !model.options.valid || model.busy || workspace.isRunning) + if let exported = model.exported { + Button(strings("Open exported package")) { NSWorkspace.shared.open(exported) }.buttonStyle( + LabButtonStyle(compact: true)) + } + if let error = model.error { + DiagnosticMessage(title: strings(error), details: model.details, strings: strings) + } + } + + static func title(_ id: String) -> String { + switch id { + case "completion": "Run completion" + case "sampling": "Scalar sampling" + case "agreement": "Independent-chain agreement" + case "trees": "Tree evidence" + default: "Predictive evidence" + } + } + static func status(_ value: String) -> String { + switch value { + case "passed": "Criteria met" + case "attention": "Needs attention" + case "review_required": "Interpretation required" + default: "Evidence unavailable" + } + } + static func inputStatus(_ value: String) -> String { + switch value { + case "matches": "The original matrix matches the recorded fingerprint." + case "changed": "The original matrix has changed. Matrix inclusion will be refused." + default: "The original matrix is unavailable. Records can still be exported without it." + } + } +} diff --git a/apps/macos/Sources/RoveApp/Workspace.swift b/apps/macos/Sources/RoveApp/Workspace.swift index 69ddbc6..5314ea8 100644 --- a/apps/macos/Sources/RoveApp/Workspace.swift +++ b/apps/macos/Sources/RoveApp/Workspace.swift @@ -537,10 +537,19 @@ final class Workspace { var predictiveChecks: [String: PredictiveCheckModel] = [:] var marginalEstimates: [String: MarginalLikelihoodModel] = [:] var runComparisons: [String: RunComparisonModel] = [:] + var runAssessments: [String: RunAssessmentModel] = [:] var toolsBusy: Bool { predictiveChecks.values.contains(where: \.busy) || marginalEstimates.values.contains(where: \.busy) || runComparisons.values.contains(where: \.busy) + || runAssessments.values.contains(where: \.busy) + } + + func runAssessment(for entry: HistoryEntry) -> RunAssessmentModel { + if let model = runAssessments[entry.id] { return model } + let model = RunAssessmentModel(entry: entry, executable: executable) + runAssessments[entry.id] = model + return model } func predictiveCheck(for entry: HistoryEntry) -> PredictiveCheckModel { diff --git a/apps/macos/Tests/RoveAppTests/AssessmentPreviewTests.swift b/apps/macos/Tests/RoveAppTests/AssessmentPreviewTests.swift new file mode 100644 index 0000000..e177389 --- /dev/null +++ b/apps/macos/Tests/RoveAppTests/AssessmentPreviewTests.swift @@ -0,0 +1,73 @@ +import AppKit +import SwiftUI +import Testing + +@testable import RoveApp + +struct AssessmentPreviewTests { + @Test @MainActor func renderAssessmentAndPairedDistribution() async throws { + guard ProcessInfo.processInfo.environment["CI"] == nil else { return } + let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent() + let output = root.appendingPathComponent(".local/ui/assessment") + try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true) + _ = NSApplication.shared + NSApp.appearance = NSAppearance(named: .darkAqua) + Lab.registerFonts() + let suite = "rove-assessment-preview-\(UUID())" + let defaults = try #require(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let preferences = AppPreferences(defaults: defaults, preferredLanguages: ["en-US"]) + let engine = root.appendingPathComponent("target/release/rove") + let matrix = root.appendingPathComponent("fixtures/reference/20x50/matrix.nex") + let report = try await MatrixInspector.inspect(matrix, gapsAsMissing: false, executable: engine) + var settings = AnalysisSettings() + settings.steps = 1000 + settings.sampleEvery = 10 + let directory = output.appendingPathComponent("run-\(UUID())") + let draft = AnalysisDraft(matrix: matrix, report: report, settings: settings) + #expect( + await RunProcess().execute( + RunRequest(id: UUID(), executable: engine, directory: directory, draft: draft) + ) { _ in }.status == .completed) + let entry = HistoryEntry.read(directory) + let workspace = Workspace(executable: engine, preferences: preferences) + let predictive = workspace.predictiveCheck(for: entry) + predictive.replicates = "30" + predictive.start() + await predictive.waitForExit() + let saved = try #require(predictive.predictions.first) + let review = workspace.runAssessment(for: entry) + review.start() + await review.waitForExit() + #expect(review.error == nil, Comment(rawValue: review.details ?? "")) + for language in [AppLanguage.english, .portuguese] { + preferences.language = language + try await render( + RunAssessmentView(workspace: workspace, entry: entry), name: "review", height: 950) + try await render( + PredictiveReportView(prediction: saved, strings: preferences.strings), name: "prediction", + height: 850) + + @MainActor func render(_ content: V, name: String, height: CGFloat) async throws { + let view = NSHostingView( + rootView: content.padding(24).background(Lab.background) + .foregroundStyle(Lab.ink).frame(width: 820, height: height, alignment: .topLeading)) + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 820, height: height), styleMask: [.borderless], + backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + window.contentView = view + window.orderBack(nil) + try await Task.sleep(for: .milliseconds(500)) + view.layoutSubtreeIfNeeded() + let bitmap = try #require(view.bitmapImageRepForCachingDisplay(in: view.bounds)) + view.cacheDisplay(in: view.bounds, to: bitmap) + try #require(bitmap.representation(using: .png, properties: [:])).write( + to: output.appendingPathComponent("\(name)-\(language.rawValue).png")) + window.close() + } + } + } +} diff --git a/apps/macos/Tests/RoveAppTests/CheckpointTests.swift b/apps/macos/Tests/RoveAppTests/CheckpointTests.swift index dbf7aaa..3875159 100644 --- a/apps/macos/Tests/RoveAppTests/CheckpointTests.swift +++ b/apps/macos/Tests/RoveAppTests/CheckpointTests.swift @@ -41,6 +41,13 @@ struct CheckpointTests { let continued = await RunProcess().execute(resumed) { _ in } #expect(continued.status == .completed, "\(String(describing: continued))") #expect(HistoryEntry.read(directory).status == .completed) + let review = try await AssessmentRequest( + entry: HistoryEntry.read(directory), executable: engine, + output: parent.appendingPathComponent("review-\(chains)"), options: AssessmentOptions(), + export: false + ) + .execute(with: EngineTool()) + #expect(review.sections.first(where: { $0.id == "completion" })?.status == "passed") let fullDirectory = parent.appendingPathComponent("full-\(chains)") let full = RunRequest(id: UUID(), executable: engine, directory: fullDirectory, draft: draft) let complete = await RunProcess().execute(full) { _ in } diff --git a/apps/macos/Tests/RoveAppTests/ModelToolsTests.swift b/apps/macos/Tests/RoveAppTests/ModelToolsTests.swift index 610da67..6149cf2 100644 --- a/apps/macos/Tests/RoveAppTests/ModelToolsTests.swift +++ b/apps/macos/Tests/RoveAppTests/ModelToolsTests.swift @@ -67,6 +67,12 @@ struct ModelToolsTests { #expect(model.error == nil, Comment(rawValue: model.details ?? "")) #expect(model.completed == 5) let saved = try #require(model.predictions.first) + let distributions = try PredictiveDistribution.read(saved) + #expect(distributions.count == 5) + for distribution in distributions { + #expect(distribution.differences.count + distribution.undefined == 5) + #expect(distribution.bins.map(\.count).reduce(0, +) == distribution.differences.count) + } // 2,000 steps sampled every 100 give 21 samples; 10% burn-in discards 2. let source = saved.report.source #expect( diff --git a/apps/macos/Tests/RoveAppTests/RunAssessmentTests.swift b/apps/macos/Tests/RoveAppTests/RunAssessmentTests.swift new file mode 100644 index 0000000..b245ef5 --- /dev/null +++ b/apps/macos/Tests/RoveAppTests/RunAssessmentTests.swift @@ -0,0 +1,94 @@ +import Foundation +import Testing + +@testable import RoveApp + +struct RunAssessmentTests { + private var root: URL { + URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + } + private var engine: URL { root.appendingPathComponent("target/release/rove") } + + @Test @MainActor func reviewPersistsAndExportReopensWithVerifiedFiles() async throws { + let parent = FileManager.default.temporaryDirectory.appendingPathComponent( + "rove-review-\(UUID())") + try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: parent) } + let matrix = parent.appendingPathComponent("matrix.nex") + try + "#NEXUS BEGIN DATA; DIMENSIONS NTAX=4 NCHAR=4; FORMAT SYMBOLS=\"01\"; MATRIX A 0000 B 0011 C 1100 D 1111; END;" + .write(to: matrix, atomically: true, encoding: .utf8) + let report = try await MatrixInspector.inspect(matrix, gapsAsMissing: false, executable: engine) + for chains in [1, 2] { + var settings = AnalysisSettings() + settings.steps = 100 + settings.sampleEvery = 10 + settings.chains = chains + let draft = AnalysisDraft(matrix: matrix, report: report, settings: settings) + let directory = parent.appendingPathComponent("run-\(chains)") + let result = await RunProcess().execute( + RunRequest( + id: UUID(), executable: engine, + directory: directory, draft: draft) + ) { _ in } + #expect(result.status == .completed) + let entry = HistoryEntry.read(directory) + let model = RunAssessmentModel(entry: entry, executable: engine) + model.options.burnin = "20" + model.start() + await model.waitForExit() + #expect(model.error == nil, Comment(rawValue: model.details ?? "")) + let review = try #require(model.report) + #expect(review.burninPercent == 20 && !review.convergenceCertified) + #expect(review.sections.first(where: { $0.id == "completion" })?.status == "passed") + #expect( + review.sections.first(where: { $0.id == "agreement" })?.status + == (chains == 1 ? "unavailable" : "attention")) + let restored = RunAssessmentModel(entry: entry, executable: engine) + await restored.load() + #expect(restored.options.burnin == "20" && restored.report?.chainCount == chains) + let package = parent.appendingPathComponent("package-\(chains)") + model.options.includeMatrix = chains == 2 + model.start(exportTo: package) + await model.waitForExit() + #expect(model.error == nil, Comment(rawValue: model.details ?? "")) + #expect(model.exported == package) + #expect( + FileManager.default.fileExists(atPath: package.appendingPathComponent("matrix.nex").path) + == (chains == 2)) + #expect(HistoryEntry.read(package.appendingPathComponent("run")).status == .completed) + let manifest = try #require( + JSONSerialization.jsonObject( + with: Data(contentsOf: package.appendingPathComponent("manifest.json"))) as? [String: Any] + ) + let files = try #require(manifest["files"] as? [[String: Any]]) + for file in files { + let path = try #require(file["path"] as? String) + let hash = try #require(file["sha256"] as? String) + #expect(try TreeSource.fingerprint(package.appendingPathComponent(path)) == hash) + } + #expect(HistoryEntry.read(directory).status == .completed) + } + let entry = HistoryEntry.read(parent.appendingPathComponent("run-1")) + try Data("changed".utf8).write(to: matrix) + let changed = RunAssessmentModel(entry: entry, executable: engine) + changed.start() + await changed.waitForExit() + #expect(changed.report?.originalMatrixStatus == "changed") + changed.options.includeMatrix = true + let rejected = parent.appendingPathComponent("rejected") + changed.start(exportTo: rejected) + await changed.waitForExit() + #expect(changed.error != nil && !FileManager.default.fileExists(atPath: rejected.path)) + } + + @Test func histogramIncludesEveryPairAndHandlesConstantDifferences() { + let constant = PredictiveDistribution(name: "example", differences: [0, 0, 0], undefined: 2) + #expect(constant.bins.count == 1 && constant.bins[0].count == 3) + let spread = PredictiveDistribution( + name: "example", differences: [-2, -1, 0, 1, 4], undefined: 0) + #expect(spread.bins.map(\.count).reduce(0, +) == 5) + #expect(PredictiveDistribution(name: "undefined", differences: [], undefined: 2).bins.isEmpty) + } +} diff --git a/docs/es/guide/macos-preview.md b/docs/es/guide/macos-preview.md index a71c70a..2f6c6d2 100644 --- a/docs/es/guide/macos-preview.md +++ b/docs/es/guide/macos-preview.md @@ -482,3 +482,24 @@ El panel de enraizamiento dibuja la división impuesta: el terminal elegido a un Abre **Clock sigma prior** para ver cómo cambia la densidad gamma con Alpha y Beta, en la parametrización forma/escala. La línea discontinua marca la esperanza del prior; también se muestra su desviación estándar. El rango dibujado no es un intervalo de credibilidad. Con forma menor que uno, la densidad diverge en cero y la curva comienza por encima de cero. Las escalas numéricas extremas pueden no tener vista gráfica; esto no altera el prior del motor. La duración estimada corresponde al límite solicitado de pasos y usa el tiempo activo reciente del motor. No predice cuándo se establecerá la convergencia. Los controles de selección de caracteres y datación explican sus supuestos junto a la validación; estas explicaciones no demuestran adecuación para un estudio concreto. + +## Revisión de evidencias y paquetes de reproducción + +En **History → Evidence review**, elija el porcentaje de burn-in y actualice la revisión. `assessments/review-…/assessment.json` guarda una instantánea fechada con huellas SHA-256, registros originales, diagnósticos por cadena, una comparación nueva y rutas de informes de árboles y predictivos correspondientes. Actualice después de generar otros informes. El burn-in y la opción de incluir la matriz se guardan localmente junto a la ejecución. + +Finalización, muestreo de parámetros, concordancia entre cadenas, árboles y evidencia predictiva tienen estados separados. Los criterios escalares exigen al menos 1.000 muestras retenidas y ESS 200 por cadena, sin truncamiento de retardos. Entre cadenas también se requieren semillas distintas, entrada/modelo coincidentes y R-hat dividido y normalizado por rangos ≤ 1,01. Solo se excluyen parámetros verificados como fijos por el modelo. Una sola cadena no permite evaluar concordancia entre cadenas. Estos criterios diagnósticos no prueban convergencia ni sustituyen los umbrales configurables de parada. El soporte de árboles y las fracciones predictivas requieren interpretación; la evidencia ausente o inconsistente permanece visible. Las ejecuciones solo del prior describen su exploración, no la adecuación posterior. + +**Export reproducibility package…** crea una carpeta local nueva fuera de la ejecución. `manifest.json` enumera tamaños y SHA-256; `assessment.json` contiene una revisión nueva; `run/` contiene registros conocidos de Rove, muestras, checkpoints y resultados derivados. La matriz original solo se incluye al seleccionar **Include the original matrix in the export**, si coincide su huella registrada. La revisión indica originales modificados o no disponibles. No se copian archivos vecinos desconocidos, revisiones anteriores ni fuentes externas citadas por comparaciones. Se preservan rutas y nombres de taxones, se rechazan enlaces simbólicos y destinos existentes, se detectan cambios durante la copia y se conservan los originales. El ejecutable no se incluye: la reanudación exacta requiere un checkpoint válido y la identidad original del ejecutable, entrada y modelo; revise las rutas antes de reutilizar la configuración. + +Las mismas operaciones están disponibles en el motor: + +```sh +rove assess run-folder --output new-review-folder --burnin-percent 10 +rove export-run run-folder --output new-package-folder --burnin-percent 10 +# Incluir explícitamente una matriz original coincidente: +rove export-run run-folder --output another-package --include-matrix matrix.nex +``` + +La fuente puede ser una carpeta del app o de la CLI. Las ejecuciones incompletas pueden revisarse y archivarse conservando su estado. Se rechazan registros inválidos o estructuras de archivos inseguras. Los paquetes son carpetas locales, sin cargas a internet. + +Las comprobaciones predictivas guardadas muestran un histograma de estadísticas pareadas **simulado − observado**. Cada par usa el mismo árbol posterior; la estadística de parsimonia observada puede variar entre pares. Cero indica igualdad. El gráfico verifica conteos, empates y colas contra `predictive.json`, informa pares indefinidos y no se muestra si los registros discrepan. No evalúa convergencia ni decide automáticamente la adecuación. diff --git a/docs/guide/macos-preview.md b/docs/guide/macos-preview.md index 29ccb71..3a4e7a8 100644 --- a/docs/guide/macos-preview.md +++ b/docs/guide/macos-preview.md @@ -470,3 +470,24 @@ The rooting panel draws the actual constrained split: the selected terminal on o Expand **Clock sigma prior** to see the Gamma shape/scale density update as Alpha and Beta change. A dashed line marks the prior expectation; the panel also shows its standard deviation. The plotted range is a display window, not a credible interval. For shape below one, the density diverges at zero and the plotted curve starts above zero. Extreme numerical scales may have no graphical preview; this does not change the engine's prior. The run-time estimate predicts the requested step limit from recent active engine time. It does not predict when convergence will be established. Character-selection and fossil-dating controls explain their assumptions alongside their validation messages; these explanations do not establish that a model fits a particular study. + +## Evidence review and reproducibility packages + +In **History → Evidence review**, choose the burn-in percentage and refresh the review. The saved `assessments/review-…/assessment.json` is a dated snapshot with source SHA-256 fingerprints, the original run records, within-chain diagnostics, a fresh chain comparison and matching tree/predictive report paths. Refresh after generating new reports. The burn-in choice and matrix-inclusion option are saved locally beside the run. + +Completion, scalar sampling, independent-chain agreement, trees and predictive evidence have separate statuses. Scalar criteria are at least 1,000 retained draws and ESS 200 per chain without lag truncation. Between-chain criteria additionally require distinct seeds, matching input/model and rank-normalized split R-hat ≤ 1.01. Only independently verified model-fixed parameters are excluded. A single chain has no between-chain assessment. These are diagnostic reference criteria, not proof of convergence or the run's configurable stopping thresholds. Tree support and predictive tail fractions require interpretation; missing or inconsistent evidence stays visible. Prior-only runs describe prior exploration, not posterior adequacy. + +**Export reproducibility package…** creates a new local directory outside the run. `manifest.json` records the size and SHA-256 of each included file. `assessment.json` holds a fresh review; `run/` contains known Rove records, samples, checkpoints and derived-result folders. The original matrix is excluded unless **Include the original matrix in the export** is selected; inclusion requires its recorded fingerprint. Changed or unavailable originals appear in the review. Unknown neighboring files, previous assessments and external sources referenced by comparisons are not copied. Export preserves recorded paths and taxon names, refuses symbolic links and existing destinations, checks for changing source files and leaves originals untouched. It does not include the executable: exact resumption requires a valid checkpoint and the original executable/input/model identity; review paths before reusing the setup. + +The same operations are available in the engine: + +```sh +rove assess run-folder --output new-review-folder --burnin-percent 10 +rove export-run run-folder --output new-package-folder --burnin-percent 10 +# Explicitly include a matching original matrix: +rove export-run run-folder --output another-package --include-matrix matrix.nex +``` + +The source may be an app run folder or a CLI output folder. Incomplete runs can be reviewed and archived; their status is preserved. Malformed source records or unsafe file layouts are refused. Packages are directories, not uploaded archives. + +Saved posterior predictive checks also show a histogram of **simulated − observed** paired statistics. Each pair uses the same posterior tree; the observed parsimony statistic can therefore differ between pairs. Zero marks equality. The plot verifies replicate counts, ties and tails against `predictive.json`, reports undefined pairs and becomes unavailable if records disagree. It does not assess convergence or turn a tail fraction into an automatic adequacy decision. diff --git a/docs/pt-BR/guide/macos-preview.md b/docs/pt-BR/guide/macos-preview.md index 780604a..5fa830d 100644 --- a/docs/pt-BR/guide/macos-preview.md +++ b/docs/pt-BR/guide/macos-preview.md @@ -486,3 +486,24 @@ O painel de enraizamento desenha a divisão imposta: o terminal escolhido de um Abra **Prior do sigma do relógio** para ver a densidade gamma mudar com Alpha e Beta, na parametrização forma/escala. Uma linha tracejada marca a esperança do prior; o painel também mostra o desvio padrão. O trecho desenhado não é um intervalo de credibilidade. Com forma menor que um, a densidade diverge em zero e a curva começa acima de zero. Escalas numéricas extremas podem não ter prévia gráfica; isso não muda o prior do motor. A previsão de duração estima o limite de passos solicitado usando o tempo ativo recente do motor. Ela não prevê quando a convergência será estabelecida. As opções de seleção de caracteres e datação explicam suas hipóteses junto das mensagens de validação; essas explicações não demonstram adequação a um estudo específico. + +## Revisão das evidências e pacotes de reprodução + +Em **Histórico → Revisão das evidências**, escolha o burn-in e atualize a revisão. O arquivo `assessments/review-…/assessment.json` registra uma fotografia datada com identificadores SHA-256 das fontes, registros originais, diagnósticos por cadeia, uma comparação nova entre cadeias e caminhos dos relatórios de árvores e preditivos correspondentes. Atualize após gerar novos relatórios. O burn-in e a opção de incluir a matriz ficam salvos localmente junto à execução. + +Conclusão, amostragem dos parâmetros, concordância entre cadeias, árvores e evidências preditivas têm estados separados. Os critérios para parâmetros são pelo menos 1.000 amostras retidas e ESS de 200 por cadeia, sem truncamento de defasagens. A comparação entre cadeias exige também sementes distintas, entrada/modelo correspondentes e R-hat dividido e normalizado por postos ≤ 1,01. Somente parâmetros comprovadamente fixos pelo modelo são excluídos. Uma cadeia única não permite avaliar concordância entre cadeias. Esses critérios de diagnóstico não comprovam convergência nem substituem os limites configuráveis de parada da execução. Suporte de árvores e frações de cauda preditivas exigem interpretação; evidências ausentes ou inconsistentes ficam visíveis. Execuções apenas do prior descrevem a exploração do prior, não a adequação posterior. + +**Exportar pacote de reprodução…** cria uma pasta local nova fora da execução. `manifest.json` registra tamanho e SHA-256 de cada arquivo. `assessment.json` contém uma revisão nova; `run/` contém registros conhecidos do Rove, amostras, checkpoints e pastas de resultados derivados. A matriz original só é incluída com a opção **Incluir a matriz original na exportação**, mediante confirmação do identificador registrado. A revisão indica originais alterados ou indisponíveis. Arquivos vizinhos desconhecidos, revisões anteriores e fontes externas citadas em comparações não são copiados. A exportação preserva caminhos registrados e nomes de táxons, recusa links simbólicos e destinos existentes, verifica alterações das fontes e mantém os originais intactos. O executável não é incluído: a retomada exata exige checkpoint válido e a identidade original do executável, entrada e modelo; revise os caminhos antes de reutilizar a configuração. + +As mesmas operações estão disponíveis no motor: + +```sh +rove assess run-folder --output new-review-folder --burnin-percent 10 +rove export-run run-folder --output new-package-folder --burnin-percent 10 +# Incluir explicitamente uma matriz original correspondente: +rove export-run run-folder --output another-package --include-matrix matrix.nex +``` + +A origem pode ser uma pasta de execução do app ou da CLI. Execuções incompletas podem ser revisadas e arquivadas, preservando seu estado. Registros de origem inválidos ou estruturas de arquivos inseguras são recusados. Os pacotes são pastas locais, sem envio para a internet. + +As verificações preditivas salvas também mostram um histograma de estatísticas pareadas **simulado − observado**. Cada par usa a mesma árvore posterior; a estatística de parcimônia observada pode variar entre pares. Zero indica igualdade. O gráfico confere contagens, empates e caudas com `predictive.json`, informa pares indefinidos e fica indisponível quando os registros divergem. Não avalia convergência nem transforma uma fração de cauda em decisão automática de adequação. diff --git a/docs/zh-CN/guide/macos-preview.md b/docs/zh-CN/guide/macos-preview.md index b0e1831..bb62324 100644 --- a/docs/zh-CN/guide/macos-preview.md +++ b/docs/zh-CN/guide/macos-preview.md @@ -383,3 +383,24 @@ History 中已完成的运行包含 **Can the model reproduce the matrix?** 面 展开 **Clock sigma prior**,可查看 Gamma 密度随 Alpha 和 Beta 的变化,参数化为形状/尺度。虚线标示先验期望值,同时显示标准差。绘图范围不是可信区间。形状参数小于 1 时,密度在零处发散,因此曲线从大于零的位置开始。极端数值尺度可能无法绘图,但不会改变引擎使用的先验。 运行时间预测根据近期引擎活动时间估计达到所请求步数上限的时间,不预测何时能够确认收敛。性状选择和化石定年控件在验证信息旁解释相应假设;这些解释本身不能证明模型适合某项研究。 + +## 证据审查与可复现数据包 + +在 **History → Evidence review** 中选择预热比例并刷新审查。`assessments/review-…/assessment.json` 保存带时间戳的快照,包括源文件 SHA-256、原始运行记录、链内诊断、新计算的链间比较,以及匹配的树和后验预测报告路径。生成新报告后请刷新。预热比例和是否包含矩阵的选项保存在运行目录旁。 + +运行完成、标量采样、独立链一致性、树证据和预测证据分别显示状态。标量标准为每条链至少保留 1,000 个样本、ESS 至少 200,且没有滞后截断。链间比较还要求不同随机种子、相同输入与模型,以及秩归一化分割 R-hat ≤ 1.01。仅排除经核实由模型固定的参数。单链无法评估链间一致性。这些诊断参考标准既不证明收敛,也不替代可配置的停止阈值。树支持度和预测尾部比例仍需解释;缺失或不一致的证据会明确显示。仅先验运行描述先验探索,不能说明后验模型适合度。 + +**Export reproducibility package…** 在运行目录外新建本地文件夹。`manifest.json` 列出文件大小和 SHA-256;`assessment.json` 保存新审查;`run/` 包含已知的 Rove 记录、样本、检查点及派生结果。只有明确选中 **Include the original matrix in the export** 且指纹匹配时才包含原矩阵。审查会标明原矩阵已更改或不可用。不复制未知相邻文件、以前的审查或比较报告引用的外部数据源。导出保留记录中的路径和分类单元名称,拒绝符号链接和现有目标,检查复制过程中源文件是否变化,并保持原件不变。数据包不包含可执行文件:精确恢复需要有效检查点以及原可执行文件、输入和模型身份;复用配置前请检查路径。 + +引擎提供相同操作: + +```sh +rove assess run-folder --output new-review-folder --burnin-percent 10 +rove export-run run-folder --output new-package-folder --burnin-percent 10 +# 明确包含指纹匹配的原矩阵: +rove export-run run-folder --output another-package --include-matrix matrix.nex +``` + +源目录可以来自应用或 CLI。未完成运行也可审查和归档,其状态会保留。无效源记录或不安全的文件结构会被拒绝。数据包是本地文件夹,不会上载网络。 + +已保存的后验预测检验还显示 **模拟值 − 观测值** 的配对统计量直方图。每一对使用同一后验树,因此观测简约统计量可能随树变化。零表示相等。图表将配对数量、相等次数和尾部计数与 `predictive.json` 核对,报告未定义配对;记录不一致时不显示分布。它不评估收敛,也不会根据尾部比例自动判断模型适合度。 diff --git a/src/bin/rove/assessment.rs b/src/bin/rove/assessment.rs new file mode 100644 index 0000000..fa77aed --- /dev/null +++ b/src/bin/rove/assessment.rs @@ -0,0 +1,392 @@ +//! Evidence review and local reproducibility packages. No convergence certificate. +use std::collections::{BTreeMap, HashSet}; +use std::error::Error; +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use rove::summary::Burnin; +use serde_json::{Value, json}; + +use super::{compare, diagnose, events::Cancellation, sha256, summarize}; + +type Result = std::result::Result>; + +struct Output(PathBuf, bool); +impl Drop for Output { + fn drop(&mut self) { + if !self.1 { + let _ = fs::remove_dir_all(&self.0); + } + } +} + +fn write(path: &Path, value: &Value) -> Result<()> { + fs::write(path, serde_json::to_vec_pretty(value)?)?; + Ok(()) +} + +fn check(cancel: &dyn Fn() -> bool) -> Result<()> { + if cancel() { + Err("assessment/export cancelled".into()) + } else { + Ok(()) + } +} + +fn inventory(root: &Path, cancel: &dyn Fn() -> bool) -> Result> { + fn visit( + root: &Path, + relative: &Path, + depth: usize, + out: &mut BTreeMap, + cancel: &dyn Fn() -> bool, + ) -> Result<()> { + check(cancel)?; + if depth > 16 || out.len() >= 100_000 { + return Err("run archive exceeds file/depth limit".into()); + } + let path = root.join(relative); + let meta = fs::symlink_metadata(&path)?; + if meta.file_type().is_symlink() { + return Err("run archive contains a symbolic link".into()); + } + if meta.is_file() { + out.insert(relative.to_owned(), sha256::file(&path)?); + } else if meta.is_dir() { + for child in fs::read_dir(path)? { + visit( + root, + &relative.join(child?.file_name()), + depth + 1, + out, + cancel, + )?; + } + } else { + return Err("run archive contains a non-regular file".into()); + } + Ok(()) + } + let mut files = BTreeMap::new(); + // Export only Rove-owned records and derived-result folders, not neighboring research files. + for child in fs::read_dir(root)? { + let child = child?; + let name = child.file_name(); + let text = name.to_str().ok_or("non-UTF-8 run filename")?; + if matches!( + text, + "results" + | "run.json" + | "trace.log" + | "trees.nexus" + | "setup.rove.json" + | "session.json" + | "engine.stderr.log" + | "events.jsonl" + | "dating.json" + | "comparison.json" + | "checkpoint.json" + | "diagnostics" + | "comparisons" + | "predictions" + | "summaries" + | "marginal" + ) || (text.starts_with("checkpoint-") && text.ends_with(".bin")) + || (text.starts_with("chain-") && text[6..].parse::().is_ok()) + { + visit(root, Path::new(&name), 0, &mut files, cancel)?; + } + } + Ok(files) +} + +fn section(id: &str, status: &str, message: &str) -> Value { + json!({"id":id, "status":status, "message":message}) +} + +fn assess( + root: &Path, + burnin: u8, + files: &BTreeMap, + cancel: &dyn Fn() -> bool, +) -> Result { + let engine = if root.join("results/run.json").exists() { + root.join("results") + } else { + root.to_owned() + }; + let record = summarize::record(&engine.join("run.json"))?; + let grouped = record["kind"] == "independent_chains"; + let directories = if grouped { + let n = record["chain_count"] + .as_u64() + .filter(|n| (2..=16).contains(n)) + .ok_or("invalid chain count")?; + (1..=n) + .map(|i| engine.join(format!("chain-{i:02}"))) + .collect::>() + } else { + vec![engine.clone()] + }; + let mut sections = Vec::new(); + let mut diagnostics = Vec::new(); + let mut completed = record["status"] == "completed"; + if root.join("session.json").exists() { + let session = summarize::record(&root.join("session.json"))?; + completed &= session["status"] == "completed" && session["exitCode"] == 0; + } + for directory in &directories { + match diagnose::inspect( + &directory.join("trace.log"), + Burnin::Percent(burnin), + cancel, + ) { + Ok(mut value) => { + completed &= value["source"]["completion"] == "completed"; + if let Some(columns) = value["columns"].as_array_mut() { + for column in columns { + column.as_object_mut().unwrap().remove("points"); + } + } + diagnostics.push(value); + } + Err(error) => { + check(cancel)?; + completed = false; + diagnostics.push(json!({"source":{"path":directory.join("trace.log")},"error":error.to_string()})); + } + } + } + let comparison = (|| -> Result { + let records = compare::compatible_records(&directories)?; + let first = &records[0]; + if grouped { + let children = record["chains"] + .as_array() + .ok_or("missing group chain records")?; + if children.len() != directories.len() { + return Err("group chain count mismatch".into()); + } + for (i, child) in children.iter().enumerate() { + if child["index"] != i + 1 + || child["directory"] != format!("chain-{:02}", i + 1) + || child["seed"] != records[i]["settings"]["seed"] + || records[i]["input"]["sha256"] != record["input"]["sha256"] + || records[i]["settings"]["steps"] != record["settings"]["steps"] + || records[i]["settings"]["sample_every"] != record["settings"]["sample_every"] + { + return Err("group metadata disagrees with a chain".into()); + } + } + } + let constraints: Vec> = + serde_json::from_value(first["model"]["monophyly"].clone())?; + compare::summarize( + &directories, + burnin as usize, + &constraints, + first["model"].get("dating"), + cancel, + false, + ) + })(); + let (comparison, consistent) = match comparison { + Ok(value) => (value, true), + Err(error) => { + check(cancel)?; + (json!({"error":error.to_string()}), false) + } + }; + completed &= consistent && diagnostics.iter().all(|d| d.get("error").is_none()); + sections.push(section("completion", if completed {"passed"} else {"attention"}, + if completed {"Recorded steps and sample files agree. Completion is not convergence."} else {"The run is unfinished, incomplete or inconsistent. Review the source records and errors."})); + let enough = comparison["retained_per_chain"].as_u64().unwrap_or(0) >= 1000; + let scalar_pass = completed + && enough + && comparison["statistics"].as_array().is_some_and(|columns| { + columns.iter().any(|v| v["fixed_by_model"] != true) + && columns.iter().all(|v| { + v["fixed_by_model"] == true + || (v["ess"].as_array().is_some_and(|values| { + values + .iter() + .all(|x| x.as_f64().is_some_and(|x| x >= 200.0)) + }) && v["lag_limit_reached"] + .as_array() + .is_some_and(|values| values.iter().all(|x| x == false))) + }) + }); + sections.push(section("sampling", if !consistent {"unavailable"} else if scalar_pass {"passed"} else {"attention"}, + "Review every sampled scalar: at least 1,000 retained draws and ESS 200 per chain, with no lag truncation. Verified model-fixed values are excluded; stuck sampled values are not.")); + sections.push(section("agreement", if !consistent || directories.len() == 1 {"unavailable"} else if completed && compare::thresholds_met(&comparison, 200.0, 1.01) {"passed"} else {"attention"}, + "Between-chain assessment requires independent seeds, matching input/model, ESS 200 per chain, at least 1,000 retained draws and rank-normalized split R-hat at most 1.01. These diagnostics do not prove convergence.")); + let mut summaries = Vec::new(); + let mut predictions = Vec::new(); + for relative in files.keys() { + check(cancel)?; + let name = relative.file_name().and_then(|s| s.to_str()).unwrap_or(""); + if !matches!(name, "summary.json" | "predictive.json") { + continue; + } + let value = match summarize::record(&root.join(relative)) { + Ok(v) => v, + Err(_) => continue, + }; + // Presence is not adequacy: only list reports whose recorded source hashes match this snapshot. + let matched = directories.iter().any(|directory| { + let prefix = directory.strip_prefix(root).unwrap(); + let trees = files.get(&prefix.join("trees.nexus")); + if name == "summary.json" { + value["status"] == "completed" + && trees.is_some_and(|h| value["source"]["sha256"] == *h) + } else { + value["status"] == "completed" + && value["method"] == "posterior-predictive-paired-v1" + && trees.is_some_and(|h| value["source"]["trees_sha256"] == *h) + && files + .get(&prefix.join("trace.log")) + .is_some_and(|h| value["source"]["trace_sha256"] == *h) + && files + .get(&prefix.join("run.json")) + .is_some_and(|h| value["source"]["run_sha256"] == *h) + } + }); + if matched { + if name == "summary.json" { + summaries.push(relative); + } else { + predictions.push(relative); + } + } + } + sections.push(section("trees", if summaries.is_empty() {"unavailable"} else {"review_required"}, + "Review tree summaries and unconstrained clade frequencies. High support or agreement on constant clades does not establish exploration of tree space.")); + sections.push(section("prediction", if predictions.is_empty() {"unavailable"} else {"review_required"}, + "Review paired predictive discrepancies, undefined pairs and simulation uncertainty. A saved check alone does not establish model adequacy.")); + let input = if grouped { + summarize::record(&directories[0].join("run.json")) + .ok() + .map(|v| v["input"].clone()) + .unwrap_or(Value::Null) + } else { + record["input"].clone() + }; + let input_status = input["path"] + .as_str() + .map(|p| match sha256::file(Path::new(p)) { + Ok(h) if input["sha256"] == h => "matches", + Ok(_) => "changed", + Err(_) => "unavailable", + }) + .unwrap_or("unavailable"); + Ok( + json!({"schema_version":1,"kind":"run_assessment","rove_version":env!("CARGO_PKG_VERSION"), + "created_unix_seconds":SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(), + "source":root,"chain_count":directories.len(),"burnin_percent":burnin, + "input":input,"original_matrix_status":input_status,"run_record":record, + "criteria":{"minimum_retained_per_chain":1000,"min_ess_per_chain":200,"max_rhat":1.01}, + "sections":sections,"diagnostics":diagnostics,"comparison":comparison, + "tree_reports":summaries,"predictive_reports":predictions,"convergence_certified":false, + "source_files":files.iter().map(|(p,h)|json!({"path":p,"sha256":h})).collect::>()}), + ) +} + +pub(super) fn run(arguments: &[String], export: bool) -> Result<()> { + let mut input = None; + let mut output = None; + let mut matrix = None; + let mut burnin = 10u8; + let mut cancel_on_close = false; + let mut seen = HashSet::new(); + let mut args = arguments.iter(); + while let Some(arg) = args.next() { + if arg.starts_with("--") && !seen.insert(arg) { + return Err(format!("duplicate option {arg}").into()); + } + match arg.as_str() { + "--output" => { + output = Some(PathBuf::from( + args.next().ok_or("missing output directory")?, + )) + } + "--include-matrix" if export => { + matrix = Some(PathBuf::from(args.next().ok_or("missing matrix path")?)) + } + "--burnin-percent" => burnin = args.next().ok_or("missing burn-in")?.parse()?, + "--cancel-on-stdin-close" => cancel_on_close = true, + path if !path.starts_with('-') && input.is_none() => input = Some(PathBuf::from(path)), + _ => return Err(format!("unsupported assessment/export argument {arg}").into()), + } + } + if burnin >= 100 { + return Err("burn-in must be between 0 and 99 percent".into()); + } + let root = input.ok_or("missing run directory")?.canonicalize()?; + let output = output.ok_or("missing --output new directory")?; + let parent = output + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + let output = parent + .canonicalize()? + .join(output.file_name().ok_or("invalid output directory")?); + if export && output.starts_with(&root) { + return Err("export destination must be outside the source run".into()); + } + if output.exists() { + return Err("output directory already exists".into()); + } + let cancellation = Cancellation::watch_stdin(cancel_on_close); + let cancel = || cancellation.requested(); + let before = inventory(&root, &cancel)?; + let report = assess(&root, burnin, &before, &cancel)?; + fs::create_dir(&output)?; + let mut guard = Output(output.clone(), false); + write(&output.join("assessment.json"), &report)?; + if export { + let mut entries = Vec::new(); + for (relative, hash) in &before { + check(&cancel)?; + let target = output.join("run").join(relative); + fs::create_dir_all(target.parent().unwrap())?; + fs::copy(root.join(relative), &target)?; + if sha256::file(&target)? != *hash { + return Err("source changed while exporting".into()); + } + entries.push(json!({"path":Path::new("run").join(relative),"sha256":hash,"bytes":fs::metadata(&target)?.len()})); + } + if let Some(source) = matrix.as_ref() { + let hash = sha256::file(source)?; + if report["input"]["sha256"] != hash { + return Err("included matrix does not match the run fingerprint".into()); + } + let target = output.join("matrix.nex"); + fs::copy(source, &target)?; + if sha256::file(&target)? != hash { + return Err("matrix changed while exporting".into()); + } + entries.push( + json!({"path":"matrix.nex","sha256":hash,"bytes":fs::metadata(target)?.len()}), + ); + } + entries.push(json!({"path":"assessment.json","sha256":sha256::file(&output.join("assessment.json"))?,"bytes":fs::metadata(output.join("assessment.json"))?.len()})); + write( + &output.join("manifest.json"), + &json!({"schema_version":1,"kind":"rove_reproducibility_package", + "created_unix_seconds":report["created_unix_seconds"],"rove_version":env!("CARGO_PKG_VERSION"), + "export_executable_sha256":sha256::file(&std::env::current_exe()?)?,"source":root, + "matrix_included":matrix.is_some(),"files":entries, + "exact_resume":"Requires a valid checkpoint, the original executable fingerprint and original model/input identity. This package does not include the executable. Paths in source records are preserved; review paths before reuse.", + "scope":"Known Rove records, raw samples and derived-result folders; previous assessments, neighboring files and external comparison sources are not copied. Export does not certify convergence."}), + )?; + } + if inventory(&root, &cancel)? != before { + return Err( + "run files changed during assessment/export; retry after the run finishes".into(), + ); + } + check(&cancel)?; + guard.1 = true; + Ok(()) +} diff --git a/src/bin/rove/compare.rs b/src/bin/rove/compare.rs index 234725f..b063710 100644 --- a/src/bin/rove/compare.rs +++ b/src/bin/rove/compare.rs @@ -271,10 +271,27 @@ pub(super) fn run(arguments: &[String]) -> Result<(), Box> { "compare needs 2 to 16 run directories and burn-in from 0 to 99 percent".into(), ); } + let records = compatible_records(&directories)?; + let first = &records[0]; + let constraints: Vec> = + serde_json::from_value(first["model"]["monophyly"].clone())?; + let summary = summarize( + &directories, + burnin, + &constraints, + first["model"].get("dating"), + &|| false, + true, + )?; + println!("{}", serde_json::to_string_pretty(&summary)?); + Ok(()) +} + +pub(super) fn compatible_records(directories: &[PathBuf]) -> Result, Box> { let records = directories .iter() .map(|d| -> Result> { - let mut record: Value = serde_json::from_slice(&fs::read(d.join("run.json"))?)?; + let mut record = super::summarize::record(&d.join("run.json"))?; // Records before configurable sigma priors used the reference prior. if record["model"] .get("clock_sigma_prior_parameters") @@ -294,28 +311,18 @@ pub(super) fn run(arguments: &[String]) -> Result<(), Box> { Ok(record) }) .collect::, _>>()?; - let first = &records[0]; + let first = records.first().ok_or("no chain directories")?; let mut seeds = std::collections::HashSet::new(); for record in &records { if record["input"]["sha256"] != first["input"]["sha256"] + || record["input"]["gaps"] != first["input"]["gaps"] || record["model"] != first["model"] || !seeds.insert(record["settings"]["seed"].as_u64().ok_or("missing seed")?) { return Err("comparison requires the same input and model, with distinct seeds".into()); } } - let constraints: Vec> = - serde_json::from_value(first["model"]["monophyly"].clone())?; - let summary = summarize( - &directories, - burnin, - &constraints, - first["model"].get("dating"), - &|| false, - true, - )?; - println!("{}", serde_json::to_string_pretty(&summary)?); - Ok(()) + Ok(records) } #[cfg(test)] diff --git a/src/bin/rove/main.rs b/src/bin/rove/main.rs index 46e9a59..ecdca00 100644 --- a/src/bin/rove/main.rs +++ b/src/bin/rove/main.rs @@ -1,3 +1,4 @@ +mod assessment; mod benchmark; mod checkpoint; mod compare; @@ -51,6 +52,9 @@ const USAGE: &str = [--expect-input-sha256 ] rove benchmark [--cancel-on-stdin-close] rove compare ... [--burnin-percent <0..99>] + rove assess --output [--burnin-percent <0..99>] + rove export-run --output [--burnin-percent <0..99>] + [--include-matrix ] [--cancel-on-stdin-close] rove inspect [--gaps reject|missing] [--partitioning observed|declared|labels] rove inspect-tree rove diagnose --burnin-percent <0..99> [--output ] @@ -1241,7 +1245,12 @@ fn run_chain( fn main() { let arguments: Vec = std::env::args().skip(1).collect(); - let result = if arguments.first().is_some_and(|a| a == "benchmark") { + let result = if arguments + .first() + .is_some_and(|a| a == "assess" || a == "export-run") + { + assessment::run(&arguments[1..], arguments[0] == "export-run").map(|_| true) + } else if arguments.first().is_some_and(|a| a == "benchmark") { benchmark::run(&arguments[1..]) } else if arguments.first().is_some_and(|a| a == "predict") { predict::run(&arguments[1..]).map(|_| true) diff --git a/tests/assessment_cli.rs b/tests/assessment_cli.rs new file mode 100644 index 0000000..93489d8 --- /dev/null +++ b/tests/assessment_cli.rs @@ -0,0 +1,222 @@ +use serde_json::Value; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +fn call(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_rove")) + .args(args) + .output() + .unwrap() +} +fn good(output: Output) { + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} +fn read(path: impl AsRef) -> Value { + serde_json::from_slice(&fs::read(path).unwrap()).unwrap() +} +fn fixture(name: &str, chains: &str) -> PathBuf { + let root = Path::new(env!("CARGO_TARGET_TMPDIR")).join(name); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + fs::write(root.join("matrix.nex"), "#NEXUS BEGIN DATA; DIMENSIONS NTAX=4 NCHAR=4; FORMAT SYMBOLS=\"01\"; MATRIX A 0000 B 0011 C 1100 D 1111; END;").unwrap(); + good(call(&[ + "sample", + root.join("matrix.nex").to_str().unwrap(), + "--output", + root.join("run").to_str().unwrap(), + "--seed", + "42", + "--steps", + "100", + "--sample-every", + "10", + "--chains", + chains, + ])); + root +} +fn assess(root: &Path, name: &str) -> Value { + good(call(&[ + "assess", + root.join("run").to_str().unwrap(), + "--output", + root.join(name).to_str().unwrap(), + ])); + read(root.join(name).join("assessment.json")) +} +fn status<'a>(report: &'a Value, id: &str) -> &'a Value { + &report["sections"] + .as_array() + .unwrap() + .iter() + .find(|v| v["id"] == id) + .unwrap()["status"] +} + +#[test] +fn review_distinguishes_finished_short_single_chain_from_convergence() { + let root = fixture("assessment-single", "1"); + let report = assess(&root, "review"); + assert_eq!(status(&report, "completion"), "passed"); + assert_eq!(status(&report, "sampling"), "attention"); + assert_eq!(status(&report, "agreement"), "unavailable"); + assert_eq!(status(&report, "prediction"), "unavailable"); + assert_eq!(report["convergence_certified"], false); + assert_eq!(report["original_matrix_status"], "matches"); + let log = root.join("run/trace.log"); + let original = fs::read_to_string(&log).unwrap(); + fs::write( + &log, + original + .lines() + .take(original.lines().count() - 1) + .collect::>() + .join("\n") + + "\n", + ) + .unwrap(); + let bad = assess(&root, "truncated"); + assert_eq!(status(&bad, "completion"), "attention"); + assert!( + bad["diagnostics"][0]["error"] + .as_str() + .unwrap() + .contains("truncated") + ); +} + +#[test] +fn chain_group_checks_child_identity_before_assessing_agreement() { + let root = fixture("assessment-group", "2"); + let report = assess(&root, "review"); + assert_eq!(status(&report, "completion"), "passed"); + assert_eq!(status(&report, "agreement"), "attention"); + let file = root.join("run/chain-02/run.json"); + let mut record = read(&file); + record["model"]["partitioning"] = Value::String("declared".into()); + fs::write(file, serde_json::to_vec(&record).unwrap()).unwrap(); + let incompatible = assess(&root, "mixed"); + assert_eq!(status(&incompatible, "agreement"), "unavailable"); + assert_eq!(status(&incompatible, "completion"), "attention"); +} + +#[test] +fn archive_preserves_sources_and_requires_explicit_matching_matrix() { + let root = fixture("assessment-export", "1"); + let original = fs::read(root.join("run/trace.log")).unwrap(); + good(call(&[ + "export-run", + root.join("run").to_str().unwrap(), + "--output", + root.join("package").to_str().unwrap(), + ])); + let manifest = read(root.join("package/manifest.json")); + assert_eq!(manifest["matrix_included"], false); + assert!(!root.join("package/matrix.nex").exists()); + assert_eq!( + fs::read(root.join("package/run/trace.log")).unwrap(), + original + ); + assert_eq!(fs::read(root.join("run/trace.log")).unwrap(), original); + assert!( + manifest["files"] + .as_array() + .unwrap() + .iter() + .all(|v| v["sha256"].as_str().unwrap().len() == 64) + ); + good(call(&[ + "export-run", + root.join("run").to_str().unwrap(), + "--output", + root.join("with-matrix").to_str().unwrap(), + "--include-matrix", + root.join("matrix.nex").to_str().unwrap(), + ])); + assert_eq!( + fs::read(root.join("with-matrix/matrix.nex")).unwrap(), + fs::read(root.join("matrix.nex")).unwrap() + ); + fs::write(root.join("matrix.nex"), "changed").unwrap(); + let changed = assess(&root, "changed"); + assert_eq!(changed["original_matrix_status"], "changed"); + let failed = call(&[ + "export-run", + root.join("run").to_str().unwrap(), + "--output", + root.join("rejected").to_str().unwrap(), + "--include-matrix", + root.join("matrix.nex").to_str().unwrap(), + ]); + assert!(!failed.status.success()); + assert!(!root.join("rejected").exists()); + assert!( + !call(&[ + "export-run", + root.join("run").to_str().unwrap(), + "--output", + root.join("package").to_str().unwrap() + ]) + .status + .success() + ); + assert!( + !call(&[ + "export-run", + root.join("run").to_str().unwrap(), + "--output", + root.join("run/nested").to_str().unwrap() + ]) + .status + .success() + ); +} + +#[test] +fn reports_require_matching_source_fingerprints() { + let root = fixture("assessment-reports", "1"); + fs::create_dir(root.join("run/summaries")).unwrap(); + good(call(&[ + "summarize", + root.join("run/trees.nexus").to_str().unwrap(), + "--output", + root.join("run/summaries/first").to_str().unwrap(), + "--burnin-percent", + "10", + "--heights", + "keep", + ])); + let report = assess(&root, "review"); + assert_eq!(status(&report, "trees"), "review_required"); + let file = root.join("run/summaries/first/summary.json"); + let mut summary = read(&file); + summary["source"]["sha256"] = Value::String("0".repeat(64)); + fs::write(&file, serde_json::to_vec(&summary).unwrap()).unwrap(); + let changed = assess(&root, "changed"); + assert_eq!(status(&changed, "trees"), "unavailable"); +} + +#[cfg(unix)] +#[test] +fn exports_reject_symlinked_artifacts() { + let root = fixture("assessment-symlinks", "1"); + fs::create_dir(root.join("run/predictions")).unwrap(); + std::os::unix::fs::symlink(root.join("matrix.nex"), root.join("run/predictions/linked")) + .unwrap(); + assert!( + !call(&[ + "export-run", + root.join("run").to_str().unwrap(), + "--output", + root.join("package").to_str().unwrap() + ]) + .status + .success() + ); + assert!(!root.join("package").exists()); +} diff --git a/tools/native/cli-parity.json b/tools/native/cli-parity.json index 2088c25..246e029 100644 --- a/tools/native/cli-parity.json +++ b/tools/native/cli-parity.json @@ -8,7 +8,9 @@ "diagnose": "apps/macos/Sources/RoveApp/TraceDiagnosticsView.swift", "summarize": "apps/macos/Sources/RoveApp/TreeSummaryView.swift", "predict": "apps/macos/Sources/RoveApp/PredictiveCheckView.swift", - "compare": "apps/macos/Sources/RoveApp/RunComparisonView.swift" + "compare": "apps/macos/Sources/RoveApp/RunComparisonView.swift", + "assess": "apps/macos/Sources/RoveApp/RunAssessmentView.swift", + "export-run": "apps/macos/Sources/RoveApp/RunAssessmentView.swift" }, "flags": { "--alpha": { @@ -158,6 +160,10 @@ "--weight": { "native": "apps/macos/Sources/RoveApp/AdvancedOptionsView.swift", "control": "Advanced sampling" + }, + "--include-matrix": { + "native": "apps/macos/Sources/RoveApp/RunAssessmentView.swift", + "control": "Explicit original-matrix inclusion in local reproducibility export" } } }