|
| 1 | +//! atlas-classify — the Atlas classification operating procedure |
| 2 | +//! CLI (#12405): the unclassified-remainder sweep and the |
| 3 | +//! schema-change review from the classification design |
| 4 | +//! (`doc/2026-11-21T21-32-00Z_design_atlas_classification_model_v1.md`, |
| 5 | +//! §5.1/§5.2), over the decision records of #12402. |
| 6 | +//! |
| 7 | +//! Command-line contract (#3352): the whole command line is |
| 8 | +//! declared here and parsed strictly before any file is opened; |
| 9 | +//! anything unaccounted for is a usage error with exit code 2. |
| 10 | +//! |
| 11 | +//! Usage: |
| 12 | +//! atlas-classify --db CORPUS.db run [--commit] |
| 13 | +//! [--window-days N] [--actor A] [--now TS] |
| 14 | +//! [--schema-version N] [--max-decisions N] |
| 15 | +//! [--manifest-out PATH] |
| 16 | +//! atlas-classify --db CORPUS.db schema-review |
| 17 | +//! --old-schema OLD.json --new-schema NEW.json |
| 18 | +//! [--reviewer-model M] [--reviewer-model-version V] |
| 19 | +//! [--manifest-out PATH] |
| 20 | +//! atlas-classify --db CORPUS.db schema-apply |
| 21 | +//! --review REVIEW.json --dispositions DISPOSITIONS.json |
| 22 | +//! [--now TS] [--manifest-out PATH] |
| 23 | +//! |
| 24 | +//! `run` is a dry-run unless `--commit` is given: it enumerates |
| 25 | +//! only unclassified/default-state/unresolved embeds, prints the |
| 26 | +//! run manifest (counts by prior state and outcome, the declared |
| 27 | +//! relatedness window, vector-preservation hashes, and every |
| 28 | +//! decision) as JSON, and writes nothing. With `--commit` it |
| 29 | +//! writes one classification record per candidate into the |
| 30 | +//! corpus's `classification_records` table; chunks and vectors |
| 31 | +//! are never modified. Runs are deterministic and resumable: |
| 32 | +//! re-running a committed run skips what is already decided. |
| 33 | +//! |
| 34 | +//! `schema-review` compares two schema documents section by |
| 35 | +//! section (changed sections only, unless the new document |
| 36 | +//! declares a breaking-change event) and prints the review |
| 37 | +//! batch: proposals plus model/config/schema provenance. It |
| 38 | +//! writes nothing. `schema-apply` applies a review batch's |
| 39 | +//! proposals, each only with a reviewed disposition naming a |
| 40 | +//! reviewer and rationale; lowerings without one are refused. |
| 41 | +
|
| 42 | +use std::collections::BTreeMap; |
| 43 | +use std::path::{Path, PathBuf}; |
| 44 | +use std::process::ExitCode; |
| 45 | + |
| 46 | +use atlas_core::classify::{ |
| 47 | + self, Disposition, ReviewerIdentity, RunConfig, SchemaDoc, iso_now, |
| 48 | +}; |
| 49 | +use serde_json::Value as Json; |
| 50 | + |
| 51 | +fn fail(msg: &str) -> ExitCode { |
| 52 | + eprintln!("atlas-classify: {msg}"); |
| 53 | + ExitCode::from(2) |
| 54 | +} |
| 55 | + |
| 56 | +fn usage() -> ExitCode { |
| 57 | + eprintln!( |
| 58 | + "usage:\n atlas-classify --db CORPUS run [--commit] [--window-days N] [--actor A] \ |
| 59 | + [--now TS] [--schema-version N] [--max-decisions N] [--manifest-out PATH]\n \ |
| 60 | + atlas-classify --db CORPUS schema-review --old-schema F --new-schema F \ |
| 61 | + [--reviewer-model M] [--reviewer-model-version V] [--manifest-out PATH]\n \ |
| 62 | + atlas-classify --db CORPUS schema-apply --review F --dispositions F \ |
| 63 | + [--now TS] [--manifest-out PATH]" |
| 64 | + ); |
| 65 | + ExitCode::from(2) |
| 66 | +} |
| 67 | + |
| 68 | +/// A strict flag set: every token must be a declared flag, with |
| 69 | +/// its value where the declaration requires one. |
| 70 | +struct Flags { |
| 71 | + values: BTreeMap<String, String>, |
| 72 | + switches: Vec<String>, |
| 73 | +} |
| 74 | + |
| 75 | +impl Flags { |
| 76 | + fn parse( |
| 77 | + args: &[String], |
| 78 | + value_flags: &[&str], |
| 79 | + switch_flags: &[&str], |
| 80 | + ) -> Result<Flags, String> { |
| 81 | + let mut values = BTreeMap::new(); |
| 82 | + let mut switches = Vec::new(); |
| 83 | + let mut i = 0; |
| 84 | + while i < args.len() { |
| 85 | + let arg = &args[i]; |
| 86 | + if value_flags.contains(&arg.as_str()) { |
| 87 | + let value = args |
| 88 | + .get(i + 1) |
| 89 | + .ok_or_else(|| format!("{arg} needs a value"))?; |
| 90 | + if values.insert(arg.clone(), value.clone()).is_some() { |
| 91 | + return Err(format!("{arg} given twice")); |
| 92 | + } |
| 93 | + i += 2; |
| 94 | + } else if switch_flags.contains(&arg.as_str()) { |
| 95 | + if switches.contains(arg) { |
| 96 | + return Err(format!("{arg} given twice")); |
| 97 | + } |
| 98 | + switches.push(arg.clone()); |
| 99 | + i += 1; |
| 100 | + } else { |
| 101 | + return Err(format!("unknown argument {arg:?}")); |
| 102 | + } |
| 103 | + } |
| 104 | + Ok(Flags { values, switches }) |
| 105 | + } |
| 106 | + |
| 107 | + fn get(&self, name: &str) -> Option<&str> { |
| 108 | + self.values.get(name).map(String::as_str) |
| 109 | + } |
| 110 | + |
| 111 | + fn require(&self, name: &str) -> Result<&str, String> { |
| 112 | + self.get(name) |
| 113 | + .ok_or_else(|| format!("missing {name}")) |
| 114 | + } |
| 115 | + |
| 116 | + fn has(&self, name: &str) -> bool { |
| 117 | + self.switches.iter().any(|s| s == name) |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +fn now_default() -> String { |
| 122 | + let secs = std::time::SystemTime::now() |
| 123 | + .duration_since(std::time::UNIX_EPOCH) |
| 124 | + .map(|d| d.as_secs()) |
| 125 | + .unwrap_or(0); |
| 126 | + iso_now(secs) |
| 127 | +} |
| 128 | + |
| 129 | +fn read_json(path: &str) -> Result<Json, String> { |
| 130 | + let text = |
| 131 | + std::fs::read_to_string(path).map_err(|e| format!("read {path}: {e}"))?; |
| 132 | + serde_json::from_str(&text).map_err(|e| format!("parse {path}: {e}")) |
| 133 | +} |
| 134 | + |
| 135 | +fn emit(doc: &Json, manifest_out: Option<&str>) -> Result<(), String> { |
| 136 | + let text = serde_json::to_string_pretty(doc) |
| 137 | + .map_err(|e| format!("serialize manifest: {e}"))?; |
| 138 | + if let Some(path) = manifest_out { |
| 139 | + std::fs::write(path, format!("{text}\n")) |
| 140 | + .map_err(|e| format!("write {path}: {e}"))?; |
| 141 | + } |
| 142 | + println!("{text}"); |
| 143 | + Ok(()) |
| 144 | +} |
| 145 | + |
| 146 | +fn parse_u64(raw: &str, flag: &str) -> Result<u64, String> { |
| 147 | + raw.parse::<u64>() |
| 148 | + .map_err(|_| format!("{flag} must be an unsigned integer, got {raw:?}")) |
| 149 | +} |
| 150 | + |
| 151 | +fn action_run(db: &Path, args: &[String]) -> Result<Json, String> { |
| 152 | + let flags = Flags::parse( |
| 153 | + args, |
| 154 | + &[ |
| 155 | + "--window-days", |
| 156 | + "--actor", |
| 157 | + "--now", |
| 158 | + "--schema-version", |
| 159 | + "--max-decisions", |
| 160 | + "--manifest-out", |
| 161 | + ], |
| 162 | + &["--commit"], |
| 163 | + )?; |
| 164 | + let mut config = RunConfig { |
| 165 | + now: flags |
| 166 | + .get("--now") |
| 167 | + .map(str::to_owned) |
| 168 | + .unwrap_or_else(now_default), |
| 169 | + ..RunConfig::default() |
| 170 | + }; |
| 171 | + if let Some(actor) = flags.get("--actor") { |
| 172 | + config.actor = actor.to_string(); |
| 173 | + } |
| 174 | + if let Some(days) = flags.get("--window-days") { |
| 175 | + config.window_days = days |
| 176 | + .parse::<i64>() |
| 177 | + .map_err(|_| format!("--window-days must be an integer, got {days:?}"))?; |
| 178 | + if config.window_days < 0 { |
| 179 | + return Err("--window-days must not be negative".to_string()); |
| 180 | + } |
| 181 | + } |
| 182 | + if let Some(v) = flags.get("--schema-version") { |
| 183 | + config.schema_version = parse_u64(v, "--schema-version")?; |
| 184 | + } |
| 185 | + if let Some(v) = flags.get("--max-decisions") { |
| 186 | + config.max_decisions = Some( |
| 187 | + parse_u64(v, "--max-decisions")? |
| 188 | + .try_into() |
| 189 | + .map_err(|_| "--max-decisions is too large".to_string())?, |
| 190 | + ); |
| 191 | + } |
| 192 | + let manifest = classify::run_classification(db, flags.has("--commit"), &config) |
| 193 | + .map_err(|e| e.to_string())?; |
| 194 | + serde_json::to_value(&manifest).map_err(|e| format!("serialize manifest: {e}")) |
| 195 | +} |
| 196 | + |
| 197 | +fn action_schema_review(db: &Path, args: &[String]) -> Result<Json, String> { |
| 198 | + let flags = Flags::parse( |
| 199 | + args, |
| 200 | + &[ |
| 201 | + "--old-schema", |
| 202 | + "--new-schema", |
| 203 | + "--reviewer-model", |
| 204 | + "--reviewer-model-version", |
| 205 | + "--manifest-out", |
| 206 | + ], |
| 207 | + &[], |
| 208 | + )?; |
| 209 | + let old = SchemaDoc::parse(&read_json(flags.require("--old-schema")?)?) |
| 210 | + .map_err(|e| e.to_string())?; |
| 211 | + let new = SchemaDoc::parse(&read_json(flags.require("--new-schema")?)?) |
| 212 | + .map_err(|e| e.to_string())?; |
| 213 | + // The review's config provenance binds the reviewer identity |
| 214 | + // and both schema documents. |
| 215 | + let config_canonical = format!( |
| 216 | + "atlas-classify-schema-review/1\nmodel={}\nmodel_version={}\nold={}\nnew={}\n", |
| 217 | + flags.get("--reviewer-model").unwrap_or("atlas-classify"), |
| 218 | + flags |
| 219 | + .get("--reviewer-model-version") |
| 220 | + .unwrap_or(env!("CARGO_PKG_VERSION")), |
| 221 | + old.content_hash(), |
| 222 | + new.content_hash(), |
| 223 | + ); |
| 224 | + let reviewer = ReviewerIdentity { |
| 225 | + model: flags |
| 226 | + .get("--reviewer-model") |
| 227 | + .unwrap_or("atlas-classify") |
| 228 | + .to_string(), |
| 229 | + model_version: flags |
| 230 | + .get("--reviewer-model-version") |
| 231 | + .unwrap_or(env!("CARGO_PKG_VERSION")) |
| 232 | + .to_string(), |
| 233 | + config_version: format!( |
| 234 | + "sha256:{}", |
| 235 | + classify::sha256_hex(config_canonical.as_bytes()) |
| 236 | + ), |
| 237 | + }; |
| 238 | + let review = classify::review_schema_change(db, &old, &new, reviewer) |
| 239 | + .map_err(|e| e.to_string())?; |
| 240 | + serde_json::to_value(&review).map_err(|e| format!("serialize review: {e}")) |
| 241 | +} |
| 242 | + |
| 243 | +fn action_schema_apply(db: &Path, args: &[String]) -> Result<Json, String> { |
| 244 | + let flags = Flags::parse( |
| 245 | + args, |
| 246 | + &["--review", "--dispositions", "--now", "--manifest-out"], |
| 247 | + &[], |
| 248 | + )?; |
| 249 | + let review: classify::SchemaReview = |
| 250 | + serde_json::from_value(read_json(flags.require("--review")?)?) |
| 251 | + .map_err(|e| format!("parse review: {e}"))?; |
| 252 | + let dispositions: BTreeMap<String, Disposition> = |
| 253 | + classify::parse_dispositions(&read_json(flags.require("--dispositions")?)?) |
| 254 | + .map_err(|e| e.to_string())?; |
| 255 | + let now = flags |
| 256 | + .get("--now") |
| 257 | + .map(str::to_owned) |
| 258 | + .unwrap_or_else(now_default); |
| 259 | + let report = classify::apply_schema_review(db, &review, &dispositions, &now) |
| 260 | + .map_err(|e| e.to_string())?; |
| 261 | + serde_json::to_value(&report).map_err(|e| format!("serialize report: {e}")) |
| 262 | +} |
| 263 | + |
| 264 | +fn main() -> ExitCode { |
| 265 | + let args: Vec<String> = std::env::args().skip(1).collect(); |
| 266 | + // Global flags: exactly one --db, then the action and its args. |
| 267 | + let mut db: Option<PathBuf> = None; |
| 268 | + let mut rest: Vec<String> = Vec::new(); |
| 269 | + let mut i = 0; |
| 270 | + while i < args.len() { |
| 271 | + if args[i] == "--db" { |
| 272 | + if db.is_some() { |
| 273 | + return fail("--db given twice"); |
| 274 | + } |
| 275 | + match args.get(i + 1) { |
| 276 | + Some(path) => { |
| 277 | + db = Some(PathBuf::from(path)); |
| 278 | + i += 2; |
| 279 | + } |
| 280 | + None => return fail("--db needs a value"), |
| 281 | + } |
| 282 | + } else { |
| 283 | + rest.push(args[i].clone()); |
| 284 | + i += 1; |
| 285 | + } |
| 286 | + } |
| 287 | + let Some(db) = db else { |
| 288 | + return usage(); |
| 289 | + }; |
| 290 | + let Some((action, action_args)) = rest.split_first() else { |
| 291 | + return usage(); |
| 292 | + }; |
| 293 | + let result = match action.as_str() { |
| 294 | + "run" => action_run(&db, action_args), |
| 295 | + "schema-review" => action_schema_review(&db, action_args), |
| 296 | + "schema-apply" => action_schema_apply(&db, action_args), |
| 297 | + other => return fail(&format!("unknown action {other:?}")), |
| 298 | + }; |
| 299 | + match result { |
| 300 | + Ok(doc) => { |
| 301 | + // Actions return the document; print it, and also |
| 302 | + // write it when the action carried --manifest-out. |
| 303 | + let manifest_out = action_args |
| 304 | + .iter() |
| 305 | + .position(|a| a == "--manifest-out") |
| 306 | + .and_then(|pos| action_args.get(pos + 1)) |
| 307 | + .map(String::as_str); |
| 308 | + match emit(&doc, manifest_out) { |
| 309 | + Ok(()) => ExitCode::SUCCESS, |
| 310 | + Err(msg) => fail(&msg), |
| 311 | + } |
| 312 | + } |
| 313 | + Err(msg) => fail(&msg), |
| 314 | + } |
| 315 | +} |