# src/artifacts.jl # --------------------------------------------------------------------------- # Result persistence. # # Ion images and feature matrices must never be dumped into the JSON-RPC channel # verbatim: a 2000×2000 float matrix is ~32 MB of JSON and stalls the model. # Tools return compact statistics + a downsampled preview, and the full data is # written to disk under `artifacts//`. # --------------------------------------------------------------------------- const ARTIFACT_LOCK = ReentrantLock() """Root directory for generated files (override with `JULIA_MSI_MCP_ARTIFACTS`).""" function artifact_root() root = get(ENV, "JULIA_MSI_MCP_ARTIFACTS", "") if isempty(root) root = joinpath(pkgdir(@__MODULE__), "artifacts") end root = abspath(expanduser(root)) lock(ARTIFACT_LOCK) do isdir(root) || mkpath(root) end return root end function artifact_dir(task_id::AbstractString; label::AbstractString="") dir = joinpath(artifact_root(), safe_filename(task_id, "task")) if !isempty(label) dir = joinpath(dir, safe_filename(label, "output")) end lock(ARTIFACT_LOCK) do isdir(dir) || mkpath(dir) end return dir end """ artifact_retention_config() -> (max_age_days, max_total_bytes) Read the retention policy from the environment. Both knobs default to disabled: - `JULIA_MSI_MCP_ARTIFACT_MAX_AGE_DAYS` (default 7): remove task dirs older than this. - `JULIA_MSI_MCP_ARTIFACT_MAX_BYTES` (default 0): trim oldest dirs until the root is under this many bytes (0 disables the size budget). """ function artifact_retention_config() max_age_days = try parse(Float64, get(ENV, "JULIA_MSI_MCP_ARTIFACT_MAX_AGE_DAYS", "7")) catch 7.0 end max_total_bytes = try parse(Float64, get(ENV, "JULIA_MSI_MCP_ARTIFACT_MAX_BYTES", "0")) catch 0.0 end return max_age_days, max_total_bytes end function _dir_size_bytes(path::AbstractString) total = 0 try for (root, _dirs, files) in walkdir(path) for f in files p = joinpath(root, f) try total += filesize(p) catch end end end catch end return total end """ prune_artifacts!(; max_age_days=0.0, max_total_bytes=0.0, dry_run=false) Delete artifact task-directories older than `max_age_days` (0 disables age-based pruning) and, if `max_total_bytes > 0`, remove oldest-first until the artifact root fits the budget. Only top-level task directories (one per task) are considered. Returns a summary dict with `removed`, `freed_bytes`, `remaining_bytes` and `dry_run`. """ function prune_artifacts!(; max_age_days::Real=0.0, max_total_bytes::Real=0.0, dry_run::Bool=false) root = artifact_root() removed = 0 freed = 0 lock(ARTIFACT_LOCK) do entries = sort!([(mtime(p), p) for p in readdir(root; join=true) if isdir(p)]; by=first) # oldest first handled = Set{String}() # Age-based pruning. if max_age_days > 0 for (mt, path) in entries if time() - mt > max_age_days * 86400 freed += _dir_size_bytes(path) dry_run || rm(path; recursive=true, force=true) push!(handled, path) removed += 1 end end end # Size budget: oldest-first until the root fits. if max_total_bytes > 0 for (_, path) in entries path in handled && continue _dir_size_bytes(root) <= max_total_bytes && break freed += _dir_size_bytes(path) dry_run || rm(path; recursive=true, force=true) push!(handled, path) removed += 1 end end end remaining_bytes = _dir_size_bytes(root) return Dict{String,Any}( "removed" => removed, "freed_bytes" => freed, "remaining_bytes" => remaining_bytes, "dry_run" => dry_run, "root" => root, ) end function artifact_record(path::AbstractString) isfile(path) || return nothing return Dict{String,Any}( "path" => String(path), "uri" => "file://" * String(path), "name" => basename(path), "bytes" => filesize(path), "mime_type" => if endswith(lowercase(path), ".csv") "text/csv" elseif endswith(lowercase(path), ".pgm") "image/x-portable-graymap" elseif endswith(lowercase(path), ".mtx") "text/plain" elseif endswith(lowercase(path), ".json") JSON_MIME else "application/octet-stream" end, ) end function write_json_file(path::AbstractString, payload) open(path, "w") do io JSON3.write(io, jsonable(payload)) end return artifact_record(path) end """Write an intensity matrix as CSV with a `y\\x` header row.""" function write_matrix_csv(path::AbstractString, mat::AbstractMatrix{<:Real}) h, w = size(mat) open(path, "w") do io print(io, "y\\x") for x in 1:w print(io, ",", x) end println(io) for y in 1:h print(io, y) for x in 1:w v = Float64(mat[y, x]) print(io, ",", isfinite(v) ? repr(v) : "0.0") end println(io) end end return artifact_record(path) end """Write a normalized 8-bit grayscale PGM (viewable in most image apps).""" function write_matrix_pgm(path::AbstractString, mat::AbstractMatrix{<:Real}) h, w = size(mat) vmax = 0.0 @inbounds for v in mat f = Float64(v) isfinite(f) && f > vmax && (vmax = f) end scale = vmax > 0 ? 255.0 / vmax : 0.0 open(path, "w") do io write(io, "P5\n# JuliaMSI_MCP ion image (normalized to max)\n$(w) $(h)\n255\n") buf = Vector{UInt8}(undef, h * w) k = 1 # PGM is row-major; Julia matrices are column-major. for y in 1:h, x in 1:w v = Float64(mat[y, x]) buf[k] = (!isfinite(v) || v <= 0) ? 0x00 : round(UInt8, clamp(v * scale, 0.0, 255.0)) k += 1 end write(io, buf) end return artifact_record(path) end """Write a vector as a two-column CSV (`index,value`).""" function write_vector_csv(path::AbstractString, values::AbstractVector{<:Real}; header::AbstractString="index,value") open(path, "w") do io println(io, header) for (i, v) in enumerate(values) println(io, i, ",", repr(Float64(v))) end end return artifact_record(path) end """Stream a `SparseMatrixCSC` to Matrix Market coordinate format.""" function write_sparse_mtx(path::AbstractString, mat::SparseMatrixCSC) m, n = size(mat) open(path, "w") do io write(io, "%%MatrixMarket matrix coordinate real general\n") write(io, "$(m) $(n) $(SparseArrays.nnz(mat))\n") rows = SparseArrays.rowvals(mat) vals = SparseArrays.nonzeros(mat) @inbounds for j in 1:n for idx in SparseArrays.nzrange(mat, j) write(io, "$(rows[idx]) $(j) $(vals[idx])\n") end end end return artifact_record(path) end """Persist a single ion image (CSV + PGM + JSON sidecar) and return the paths.""" function persist_ion_image(dir::AbstractString, label::AbstractString, mat::AbstractMatrix{<:Real}; extra=nothing) base = safe_filename(label, "ion_image") csv = write_matrix_csv(joinpath(dir, base * ".csv"), mat) pgm = write_matrix_pgm(joinpath(dir, base * ".pgm"), mat) sidecar = Dict{String,Any}( "label" => String(label), "stats" => matrix_stats(mat), "artifacts" => Dict{String,Any}("csv" => csv, "pgm" => pgm), ) extra !== nothing && (sidecar["metadata"] = extra) meta = write_json_file(joinpath(dir, base * ".json"), sidecar) return Dict{String,Any}("csv" => csv, "pgm" => pgm, "metadata" => meta) end """Top-N bins by total intensity for a feature matrix.""" function top_bins(mat::SparseMatrixCSC, bin_centers::AbstractVector{<:Real}; n::Integer=20) totals = vec(sum(mat; dims=2)) positive = findall(>(0), totals) isempty(positive) && return Any[] k = min(Int(n), length(positive)) order = positive[sortperm(totals[positive]; rev=true)[1:k]] return [Dict{String,Any}( "bin" => Int(i), "mz" => compact_float(bin_centers[i]), "total_intensity" => compact_float(totals[i]), "spectra_with_signal" => count(>(0), mat[i, :]), ) for i in order] end