Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-runtime/src/destination.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-runtime / src / destination.rs` 956 lines ยท 35350 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! Which path does a compose goal ask to WRITE? (issue #288) 17 //! 18 //! A goal mentions paths in two roles: the DESTINATION (the file the task 19 //! creates or changes) and SOURCES (material it reads: "about README.md"). 20 //! Only the destination decides the task kind, the budget, the prompt and the 21 //! merge. This module is a small rule-based parser with two tables: 22 //! 23 //! * `DESTINATION_VERBS`: a verb that introduces the destination ("create", 24 //! "update", "append", "save", ...). The first path after it is the target. 25 //! * `SOURCE_MARKERS`: a word that marks the next path as source material 26 //! ("about", "from", "using", "based on", "summarising", ...). Paths joined 27 //! to a source by "and" or a comma are sources too. 28 //! 29 //! Rules, in order: 30 //! 0. A file operation word (rename, move, delete, remove) is 31 //! `Err(Unsupported)`, as before, unless it is subject matter: it follows 32 //! "how to" (or when/where/why to) and acts on nothing (no path later in 33 //! the same sentence, no "it"/"the rest"/..., not the end of the sentence), 34 //! as in "a how-to that shows how to rename a folder of photos". Even then 35 //! the goal passes only when it names exactly one file to write. 36 //! 1. A path-like word is one with a `/`, a file extension, or a name that 37 //! exists as a file (`Makefile`). Absolute, `~` and `..` paths are path-like 38 //! and unsafe. 39 //! 2. Paths marked as sources are set aside. A path introduced as an existing 40 //! file ("there is a file at X", "there are files at X and Y") is set aside 41 //! too, but only when a destination verb directly names another file to 42 //! write ("create a new file called Y"); otherwise it stays a candidate 43 //! (alone: the file to edit). 44 //! 3. No destination left: `Ok(None)` (a new document, the model names it). 45 //! 4. One destination: it. 46 //! 5. Several destinations: the first is taken only when a destination verb 47 //! comes before it and no later path is joined to it by "and"/"," or 48 //! introduced by a second destination verb. Otherwise `Err(Ambiguous)` 49 //! naming every candidate. Never a silent pick. 50 //! 51 //! The words of a goal are untrusted text; nothing here touches the disk 52 //! except through the `is_file` callback. 53 54 /// Verbs that introduce the destination of a task. 55 pub const DESTINATION_VERBS: &[&str] = &[ 56 "create", "write", "make", "generate", "produce", "draft", "compose", "update", "edit", 57 "modify", "append", "add", "insert", "rewrite", "change", "fix", "extend", "revise", "save", 58 "put", "store", "place", "prepend", "replace", 59 ]; 60 61 /// Words that mark the path after them as source material. 62 pub const SOURCE_MARKERS: &[&str] = &[ 63 "about", 64 "from", 65 "using", 66 "use", 67 "of", 68 "reading", 69 "read", 70 "summarising", 71 "summarizing", 72 "summarise", 73 "summarize", 74 "describing", 75 "covering", 76 "per", 77 "following", 78 "reference", 79 "referencing", 80 "given", 81 ]; 82 83 /// Words that may sit between a destination verb and the path it governs 84 /// ("Edit the given README.md"): a verb reaching the path through these wins 85 /// over a source marker. 86 pub const FILLERS: &[&str] = &[ 87 "the", 88 "a", 89 "an", 90 "this", 91 "that", 92 "my", 93 "our", 94 "your", 95 "file", 96 "document", 97 "doc", 98 "new", 99 "existing", 100 "given", 101 "reference", 102 "referenced", 103 "called", 104 "named", 105 "same", 106 "current", 107 ]; 108 109 /// Nouns that place a position INSIDE a file: in "the end of X" or "the Intro 110 /// section of X", the word "of" points at the file being changed, so it is not 111 /// a source marker. Other "of" phrases ("summary of X", "list of X", "copy of 112 /// X") still mark X as material to read. 113 pub const LOCATIONAL: &[&str] = &[ 114 "section", 115 "sections", 116 "part", 117 "end", 118 "top", 119 "bottom", 120 "start", 121 "beginning", 122 "body", 123 "contents", 124 "content", 125 "heading", 126 "line", 127 "lines", 128 "row", 129 "block", 130 "footer", 131 "header", 132 "middle", 133 "rest", 134 "bit", 135 ]; 136 137 /// File operations this parser never turns into a write. 138 pub const FILE_OPS: &[&str] = &["rename", "move", "delete", "remove"]; 139 140 /// Words a file operation acts on without naming a path ("delete it", 141 /// "remove the rest"). 142 pub const OP_OBJECTS: &[&str] = &[ 143 "it", 144 "its", 145 "them", 146 "their", 147 "everything", 148 "all", 149 "both", 150 "these", 151 "those", 152 "anything", 153 "each", 154 "others", 155 "rest", 156 "else", 157 "one", 158 ]; 159 160 /// Question words that, before "to", make a following file operation the 161 /// subject of the document ("how to rename a folder"), not a request. 162 pub const TOPIC_LEADS: &[&str] = &["how", "when", "where", "why"]; 163 164 /// Nouns of an existence statement ("there are files at ..."). 165 pub const EXISTING_NOUNS: &[&str] = &[ 166 "file", 167 "files", 168 "document", 169 "documents", 170 "doc", 171 "docs", 172 "note", 173 "notes", 174 ]; 175 176 /// Top-level domains that make a bare `name.tld` token a host name, not a file. 177 pub const HOST_TLDS: &[&str] = &[ 178 "org", "com", "net", "io", "dev", "edu", "gov", "ai", "co", "app", "me", "info", "xyz", 179 ]; 180 181 /// Words after which a `name.tld` token is a web address. 182 pub const HOST_LEAD: &[&str] = &["visit", "see", "at", "http", "https", "www", "url", "site"]; 183 184 /// A path-like word of the goal. 185 #[derive(Clone, Debug, PartialEq, Eq)] 186 struct Cand { 187 path: String, 188 idx: usize, 189 source: bool, 190 /// Joined to the previous path-like word by "and", "or" or a comma. 191 conj: bool, 192 /// A destination verb stands between the previous path-like word and this one. 193 verb_before: bool, 194 /// Introduced as a file that exists ("there is a file at X"), or joined 195 /// to one: material to read when the goal names another file to write. 196 existing: bool, 197 /// A destination verb governs this path directly ("create the file X"). 198 governed: bool, 199 } 200 201 /// The raw word ends a sentence ("loop." but not "e.g."). 202 fn ends_sentence(raw: &str) -> bool { 203 let t = raw.trim_end_matches(['"', '\'', '`', ')', ']']); 204 t.ends_with(['.', '!', '?', ';']) && !matches!(clean(raw), "e.g" | "i.e" | "etc" | "vs") 205 } 206 207 /// The file operation at `i` acts on something: a path later in the same 208 /// sentence, a word like "it" or "the rest", or nothing before the sentence 209 /// ends ("delete this."). 210 fn op_acts(raw: &[&str], words: &[String], i: usize, is_file: &dyn Fn(&str) -> bool) -> bool { 211 if ends_sentence(raw[i]) || i + 1 == raw.len() { 212 return true; 213 } 214 let mut object_seen = false; 215 for j in i + 1..raw.len() { 216 if path_like(clean(raw[j]), is_file) { 217 return true; 218 } 219 let lw = words[j].as_str(); 220 if !object_seen { 221 if OP_OBJECTS.contains(&lw) { 222 return true; 223 } 224 if !FILLERS.contains(&lw) { 225 object_seen = true; 226 } else if ends_sentence(raw[j]) || j + 1 == raw.len() { 227 return true; 228 } 229 } 230 if ends_sentence(raw[j]) { 231 break; 232 } 233 } 234 false 235 } 236 237 /// The first file operation the goal ASKS for. An operation word is subject 238 /// matter only after "how to" (or when/where/why to) and only when it acts 239 /// on nothing ("a how-to that shows how to rename a folder of photos"); 240 /// every other use is asked for ("so delete the stale doc", "Delete the 241 /// draft.", "how to delete it"). 242 fn asked_file_op(raw: &[&str], words: &[String], is_file: &dyn Fn(&str) -> bool) -> Option { 243 for (i, w) in words.iter().enumerate() { 244 if !FILE_OPS.contains(&w.as_str()) { 245 continue; 246 } 247 let topic = i >= 2 && words[i - 1] == "to" && TOPIC_LEADS.contains(&words[i - 2].as_str()); 248 if !topic || op_acts(raw, words, i, is_file) { 249 return Some(w.clone()); 250 } 251 } 252 None 253 } 254 255 /// The path at `i` is introduced as an existing file: "there is a file at X", 256 /// "there's a file called X", "there are files at X", "a file exists at X". 257 /// Never "there is a NEW file ...". 258 fn introduced_as_existing(words: &[String], i: usize) -> bool { 259 let mut j = i; 260 while j > 0 { 261 let p = words[j - 1].as_str(); 262 if p == "new" { 263 return false; 264 } 265 if FILLERS.contains(&p) || EXISTING_NOUNS.contains(&p) || matches!(p, "at" | "in") { 266 j -= 1; 267 } else { 268 break; 269 } 270 } 271 if j == i || j == 0 { 272 return false; 273 } 274 let lead = words[j - 1].as_str(); 275 let before = (j > 1).then(|| words[j - 2].as_str()); 276 matches!(lead, "there's" | "theres" | "exists" | "exist") 277 || (matches!(lead, "is" | "are") && before == Some("there")) 278 } 279 280 /// The destination could not be chosen. 281 #[derive(Clone, Debug, PartialEq, Eq)] 282 pub enum DestinationError { 283 /// Several candidate destinations and no rule picks one. 284 Ambiguous(Vec), 285 /// The goal only mentions paths as source material; nothing is named to write. 286 NoDestination(Vec), 287 /// The goal asks for an operation this parser does not support. 288 Unsupported(String), 289 } 290 291 impl std::fmt::Display for DestinationError { 292 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 293 match self { 294 Self::NoDestination(c) => write!( 295 f, 296 "no destination named: the goal only mentions {} as material to read; name the file to write", 297 c.join(", ") 298 ), 299 Self::Unsupported(w) => write!(f, "{w} is not supported: name the file to create or edit"), 300 Self::Ambiguous(c) => write!( 301 f, 302 "ambiguous destination: the goal names several files to write ({}); name one", 303 c.join(", ") 304 ), 305 } 306 } 307 } 308 309 /// A path with its leading `./` segments removed, and nothing else changed 310 /// (sc#402): `./report.md` and `report.md` name the same workspace file, so a 311 /// path that enters from text (a goal word, a reply's `filename:` line) is 312 /// read in its bare form. Inner `./` segments, `..`, absolute paths, `~`, 313 /// empty results and every other form are left exactly as written, so the 314 /// strict checks that follow (`check_relative_path` in compose/bridge.rs, 315 /// `effects::confine_shape`) refuse them as before. The one shared reading. 316 pub fn strip_leading_curdir(path: &str) -> &str { 317 let mut p = path; 318 while let Some(rest) = p.strip_prefix("./") { 319 p = rest; 320 } 321 p 322 } 323 324 fn clean(w: &str) -> &str { 325 const Q: fn(char) -> bool = |c| matches!(c, '"' | '\'' | '`' | '(' | ')' | '[' | ']'); 326 // sc#402: a leading `./` is dropped once quotes and punctuation are gone. 327 strip_leading_curdir( 328 w.trim_matches(Q) 329 .trim_end_matches(['.', ',', ';', ':', '!', '?']) 330 .trim_matches(Q), 331 ) 332 } 333 334 fn has_extension(w: &str) -> bool { 335 let last = w.rsplit('/').next().unwrap_or(w); 336 match last.rsplit_once('.') { 337 Some((stem, ext)) => { 338 !stem.is_empty() 339 && !ext.is_empty() 340 && ext.len() <= 10 341 && ext.starts_with(|c: char| c.is_ascii_alphabetic()) 342 && ext.chars().all(|c| c.is_ascii_alphanumeric()) 343 && !matches!(w, "e.g" | "i.e" | "etc") 344 && !(ext.len() == 1 && stem.contains('.')) 345 } 346 None => false, 347 } 348 } 349 350 /// True for a word that names a path, safe or not. 351 fn path_like(w: &str, is_file: &dyn Fn(&str) -> bool) -> bool { 352 if w.is_empty() || w.contains('@') || w.contains("://") { 353 return false; 354 } 355 let unsafe_form = 356 w.starts_with('/') || w.starts_with("~/") || w == "~" || w.split('/').any(|c| c == ".."); 357 if unsafe_form { 358 return w.contains('/') || w.starts_with('~'); 359 } 360 let ok_chars = w 361 .chars() 362 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '/')); 363 ok_chars && (w.contains('/') && has_extension(w) || has_extension(w) || is_file(w)) 364 } 365 366 /// What a goal names: the one file to write (resolved into its folder when the 367 /// goal says "in the Y folder") and the other paths it mentions, in goal order. 368 /// The other paths are references: material to read, never written. 369 #[derive(Clone, Debug, Default, PartialEq, Eq)] 370 pub struct Named { 371 pub dest: Option, 372 pub inputs: Vec, 373 } 374 375 #[derive(Default)] 376 struct Parsed { 377 /// Destination path as written in the goal, and its word index. 378 dest: Option<(String, usize)>, 379 others: Vec, 380 } 381 382 const FOLDER_NOUNS: &[&str] = &["folder", "directory", "dir"]; 383 const FOLDER_ARTICLES: &[&str] = &["the", "a", "an", "our", "my", "this"]; 384 /// Plural nouns and verbs that make a folder phrase a place to read from. 385 const READ_INTENT: &[&str] = &[ 386 "files", 387 "documents", 388 "docs", 389 "notes", 390 "texts", 391 "read", 392 "reading", 393 "from", 394 "about", 395 "using", 396 "summarise", 397 "summarize", 398 "of", 399 ]; 400 401 /// "in the Y folder" phrases of the goal: (folder name, index of "in"). 402 fn folder_phrases(raw: &[&str], words: &[String]) -> Vec<(String, usize)> { 403 let mut out = Vec::new(); 404 for (i, w) in words.iter().enumerate() { 405 if !matches!(w.as_str(), "in" | "inside" | "into") { 406 continue; 407 } 408 let mut j = i + 1; 409 while j < words.len() && FOLDER_ARTICLES.contains(&words[j].as_str()) { 410 j += 1; 411 } 412 if j + 1 >= words.len() || !FOLDER_NOUNS.contains(&words[j + 1].as_str()) { 413 continue; 414 } 415 let name = clean(raw[j]); 416 let plain = !name.is_empty() 417 && !name.starts_with('.') 418 && name 419 .chars() 420 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')); 421 if plain { 422 out.push((name.to_string(), i)); 423 } 424 } 425 out 426 } 427 428 /// The destination written as "X ... in the Y folder" is `Y/X`. Only a bare 429 /// name directly followed by the phrase is moved. 430 fn resolve_in_folder(raw: &[&str], words: &[String], dest: String, idx: usize) -> String { 431 if dest.contains('/') { 432 return dest; 433 } 434 match folder_phrases(raw, words) 435 .into_iter() 436 .find(|(_, at)| *at == idx + 1) 437 { 438 Some((folder, _)) => format!("{folder}/{dest}"), 439 None => dest, 440 } 441 } 442 443 /// Every folder the goal names with "the Y folder" (any role), in goal order. 444 pub fn goal_folders(goal: &str) -> Vec { 445 let raw: Vec<&str> = goal.split_whitespace().collect(); 446 let words: Vec = raw.iter().map(|w| clean(w).to_ascii_lowercase()).collect(); 447 let mut out: Vec = Vec::new(); 448 for (n, _) in folder_phrases(&raw, &words) { 449 if !out.contains(&n) { 450 out.push(n); 451 } 452 } 453 out 454 } 455 456 /// Folders the goal names as a place to READ from ("the three text files in the 457 /// inbox folder"): the phrase is not the folder of a file the goal names 458 /// (the word before "in" is not a path) and a reading word stands within the 459 /// five words before "in". 460 pub fn input_folders(goal: &str) -> Vec { 461 let raw: Vec<&str> = goal.split_whitespace().collect(); 462 let words: Vec = raw.iter().map(|w| clean(w).to_ascii_lowercase()).collect(); 463 let mut out: Vec = Vec::new(); 464 for (n, at) in folder_phrases(&raw, &words) { 465 let after_path = at > 0 && { 466 let p = clean(raw[at - 1]); 467 p.contains('/') || has_extension(p) 468 }; 469 let reads = words[at.saturating_sub(5)..at] 470 .iter() 471 .any(|w| READ_INTENT.contains(&w.as_str())); 472 if !after_path && reads && !out.contains(&n) { 473 out.push(n); 474 } 475 } 476 out 477 } 478 479 /// The destination the goal names. `is_file(w)` says whether the plain 480 /// relative word `w` is an existing file (for extension-less names). 481 pub fn named_destination( 482 goal: &str, 483 is_file: &dyn Fn(&str) -> bool, 484 ) -> Result, DestinationError> { 485 named_paths(goal, is_file, &|_| false).map(|n| n.dest) 486 } 487 488 /// The destination and the input paths a goal names. `is_input(w)` says whether 489 /// the word `w` is an existing workspace file that is material to read: such a 490 /// name is never taken as a write target when the goal also names a new file. 491 pub fn named_paths( 492 goal: &str, 493 is_file: &dyn Fn(&str) -> bool, 494 is_input: &dyn Fn(&str) -> bool, 495 ) -> Result { 496 let raw: Vec<&str> = goal.split_whitespace().collect(); 497 let words: Vec = raw.iter().map(|w| clean(w).to_ascii_lowercase()).collect(); 498 if let Some(op) = asked_file_op(&raw, &words, is_file) { 499 return Err(DestinationError::Unsupported(op)); 500 } 501 // A file-operation word that acts on nothing is subject matter only when 502 // the goal names exactly one file to write; otherwise it is refused as before. 503 let op_word = words.iter().find(|w| FILE_OPS.contains(&w.as_str())); 504 let finish = |p: Parsed| { 505 let dest = p.dest.map(|(d, i)| resolve_in_folder(&raw, &words, d, i)); 506 Named { 507 dest, 508 inputs: p.others, 509 } 510 }; 511 match (op_word, parse(&raw, &words, is_file, is_input)) { 512 (_, Ok(p)) if p.dest.is_some() => Ok(finish(p)), 513 (Some(op), _) => Err(DestinationError::Unsupported(op.clone())), 514 (None, other) => other.map(finish), 515 } 516 } 517 518 fn parse( 519 raw: &[&str], 520 words: &[String], 521 is_file: &dyn Fn(&str) -> bool, 522 is_input: &dyn Fn(&str) -> bool, 523 ) -> Result { 524 let mut cands: Vec = Vec::new(); 525 let mut verb_since_last = false; 526 let mut first_verb: Option = None; 527 for (i, w) in raw.iter().enumerate() { 528 let c = clean(w); 529 let lw = &words[i]; 530 if DESTINATION_VERBS.contains(&lw.as_str()) { 531 verb_since_last = true; 532 first_verb.get_or_insert(i); 533 } 534 if !path_like(c, is_file) { 535 continue; 536 } 537 let governed = { 538 let mut j = i; 539 while j > 0 && FILLERS.contains(&words[j - 1].as_str()) { 540 j -= 1; 541 } 542 j > 0 && DESTINATION_VERBS.contains(&words[j - 1].as_str()) 543 }; 544 let host_like = !c.contains('/') 545 && !is_file(c) 546 && (c 547 .rsplit('.') 548 .next() 549 .is_some_and(|t| HOST_TLDS.contains(&t.to_ascii_lowercase().as_str())) 550 || (i > 0 && HOST_LEAD.contains(&words[i - 1].as_str()))); 551 if host_like && !governed { 552 continue; 553 } 554 let prev = (i > 0).then(|| words[i - 1].as_str()); 555 let prev2 = (i > 1).then(|| words[i - 2].as_str()); 556 let location_of = prev == Some("of") && prev2.is_some_and(|p| LOCATIONAL.contains(&p)); 557 let marked = !governed 558 && (prev.is_some_and(|p| SOURCE_MARKERS.contains(&p) && !location_of) 559 || (prev == Some("on") && prev2 == Some("based")) 560 || (prev == Some("on") && prev2 == Some("relying"))); 561 // Joined to the previous path-like word: "A and B", "A, B", "A or B", "A B". 562 let joined = cands.last().is_some_and(|l| { 563 (prev == Some("and") || prev == Some("or") || prev == Some("&")) && l.idx + 2 == i 564 || l.idx + 1 == i 565 }); 566 let source = marked || (joined && cands.last().is_some_and(|l| l.source)); 567 let existing = !governed 568 && (introduced_as_existing(words, i) 569 || (joined && cands.last().is_some_and(|l| l.existing))); 570 cands.push(Cand { 571 path: c.to_string(), 572 idx: i, 573 source, 574 conj: joined, 575 verb_before: verb_since_last && !cands.is_empty(), 576 existing, 577 governed, 578 }); 579 verb_since_last = false; 580 } 581 let mut dests: Vec<&Cand> = cands.iter().filter(|c| !c.source).collect(); 582 // A file introduced as existing is read, not written, when a destination 583 // verb directly names another file to write ("create a new file called 584 // Y"); otherwise it stays a candidate (alone: the file to edit). 585 // Not when another destination verb stands between the two ("there is a 586 // file at X. Update it and create Y" asks to write both). 587 let demote = dests.iter().find(|c| !c.existing).is_some_and(|g| { 588 g.governed 589 && dests.iter().filter(|c| c.existing).all(|e| { 590 let (a, b) = (e.idx.min(g.idx), e.idx.max(g.idx)); 591 words[a + 1..b] 592 .iter() 593 .filter(|w| DESTINATION_VERBS.contains(&w.as_str())) 594 .count() 595 <= 1 596 }) 597 }); 598 if demote { 599 dests.retain(|c| !c.existing); 600 } 601 // A name that already exists in the workspace and is not governed by a 602 // destination verb is material to read, never a write target, when another 603 // candidate remains that does not exist (the new file the goal asks for). 604 let input_like = |c: &Cand| !c.governed && is_input(&c.path); 605 if dests.iter().any(|c| !input_like(c) && !is_input(&c.path)) { 606 dests.retain(|c| !input_like(c)); 607 } 608 let Some(first) = dests.first() else { 609 if cands.is_empty() { 610 return Ok(Parsed::default()); 611 } 612 let mut names: Vec = Vec::new(); 613 for c in &cands { 614 if !names.contains(&c.path) { 615 names.push(c.path.clone()); 616 } 617 } 618 return Err(DestinationError::NoDestination(names)); 619 }; 620 if dests.len() > 1 { 621 let verb_leads = first_verb.is_some_and(|v| v < first.idx); 622 let clash = dests[1..].iter().any(|d| d.conj || d.verb_before); 623 if !verb_leads || clash { 624 let mut names: Vec = Vec::new(); 625 for d in &dests { 626 if !names.contains(&d.path) { 627 names.push(d.path.clone()); 628 } 629 } 630 if names.len() > 1 { 631 return Err(DestinationError::Ambiguous(names)); 632 } 633 } 634 } 635 let mut others: Vec = Vec::new(); 636 for c in &cands { 637 if c.path != first.path && !others.contains(&c.path) { 638 others.push(c.path.clone()); 639 } 640 } 641 Ok(Parsed { 642 dest: Some((first.path.clone(), first.idx)), 643 others, 644 }) 645 } 646 647 #[cfg(test)] 648 mod tests { 649 use super::*; 650 651 fn d(g: &str) -> Result, DestinationError> { 652 named_destination(g, &|w| w == "Makefile") 653 } 654 655 #[test] 656 fn source_is_not_the_destination() { 657 assert_eq!( 658 d("Create docs/SUMMARY.md about README.md"), 659 Ok(Some("docs/SUMMARY.md".into())) 660 ); 661 assert_eq!( 662 d("Update README.md using docs/NOTES.md"), 663 Ok(Some("README.md".into())) 664 ); 665 assert_eq!( 666 d("Add a summary of README.md and LICENSE to docs/S.md"), 667 Ok(Some("docs/S.md".into())) 668 ); 669 } 670 671 #[test] 672 fn single_and_extensionless() { 673 assert_eq!(d("write faq.md"), Ok(Some("faq.md".into()))); 674 assert_eq!(d("Edit Makefile please"), Ok(Some("Makefile".into()))); 675 assert_eq!(d("Edit docs now"), Ok(None)); 676 assert_eq!(d("say hi, e.g. twice"), Ok(None)); 677 assert_eq!(d("under the ## 0.1.0 heading"), Ok(None)); 678 } 679 680 #[test] 681 fn several_destinations_are_ambiguous() { 682 assert!(matches!( 683 d("Create a.md and b.md"), 684 Err(DestinationError::Ambiguous(c)) if c == ["a.md", "b.md"] 685 )); 686 assert!(d("Create a.md. Then update b.md").is_err()); 687 assert!(d("put a.md b.md together").is_err()); 688 assert_eq!( 689 d("Edit `docs/plan.txt`, then README.md"), 690 Ok(Some("docs/plan.txt".into())) 691 ); 692 } 693 694 #[test] 695 fn source_only_goals_name_no_destination() { 696 for g in [ 697 "Summarise README.md", 698 "Summarise README.md and docs/A.md", 699 "Create a note summarising README.md", 700 ] { 701 assert!( 702 matches!(d(g), Err(DestinationError::NoDestination(_))), 703 "{g}" 704 ); 705 } 706 let Err(e) = d("Summarise README.md") else { 707 panic!() 708 }; 709 assert!(e.to_string().contains("README.md") && e.to_string().contains("no destination")); 710 } 711 712 #[test] 713 fn verb_governing_the_path_beats_a_marker_adjective() { 714 assert_eq!(d("Edit the given README.md"), Ok(Some("README.md".into()))); 715 assert_eq!( 716 d("Update the reference README.md"), 717 Ok(Some("README.md".into())) 718 ); 719 assert_eq!( 720 d("Create docs/S.md from the given README.md"), 721 Ok(Some("docs/S.md".into())) 722 ); 723 } 724 725 #[test] 726 fn host_names_are_not_files_unless_governed() { 727 assert_eq!( 728 d("Visit example.org and write out.md"), 729 Ok(Some("out.md".into())) 730 ); 731 assert_eq!( 732 d("See docs.example.com then create out.md"), 733 Ok(Some("out.md".into())) 734 ); 735 assert_eq!(d("Create example.org"), Ok(Some("example.org".into()))); 736 } 737 738 #[test] 739 fn of_phrases_resolve_by_what_they_point_at() { 740 let one = |g: &str| d(g).unwrap().unwrap(); 741 // A position inside the file being changed: the file is the destination. 742 for (g, want) in [ 743 ("Add a line to the Intro section of README.md", "README.md"), 744 ("Append a note to the end of README.md", "README.md"), 745 ("Insert a badge at the top of README.md", "README.md"), 746 ( 747 "Add \"x\" to the \"## Before a trip\" section of notes/GARAGE.md.", 748 "notes/GARAGE.md", 749 ), 750 ] { 751 assert_eq!(one(g), want, "{g}"); 752 } 753 // Material to read: the file is a source, the destination is named elsewhere. 754 for (g, want) in [ 755 ("Write a list of README.md into docs/L.md", "docs/L.md"), 756 ("Create docs/C.md as a copy of README.md", "docs/C.md"), 757 ( 758 "Write a summary of README.md into docs/SUMMARY.md", 759 "docs/SUMMARY.md", 760 ), 761 // Location word in the source role: the later file is not demoted, 762 // the first file after the verb still wins (documented limit). 763 ("Create docs/S.md from the top of README.md", "docs/S.md"), 764 ( 765 "Create docs/S.md summarising the section of README.md", 766 "docs/S.md", 767 ), 768 ("Create docs/S.md about the end of README.md", "docs/S.md"), 769 ] { 770 assert_eq!(one(g), want, "{g}"); 771 } 772 for g in [ 773 "Make a list of README.md", 774 "Summarise README.md", 775 "Make a copy of README.md", 776 ] { 777 assert!( 778 matches!(d(g), Err(DestinationError::NoDestination(_))), 779 "{g}" 780 ); 781 } 782 } 783 784 #[test] 785 fn rename_is_unsupported() { 786 assert!( 787 matches!(d("Rename a.md to b.md"), Err(DestinationError::Unsupported(w)) if w == "rename") 788 ); 789 } 790 791 /// A file operation the goal ASKS for is refused; the same word as subject 792 /// matter of a named document is not (v5 G6, goal D2). 793 #[test] 794 fn a_file_operation_is_refused_only_when_asked_for() { 795 let unsupported = |g: &str, want: &str| { 796 assert!( 797 matches!(d(g), Err(DestinationError::Unsupported(ref w)) if w == want), 798 "{g}: {:?}", 799 d(g) 800 ); 801 }; 802 // Asked for: the verb acts on a path named in the same sentence. 803 unsupported("rename notes/a.txt to notes/b.txt", "rename"); 804 unsupported("delete docs/x.md", "delete"); 805 unsupported("Please delete the file docs/x.md.", "delete"); 806 unsupported("move a.txt into b/", "move"); 807 unsupported("Rename my old photos.zip", "rename"); 808 unsupported("Create docs/a.md and delete docs/b.md", "delete"); 809 unsupported("Remove the line \"x\" from README.md", "remove"); 810 unsupported("Remove e.g. old.txt", "remove"); 811 // Asked for, by pronoun or with nothing named after the verb. 812 unsupported("Write docs/a.md. Then delete it.", "delete"); 813 unsupported("Create docs/a.md and remove everything else", "remove"); 814 unsupported("Write docs/a.md, then move them.", "move"); 815 // Asked for, and no single file to write: refused as before. 816 unsupported("Delete all my notes", "delete"); 817 unsupported("Move the photos into the archive folder", "move"); 818 unsupported("Write a guide on how to delete files", "delete"); 819 // Asked for although the object is a plain noun, or the path comes 820 // first: never turned into a write of that path (review of #357). 821 unsupported("docs/old.md is obsolete, so delete the stale doc", "delete"); 822 unsupported( 823 "docs/a.md needs a better name, rename the file to something shorter", 824 "rename", 825 ); 826 unsupported("Write docs/a.md. Delete the draft.", "delete"); 827 unsupported("Create docs/a.md and delete the old files", "delete"); 828 unsupported("Create docs/a.md and delete its contents", "delete"); 829 unsupported("Create docs/a.md and remove the rest", "remove"); 830 unsupported("Write docs/a.md showing how to delete it", "delete"); 831 unsupported( 832 "Write docs/guide.md explaining how to delete docs/x.md", 833 "delete", 834 ); 835 // Several operation words: one asked for is enough. 836 unsupported( 837 "Write docs/a.md explaining how to rename photos. Then rename the folder.", 838 "rename", 839 ); 840 // Subject matter of a named document. 841 assert_eq!( 842 d( 843 "I need a technical how-to saved as docs/rename-photos.md that shows how to \ 844 rename a folder of holiday photos with a bash loop. Write at least 18 lines." 845 ), 846 Ok(Some("docs/rename-photos.md".into())) 847 ); 848 assert_eq!( 849 d("Write docs/backup.md explaining how to delete old backups safely."), 850 Ok(Some("docs/backup.md".into())) 851 ); 852 } 853 854 /// "There is a file at X" points at material to read when the goal names 855 /// another file to write (v5 G6, goal D4). On its own, X stays the file. 856 #[test] 857 fn an_existing_file_mentioned_first_is_read_not_written() { 858 assert_eq!( 859 d( 860 "There is a file at notes/choir-rehearsal.txt with my rough notes from choir \ 861 practice. Please create a new file called docs/choir-summary.md that summarises \ 862 it, and leave the original alone." 863 ), 864 Ok(Some("docs/choir-summary.md".into())) 865 ); 866 assert_eq!( 867 d("There's a file called notes/a.txt. Write docs/b.md from it."), 868 Ok(Some("docs/b.md".into())) 869 ); 870 assert_eq!( 871 d("There are files at notes/a.txt and notes/b.txt. Create docs/c.md summarising them."), 872 Ok(Some("docs/c.md".into())) 873 ); 874 // The only file named: it is the destination, as before. 875 assert_eq!( 876 d("There is a file at notes/a.txt. Fix the typo in it."), 877 Ok(Some("notes/a.txt".into())) 878 ); 879 // Two files to write stay ambiguous. 880 assert!(matches!( 881 d("There is a file at notes/a.txt. Create docs/b.md and docs/c.md."), 882 Err(DestinationError::Ambiguous(c)) if c == ["docs/b.md", "docs/c.md"] 883 )); 884 assert!(matches!( 885 d("Create docs/b.md and docs/c.md"), 886 Err(DestinationError::Ambiguous(_)) 887 )); 888 // The other file is not directly named as the one to write: no 889 // demotion, still ambiguous (review of #357). 890 assert!(matches!( 891 d("There is a file at docs/x.md. Add a link to docs/y.md"), 892 Err(DestinationError::Ambiguous(c)) if c == ["docs/x.md", "docs/y.md"] 893 )); 894 // A NEW file is never an existing one; "here is" is not an existence lead. 895 for g in [ 896 "There is a new file docs/out.md. Create docs/z.md", 897 "Here is a file docs/out.md. Create docs/z.md", 898 ] { 899 assert!( 900 matches!(d(g), Err(DestinationError::Ambiguous(ref c)) if c == &["docs/out.md", "docs/z.md"]), 901 "{g}: {:?}", 902 d(g) 903 ); 904 } 905 // Another destination verb between them: both are asked to be 906 // written, still ambiguous (review of #357, round 2). 907 assert!(matches!( 908 d("There is a file at docs/x.md. Update it and create docs/y.md"), 909 Err(DestinationError::Ambiguous(c)) if c == ["docs/x.md", "docs/y.md"] 910 )); 911 // "Create a file at X" names the destination, not an existing file. 912 assert_eq!( 913 d("Create a file at docs/x.md with one line"), 914 Ok(Some("docs/x.md".into())) 915 ); 916 } 917 918 #[test] 919 fn unsafe_paths_are_named_not_skipped() { 920 assert_eq!( 921 d("Create the file ../outside.txt"), 922 Ok(Some("../outside.txt".into())) 923 ); 924 assert_eq!(d("Edit /etc/passwd"), Ok(Some("/etc/passwd".into()))); 925 assert_eq!(d("Edit ~/secret.txt"), Ok(Some("~/secret.txt".into()))); 926 } 927 } 928 929 /// sc#402: a goal that writes `./report.md` names `report.md`; unsafe forms 930 /// keep their old reading (and are refused downstream as before). 931 #[cfg(test)] 932 mod dotslash_tests { 933 use super::*; 934 935 #[test] 936 fn strip_leading_curdir_removes_only_leading_dot_slash() { 937 assert_eq!(strip_leading_curdir("./report.md"), "report.md"); 938 assert_eq!(strip_leading_curdir("././a/b.md"), "a/b.md"); 939 assert_eq!(strip_leading_curdir("a/./b"), "a/./b"); 940 assert_eq!(strip_leading_curdir("./../x"), "../x"); 941 assert_eq!(strip_leading_curdir(".//x"), "/x"); 942 assert_eq!(strip_leading_curdir("./"), ""); 943 assert_eq!(strip_leading_curdir("."), "."); 944 assert_eq!(strip_leading_curdir(""), ""); 945 assert_eq!(strip_leading_curdir("../x"), "../x"); 946 assert_eq!(strip_leading_curdir(".hidden"), ".hidden"); 947 } 948 949 #[test] 950 fn a_goal_naming_dot_slash_names_the_bare_path() { 951 let d = |g: &str| named_destination(g, &|_| false); 952 assert_eq!(d("Edit ./report.md"), Ok(Some("report.md".into()))); 953 assert_eq!(d("Write ././docs/a.md"), Ok(Some("docs/a.md".into()))); 954 assert_eq!(d("Edit ./../x.md"), Ok(Some("../x.md".into()))); 955 } 956 }