1use std::collections::{BTreeMap, BTreeSet};
20use std::path::{Path, PathBuf};
21use std::process::{Command, Stdio};
22
23use anyhow::{bail, Context, Result};
24use serde_json::Value;
25
26#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
28pub struct Scope {
29 pub name: String,
31 pub recipients: Vec<String>,
33 #[serde(default)]
37 pub projects: BTreeMap<String, String>,
38}
39
40impl Scope {
41 #[must_use]
43 pub fn for_project(&self, project: &str) -> String {
44 self.projects
45 .get(project)
46 .cloned()
47 .unwrap_or_else(|| self.name.clone())
48 }
49}
50
51#[derive(Debug, Clone, Default, serde::Deserialize)]
53struct Local {
54 #[serde(default)]
55 default_scope: Option<String>,
56 #[serde(default)]
60 repos: Vec<String>,
61}
62
63fn local() -> Local {
64 std::fs::read_to_string(config_dir().join("sync.toml"))
65 .ok()
66 .and_then(|t| toml::from_str::<Local>(&t).ok())
67 .unwrap_or_default()
68}
69
70fn expand(path: &str) -> PathBuf {
71 match path.strip_prefix("~/") {
72 Some(rest) => std::env::var_os("HOME")
73 .map_or_else(|| PathBuf::from(path), |h| PathBuf::from(h).join(rest)),
74 None => PathBuf::from(path),
75 }
76}
77
78#[must_use]
80pub fn sender_entity(host: &str) -> String {
81 format!("sync:{host}")
82}
83
84#[must_use]
86pub fn host() -> String {
87 std::fs::read_to_string("/proc/sys/kernel/hostname")
88 .map(|h| h.trim().to_string())
89 .ok()
90 .filter(|h| !h.is_empty())
91 .unwrap_or_else(|| "host".into())
92}
93
94fn config_dir() -> PathBuf {
95 std::env::var_os("XDG_CONFIG_HOME")
96 .map(PathBuf::from)
97 .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
98 .unwrap_or_else(|| PathBuf::from(".config"))
99 .join("ljos")
100}
101
102fn state_dir() -> PathBuf {
103 std::env::var_os("XDG_STATE_HOME")
104 .map(PathBuf::from)
105 .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/state")))
106 .unwrap_or_else(|| PathBuf::from(".local/state"))
107 .join("ljos")
108 .join("sync")
109}
110
111#[must_use]
113pub fn identity_path() -> PathBuf {
114 config_dir().join("age.key")
115}
116
117pub fn public_key() -> Result<String> {
124 let key = identity_path();
125 if !key.exists() {
126 if let Some(dir) = key.parent() {
127 std::fs::create_dir_all(dir)?;
128 }
129 let made = Command::new("age-keygen")
130 .arg("-o")
131 .arg(&key)
132 .stdin(Stdio::null())
133 .output()
134 .context("age-keygen not on PATH; install age")?;
135 if !made.status.success() {
136 bail!(
137 "age-keygen: {}",
138 String::from_utf8_lossy(&made.stderr).trim()
139 );
140 }
141 }
142 let out = Command::new("age-keygen")
143 .arg("-y")
144 .arg(&key)
145 .output()
146 .context("age-keygen not on PATH; install age")?;
147 if !out.status.success() {
148 bail!(
149 "age-keygen -y: {}",
150 String::from_utf8_lossy(&out.stderr).trim()
151 );
152 }
153 Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
154}
155
156pub fn scope_of_repo(root: &Path) -> Result<Option<Scope>> {
162 let path = root.join(".ljos").join("sync.toml");
163 match std::fs::read_to_string(&path) {
164 Ok(text) => Ok(Some(
165 toml::from_str(&text).with_context(|| path.display().to_string())?,
166 )),
167 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
168 Err(e) => Err(e).with_context(|| path.display().to_string()),
169 }
170}
171
172fn default_scope(repo_scope: &str) -> String {
173 local()
174 .default_scope
175 .unwrap_or_else(|| repo_scope.to_string())
176}
177
178#[must_use]
180pub fn atom_scope(atom: &Value, default: &str) -> String {
181 atom["entities"]
182 .as_array()
183 .into_iter()
184 .flatten()
185 .filter_map(Value::as_str)
186 .find_map(|e| e.strip_prefix("scope:"))
187 .map_or_else(|| default.to_string(), str::to_string)
188}
189
190#[must_use]
193pub fn travelling(atom: &Value) -> Value {
194 let mut a = atom.clone();
195 if let Some(map) = a.as_object_mut() {
196 map.remove("embedding");
197 }
198 a
199}
200
201#[must_use]
203pub fn is_own(atom: &Value) -> bool {
204 !atom["entities"]
205 .as_array()
206 .into_iter()
207 .flatten()
208 .filter_map(Value::as_str)
209 .any(|e| e.starts_with("sync:"))
210}
211
212#[must_use]
215pub fn log_plaintext(atoms: &[Value], scope: &str, default: &str) -> String {
216 let mut mine: Vec<Value> = atoms
217 .iter()
218 .filter(|a| is_own(a) && atom_scope(a, default) == scope)
219 .map(travelling)
220 .collect();
221 mine.sort_by(|a, b| a["id"].as_str().cmp(&b["id"].as_str()));
222 mine.iter().map(|a| format!("{a}\n")).collect()
223}
224
225fn log_dir(root: &Path) -> PathBuf {
226 root.join(".ljos").join("atoms")
227}
228
229fn seal(plain: &str, recipients: &[String], out: &Path) -> Result<()> {
231 if recipients.is_empty() {
232 bail!("sync: the scope names no recipients; add this machine's `ljos sync --key` to .ljos/sync.toml");
233 }
234 let mut cmd = Command::new("age");
235 for r in recipients {
236 cmd.arg("-r").arg(r);
237 }
238 let tmp = out.with_extension("age.tmp");
239 let mut child = cmd
240 .arg("-o")
241 .arg(&tmp)
242 .stdin(Stdio::piped())
243 .stderr(Stdio::piped())
244 .spawn()
245 .context("age not on PATH; install age")?;
246 use std::io::Write;
247 child
248 .stdin
249 .take()
250 .context("age: no stdin")?
251 .write_all(plain.as_bytes())?;
252 let done = child.wait_with_output()?;
253 if !done.status.success() {
254 let _ = std::fs::remove_file(&tmp);
255 bail!("age: {}", String::from_utf8_lossy(&done.stderr).trim());
256 }
257 std::fs::rename(&tmp, out)?;
258 Ok(())
259}
260
261fn open(path: &Path, identity: &Path) -> Result<Option<String>> {
264 let out = Command::new("age")
265 .arg("-d")
266 .arg("-i")
267 .arg(identity)
268 .arg(path)
269 .stdin(Stdio::null())
270 .output()
271 .context("age not on PATH; install age")?;
272 if out.status.success() {
273 Ok(Some(String::from_utf8_lossy(&out.stdout).into_owned()))
274 } else if String::from_utf8_lossy(&out.stderr).contains("no identity matched") {
275 Ok(None)
276 } else {
277 bail!(
278 "age -d {}: {}",
279 path.display(),
280 String::from_utf8_lossy(&out.stderr).trim()
281 )
282 }
283}
284
285fn age_missing_line() -> String {
288 "sync: age is not installed, so the log was not sealed; install age to sync it\n".into()
289}
290
291#[cfg(test)]
292thread_local! {
293 static AGE_ON_PATH: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
297}
298
299fn age_on_path() -> bool {
301 #[cfg(test)]
302 if let Some(present) = AGE_ON_PATH.with(|cell| cell.get()) {
303 return present;
304 }
305 crate::on_path("age")
306}
307
308#[cfg(test)]
310#[must_use]
311fn hide_age() -> impl Drop {
312 struct Guard;
313 impl Drop for Guard {
314 fn drop(&mut self) {
315 AGE_ON_PATH.with(|cell| cell.set(None));
316 }
317 }
318 AGE_ON_PATH.with(|cell| cell.set(Some(false)));
319 Guard
320}
321
322fn age_missing(err: &anyhow::Error) -> bool {
323 err.chain().any(|cause| {
324 cause
325 .downcast_ref::<std::io::Error>()
326 .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
327 })
328}
329
330pub fn export(root: &Path, scope: &Scope, atoms: &[Value]) -> Result<String> {
339 let host = host();
340 let plain = log_plaintext(atoms, &scope.name, &default_scope(&scope.name));
341 let count = plain.lines().count();
342 let dir = log_dir(root);
343 std::fs::create_dir_all(&dir)?;
344 let stamp = dir.join(format!("{host}.digest"));
345 let digest = format!(
346 "{} {}\n",
347 crate::work_id(&plain),
348 crate::work_id(&scope.recipients.join(","))
349 );
350 if std::fs::read_to_string(&stamp).is_ok_and(|d| d == digest) {
351 return Ok(format!(
352 "sync: {count} {} atoms unchanged since the last export\n",
353 scope.name
354 ));
355 }
356 if !age_on_path() {
357 return Ok(age_missing_line());
358 }
359 if let Err(err) = seal(
360 &plain,
361 &scope.recipients,
362 &dir.join(format!("{host}.jsonl.age")),
363 ) {
364 if age_missing(&err) {
365 return Ok(age_missing_line());
366 }
367 return Err(err);
368 }
369 std::fs::write(&stamp, digest)?;
370 Ok(format!(
371 "sync: exported {count} {} atoms to .ljos/atoms/{host}.jsonl.age, sealed to {} recipient{}\n",
372 scope.name,
373 scope.recipients.len(),
374 if scope.recipients.len() == 1 { "" } else { "s" }
375 ))
376}
377
378#[derive(Debug, Default, PartialEq)]
381pub struct Incoming {
382 pub post: Vec<Value>,
383 pub retired: Vec<String>,
384}
385
386#[must_use]
390pub fn incoming(
391 plain: &str,
392 host: &str,
393 before: &BTreeSet<String>,
394 held: &BTreeSet<String>,
395) -> Incoming {
396 let mut post = Vec::new();
397 let mut now = BTreeSet::new();
398 for line in plain.lines().filter(|l| !l.trim().is_empty()) {
399 let Ok(mut atom) = serde_json::from_str::<Value>(line) else {
400 continue;
401 };
402 let text = atom["text"].as_str().unwrap_or("").to_string();
403 if text.is_empty() {
404 continue;
405 }
406 let id = crate::work_id(&text);
407 now.insert(id.clone());
408 if held.contains(&id) {
409 continue;
410 }
411 if let Some(map) = atom.as_object_mut() {
412 let mut entities: Vec<Value> = map
413 .get("entities")
414 .and_then(Value::as_array)
415 .cloned()
416 .unwrap_or_default();
417 let tag = sender_entity(host);
418 if !entities.iter().any(|e| e.as_str() == Some(tag.as_str())) {
419 entities.push(Value::String(tag));
420 }
421 map.insert("entities".into(), Value::Array(entities));
422 map.insert(
423 "origin".into(),
424 Value::String(crate::admit::ORIGIN_PEER.to_string()),
425 );
426 map.remove("id");
427 }
428 post.push(atom);
429 }
430 let retired = before.difference(&now).cloned().collect();
431 Incoming { post, retired }
432}
433
434fn taken_path(scope: &str, host: &str) -> PathBuf {
435 state_dir().join(scope).join(format!("{host}.taken"))
436}
437
438fn read_taken(scope: &str, host: &str) -> BTreeSet<String> {
439 std::fs::read_to_string(taken_path(scope, host))
440 .map(|t| t.lines().map(str::to_string).collect())
441 .unwrap_or_default()
442}
443
444fn write_taken(scope: &str, host: &str, plain: &str) -> Result<()> {
445 let path = taken_path(scope, host);
446 if let Some(dir) = path.parent() {
447 std::fs::create_dir_all(dir)?;
448 }
449 let ids: BTreeSet<String> = plain
450 .lines()
451 .filter_map(|l| serde_json::from_str::<Value>(l).ok())
452 .filter_map(|a| a["text"].as_str().map(crate::work_id))
453 .collect();
454 std::fs::write(path, ids.into_iter().map(|i| i + "\n").collect::<String>())?;
455 Ok(())
456}
457
458pub fn import(root: &Path, scope: &Scope) -> Result<String> {
465 let me = host();
466 let identity = identity_path();
467 if !identity.exists() {
468 return Ok("sync: no age identity on this machine; `ljos sync --key` makes one\n".into());
469 }
470 let dir = log_dir(root);
471 let Ok(entries) = std::fs::read_dir(&dir) else {
472 return Ok(format!("sync: no {} logs yet\n", scope.name));
473 };
474 let client = crate::pack()?;
475 let mut out = String::new();
476 let mut paths: Vec<PathBuf> = entries
477 .flatten()
478 .map(|e| e.path())
479 .filter(|p| p.to_string_lossy().ends_with(".jsonl.age"))
480 .collect();
481 paths.sort();
482 for path in paths {
483 let host = path
484 .file_name()
485 .and_then(|n| n.to_str())
486 .and_then(|n| n.strip_suffix(".jsonl.age"))
487 .unwrap_or("")
488 .to_string();
489 if host.is_empty() || host == me {
490 continue;
491 }
492 let Some(plain) = open(&path, &identity)? else {
493 out.push_str(&format!(
494 "sync: {host}'s {} log is not sealed to this machine\n",
495 scope.name
496 ));
497 continue;
498 };
499 let workspace = client.workspace();
500 let tag = sender_entity(&host);
503 let held: BTreeSet<String> = crate::atoms_lean(&client, &workspace)?
504 .iter()
505 .filter(|a| {
506 a["entities"]
507 .as_array()
508 .into_iter()
509 .flatten()
510 .any(|e| e.as_str() == Some(tag.as_str()))
511 })
512 .filter_map(|a| a["text"].as_str().map(crate::work_id))
513 .collect();
514 let got = incoming(&plain, &host, &read_taken(&scope.name, &host), &held);
515 let (mut kept, mut refused) = (0usize, 0usize);
516 for mut atom in got.post {
517 if let Some(map) = atom.as_object_mut() {
518 map.insert("workspace".into(), Value::String(workspace.clone()));
519 }
520 match crate::admit::post_kept(&client, &atom) {
521 Ok(_) => kept += 1,
522 Err(_) => refused += 1,
523 }
524 }
525 let mut retired = 0usize;
526 if !got.retired.is_empty() {
527 for atom in crate::atoms_lean(&client, &workspace)? {
528 let text = atom["text"].as_str().unwrap_or("");
529 let from_host = atom["entities"]
530 .as_array()
531 .into_iter()
532 .flatten()
533 .any(|e| e.as_str() == Some(tag.as_str()));
534 if from_host && got.retired.contains(&crate::work_id(text)) {
535 if let Some(id) = atom["id"].as_str() {
536 if crate::packset_forget(id, None).is_ok() {
537 retired += 1;
538 }
539 }
540 }
541 }
542 }
543 write_taken(&scope.name, &host, &plain)?;
544 out.push_str(&format!(
545 "sync: {host}: {kept} {} atoms taken, {refused} refused, {retired} retired\n",
546 scope.name
547 ));
548 }
549 Ok(out)
550}
551
552#[must_use]
554pub fn scope_for_issue(issue: &str) -> Option<String> {
555 let hit = vissue_core::Layout::resolve(None, None)
556 .and_then(vissue_core::Router::load)
557 .and_then(|router| router.find_by_id(issue))
558 .ok()?;
559 let root = hit
560 .path
561 .ancestors()
562 .find(|d| d.join(".git").exists())?
563 .to_path_buf();
564 scope_of_repo(&root)
565 .ok()
566 .flatten()
567 .map(|s| s.for_project(&hit.project))
568}
569
570fn tracker_root() -> Result<PathBuf> {
572 let layout = vissue_core::Layout::resolve(None, None).map_err(anyhow::Error::from)?;
573 Ok(layout.root().to_path_buf())
574}
575
576fn git(root: &Path, args: &[&str]) -> std::io::Result<std::process::Output> {
577 Command::new("git")
578 .arg("-C")
579 .arg(root)
580 .args(args)
581 .stdin(Stdio::null())
582 .output()
583}
584
585fn commit_if_sealed(root: &Path, scope: &str, exported: &str) -> String {
588 let age = log_dir(root).join(format!("{}.jsonl.age", host()));
589 if exported.contains("age is not installed") && !age.is_file() {
590 return String::new();
591 }
592 commit_log(root, scope)
593}
594
595fn push_pending(root: &Path) -> String {
599 let remotes = git(root, &["remote"])
600 .ok()
601 .filter(|o| o.status.success())
602 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
603 .unwrap_or_default();
604 if remotes.is_empty() || !commits_to_push(root) {
605 return String::new();
606 }
607 match crate::tracker_push::push_checkout(root) {
608 Ok(()) => "sync: pushed pending commits\n".into(),
609 Err(e) => format!("sync: push refused: {e}\n"),
610 }
611}
612
613fn commits_to_push(root: &Path) -> bool {
616 let ahead = |spec: &str| -> Option<u64> {
617 let out = git(root, &["rev-list", "--count", spec]).ok()?;
618 if !out.status.success() {
619 return None;
620 }
621 String::from_utf8_lossy(&out.stdout).trim().parse().ok()
622 };
623 if ahead("@{upstream}..HEAD").is_some_and(|n| n > 0) {
624 return true;
625 }
626 if git(root, &["rev-parse", "--abbrev-ref", "@{upstream}"]).is_ok_and(|o| o.status.success()) {
627 return false;
628 }
629 let branch = git(root, &["rev-parse", "--abbrev-ref", "HEAD"])
630 .ok()
631 .filter(|o| o.status.success())
632 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
633 .unwrap_or_default();
634 if branch.is_empty() || branch == "HEAD" {
635 return git(root, &["rev-parse", "--verify", "HEAD"]).is_ok_and(|o| o.status.success());
636 }
637 let remote_ref = format!("origin/{branch}");
638 match ahead(&format!("{remote_ref}..HEAD")) {
639 Some(n) => n > 0,
640 None => git(root, &["rev-parse", "--verify", "HEAD"]).is_ok_and(|o| o.status.success()),
641 }
642}
643
644fn commit_log(root: &Path, scope: &str) -> String {
647 let host = host();
648 let files = [
649 format!(".ljos/atoms/{host}.jsonl.age"),
650 format!(".ljos/atoms/{host}.digest"),
651 ];
652 let common = git(root, &["rev-parse", "--git-common-dir"])
654 .ok()
655 .filter(|o| o.status.success())
656 .map(|o| root.join(String::from_utf8_lossy(&o.stdout).trim()))
657 .unwrap_or_else(|| root.join(".git"));
658 let held = crate::CommitLock::acquire(&common.join("ljos-commit.lock"));
659 let mut add = vec!["add", "--"];
660 add.extend(files.iter().map(String::as_str));
661 if git(root, &add).map_or(true, |o| !o.status.success()) {
662 return "sync: could not stage the log\n".into();
663 }
664 let staged = git(
665 root,
666 &["diff", "--cached", "--quiet", "--", &files[0], &files[1]],
667 );
668 if staged.is_ok_and(|o| o.status.success()) {
669 drop(held);
672 return push_pending(root);
673 }
674 let message = format!("chore(sync): {host} {scope} atoms");
675 let mut commit = vec!["commit", "-q", "--only", "-m", message.as_str(), "--"];
676 commit.extend(files.iter().map(String::as_str));
677 match git(root, &commit) {
678 Ok(o) if o.status.success() => {}
679 Ok(o) => {
680 return format!(
681 "sync: commit refused: {}\n",
682 String::from_utf8_lossy(&o.stderr)
683 .lines()
684 .next()
685 .unwrap_or("")
686 )
687 }
688 Err(e) => return format!("sync: git: {e}\n"),
689 }
690 drop(held);
691 let remotes = git(root, &["remote"])
692 .ok()
693 .filter(|o| o.status.success())
694 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
695 .unwrap_or_default();
696 if remotes.is_empty() {
697 return format!(
698 "sync: committed {message}; no remote is configured, so nothing was pushed. \
699 Set one with `git -C {} remote add origin URL` and `git push -u origin HEAD`.\n",
700 root.display()
701 );
702 }
703 match crate::tracker_push::push_checkout(root) {
708 Ok(()) => format!("sync: committed {message}; pushed\n"),
709 Err(e) => format!("sync: committed {message}; push refused: {e}\n"),
710 }
711}
712
713fn catch_up(root: &Path) -> String {
718 if git(root, &["fetch", "-q", "--all"]).map_or(true, |o| !o.status.success()) {
719 return "sync: fetch failed; reading the logs as they are\n".into();
720 }
721 let Some(up) = crate::tracker_upstream(root) else {
722 return String::new();
723 };
724 let mut refs = vec![up.clone()];
725 refs.extend(
726 crate::tracker_mirrors(root, &up)
727 .unwrap_or_default()
728 .into_iter()
729 .map(|(r, b)| format!("{r}/{b}")),
730 );
731 let mut stuck = Vec::new();
732 for r in refs {
733 let forward = git(root, &["merge", "-q", "--ff-only", &r]);
734 if forward.is_ok_and(|o| o.status.success()) {
735 continue;
736 }
737 let merged = git(root, &["merge", "-q", "--no-edit", &r]);
740 if !merged.is_ok_and(|o| o.status.success()) {
741 let _ = git(root, &["merge", "--abort"]);
742 stuck.push(r);
743 }
744 }
745 if stuck.is_empty() {
746 String::new()
747 } else {
748 format!(
749 "sync: could not merge {}; `ljos doctor` names the split\n",
750 stuck.join(", ")
751 )
752 }
753}
754
755pub fn sync_repo(pull_import: bool, export_log: bool) -> Result<String> {
764 sync_repos(pull_import, export_log, true)
765}
766
767pub fn sync_repo_in_passing(pull_import: bool, export_log: bool) -> Result<String> {
776 sync_repos(pull_import, export_log, false)
777}
778
779fn sync_repos(pull_import: bool, export_log: bool, asked: bool) -> Result<String> {
780 let listed = local().repos;
781 let roots: Vec<PathBuf> = if listed.is_empty() {
782 vec![tracker_root()?]
783 } else {
784 listed.iter().map(|r| expand(r)).collect()
785 };
786 let mut out = String::new();
787 for root in roots {
788 out.push_str(&sync_one(&root, pull_import, export_log, asked)?);
789 }
790 Ok(out)
791}
792
793fn sync_one(root: &Path, pull_import: bool, export_log: bool, asked: bool) -> Result<String> {
794 let root = root.to_path_buf();
795 let mut out = String::new();
796 if let Err(e) = crate::tracker_push::prepare_tracker(&root, false, true) {
800 out.push_str(&format!("sync: merge setup: {e}\n"));
801 }
802 let Some(scope) = scope_of_repo(&root)? else {
803 if !asked {
804 return Ok(String::new());
805 }
806 out.push_str(&format!(
807 "sync: {} names no scope; write .ljos/sync.toml with name and recipients (`ljos sync --key` prints this machine's)\n",
808 root.display()
809 ));
810 return Ok(out);
811 };
812 if pull_import {
813 out.push_str(&catch_up(&root));
814 out.push_str(&import(&root, &scope)?);
815 }
816 if export_log {
817 let client = crate::pack()?;
818 let atoms = crate::atoms_lean(&client, &client.workspace())?;
819 let said = export(&root, &scope, &atoms)?;
820 out.push_str(&said);
821 out.push_str(&commit_if_sealed(&root, &scope.name, &said));
822 }
823 Ok(out)
824}
825
826fn user_rules_sync_off_value(value: Option<&str>) -> bool {
830 match value {
831 Some("off") => true,
832 Some(_) => false,
833 None => cfg!(test),
834 }
835}
836
837fn user_rules_sync_off() -> bool {
838 user_rules_sync_off_value(std::env::var("LJOS_USER_RULES_SYNC").ok().as_deref())
839}
840
841#[must_use]
847pub fn user_rule_trackers() -> Vec<PathBuf> {
848 if user_rules_sync_off() {
849 return Vec::new();
850 }
851 if let Some(one) = std::env::var("LJOS_USER_RULES_TRACKER")
852 .ok()
853 .filter(|path| !path.trim().is_empty())
854 {
855 return vec![expand(one.trim())];
856 }
857 let listed = local().repos;
858 if !listed.is_empty() {
859 return listed.iter().map(|path| expand(path)).collect();
860 }
861 if let Some(root) = std::env::var_os("ISSUE_ROOT")
862 .or_else(|| std::env::var_os("VISSUE_ROOT"))
863 .filter(|root| !root.is_empty())
864 {
865 return vec![PathBuf::from(root)];
866 }
867 if let Some(root) = seat_tracker() {
868 return vec![root];
869 }
870 if let Ok(cwd) = std::env::current_dir() {
871 if cwd.join("vissue.toml").is_file() {
872 return vec![cwd];
873 }
874 }
875 Vec::new()
876}
877
878fn seat_tracker() -> Option<PathBuf> {
879 #[derive(serde::Deserialize)]
880 struct Seat {
881 root: Option<String>,
882 }
883 let path = std::env::var_os("VISSUE_CONFIG")
884 .filter(|raw| !raw.is_empty())
885 .map(PathBuf::from)
886 .or_else(|| Some(config_dir().parent()?.join("vissue").join("config.toml")))?;
887 let text = std::fs::read_to_string(path).ok()?;
888 let root = toml::from_str::<Seat>(&text).ok()?.root?;
889 let path = expand(root.trim());
890 path.is_dir().then_some(path)
891}
892
893fn machine_name(host: &str) -> String {
894 let clean: String = host
895 .chars()
896 .map(|c| {
897 if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
898 c
899 } else {
900 '-'
901 }
902 })
903 .collect();
904 let clean = clean.trim_matches('.').to_string();
905 if clean.is_empty() {
906 "host".into()
907 } else {
908 clean
909 }
910}
911
912fn looks_like_git(root: &Path) -> bool {
913 let git = root.join(".git");
914 git.is_dir() || git.is_file()
915}
916
917fn repo_rows(root: &Path) -> Vec<crate::user_rules::UserRule> {
918 let dir = root.join(".ljos").join("user-rules");
919 let Ok(read) = std::fs::read_dir(&dir) else {
920 return Vec::new();
921 };
922 let mut paths: Vec<PathBuf> = read
923 .filter_map(|entry| entry.ok())
924 .map(|entry| entry.path())
925 .filter(|path| path.extension().is_some_and(|ext| ext == "json"))
926 .collect();
927 paths.sort();
928 let mut rows = Vec::new();
929 for path in paths {
930 let Ok(text) = std::fs::read_to_string(&path) else {
931 continue;
932 };
933 if let Ok(parsed) = crate::user_rules::parse_rules(&text) {
934 rows.extend(parsed);
935 }
936 }
937 rows
938}
939
940fn git_within(
941 root: &Path,
942 args: &[&str],
943 deadline: std::time::Instant,
944) -> Result<std::process::Output> {
945 use std::os::unix::process::CommandExt;
946 let budget = deadline.saturating_duration_since(std::time::Instant::now());
947 if budget.is_zero() {
948 bail!(
949 "sync: user rules: no time left for git {}",
950 args.first().copied().unwrap_or("")
951 );
952 }
953 let mut cmd = Command::new("git");
954 cmd.arg("-C")
955 .arg(root)
956 .args(args)
957 .env("GIT_TERMINAL_PROMPT", "0")
958 .stdin(Stdio::null())
959 .stdout(Stdio::piped())
960 .stderr(Stdio::piped());
961 unsafe {
965 cmd.pre_exec(|| {
966 libc::setpgid(0, 0);
967 Ok(())
968 });
969 }
970 let child = cmd.spawn().with_context(|| {
971 format!(
972 "sync: user rules: git {}",
973 args.first().copied().unwrap_or("")
974 )
975 })?;
976 let pid = child.id();
977 let (tx, rx) = std::sync::mpsc::channel();
978 std::thread::spawn(move || {
979 let _ = tx.send(child.wait_with_output());
980 });
981 match rx.recv_timeout(budget) {
982 Ok(Ok(out)) => Ok(out),
983 Ok(Err(err)) => Err(err).context("sync: user rules: git"),
984 Err(_) => {
985 unsafe {
988 libc::kill(-(pid as i32), libc::SIGKILL);
989 libc::kill(pid as i32, libc::SIGKILL);
990 }
991 bail!(
992 "sync: user rules: the tracker did not answer within {} ms",
993 budget.as_millis()
994 )
995 }
996 }
997}
998
999fn git_succeeded(out: &std::process::Output) -> bool {
1000 out.status.success()
1001}
1002
1003fn one_line(out: &std::process::Output) -> String {
1004 let text = String::from_utf8_lossy(&out.stderr);
1005 let text = if text.trim().is_empty() {
1006 String::from_utf8_lossy(&out.stdout)
1007 } else {
1008 text
1009 };
1010 text.lines()
1011 .find(|line| !line.trim().is_empty())
1012 .unwrap_or("")
1013 .trim()
1014 .to_string()
1015}
1016
1017fn integrate_remote(root: &Path, deadline: std::time::Instant) -> Result<()> {
1018 let fetched = git_within(root, &["fetch", "-q", "--all"], deadline)?;
1019 if !git_succeeded(&fetched) {
1020 bail!("sync: user rules: fetch failed: {}", one_line(&fetched));
1021 }
1022 let Some(up) = crate::tracker_upstream(root) else {
1023 return Ok(());
1024 };
1025 let forward = git_within(root, &["merge", "-q", "--ff-only", &up], deadline)?;
1026 if git_succeeded(&forward) {
1027 return Ok(());
1028 }
1029 let merged = git_within(root, &["merge", "-q", "--no-edit", &up], deadline)?;
1030 if git_succeeded(&merged) {
1031 return Ok(());
1032 }
1033 let _ = git_within(
1034 root,
1035 &["merge", "--abort"],
1036 std::time::Instant::now() + std::time::Duration::from_secs(2),
1037 );
1038 bail!(
1039 "sync: user rules: could not merge {up}: {}",
1040 one_line(&merged)
1041 )
1042}
1043
1044fn commit_host(root: &Path, rel: &str, host: &str, deadline: std::time::Instant) -> Result<bool> {
1045 let common = git(root, &["rev-parse", "--git-common-dir"])
1046 .ok()
1047 .filter(|out| out.status.success())
1048 .map(|out| {
1049 let rel_git = String::from_utf8_lossy(&out.stdout).trim().to_string();
1050 let path = PathBuf::from(&rel_git);
1051 if path.is_absolute() {
1052 path
1053 } else {
1054 root.join(path)
1055 }
1056 })
1057 .unwrap_or_else(|| root.join(".git"));
1058 let held = crate::CommitLock::acquire(&common.join("ljos-commit.lock"));
1059 let added = git_within(root, &["add", "--", rel], deadline)?;
1060 if !git_succeeded(&added) {
1061 bail!(
1062 "sync: user rules: could not stage {rel}: {}",
1063 one_line(&added)
1064 );
1065 }
1066 let staged = git_within(root, &["diff", "--cached", "--quiet", "--", rel], deadline)?;
1067 if git_succeeded(&staged) {
1068 drop(held);
1069 return Ok(false);
1070 }
1071 let message = format!("chore(sync): {host} user rules");
1072 let committed = git_within(
1073 root,
1074 &["commit", "-q", "--only", "-m", &message, "--", rel],
1075 deadline,
1076 )?;
1077 drop(held);
1078 if git_succeeded(&committed) {
1079 Ok(true)
1080 } else {
1081 bail!("sync: user rules: commit refused: {}", one_line(&committed))
1082 }
1083}
1084
1085fn push_host(root: &Path, deadline: std::time::Instant) -> Result<()> {
1086 let upstream = git(root, &["rev-parse", "--abbrev-ref", "@{upstream}"])
1087 .ok()
1088 .is_some_and(|out| out.status.success());
1089 let args: &[&str] = if upstream {
1090 &["push", "-q"]
1091 } else {
1092 &["push", "-q", "-u", "origin", "HEAD"]
1093 };
1094 let pushed = git_within(root, args, deadline)?;
1095 if git_succeeded(&pushed) {
1096 return Ok(());
1097 }
1098 let said = format!(
1099 "{}\n{}",
1100 one_line(&pushed),
1101 String::from_utf8_lossy(&pushed.stderr)
1102 );
1103 if !crate::tracker_push::rejected(&said) {
1104 bail!("sync: user rules: push refused: {}", one_line(&pushed));
1105 }
1106 integrate_remote(root, deadline)?;
1107 let again = git_within(root, args, deadline)?;
1108 if git_succeeded(&again) {
1109 Ok(())
1110 } else {
1111 bail!("sync: user rules: push refused: {}", one_line(&again))
1112 }
1113}
1114
1115pub fn exchange_user_rules(root: &Path, host: &str, budget: std::time::Duration) -> Result<String> {
1124 if !root.is_dir() {
1125 bail!("sync: user rules: {} is not a directory", root.display());
1126 }
1127 if !looks_like_git(root) {
1128 bail!("sync: user rules: {} is not a git checkout", root.display());
1129 }
1130 let deadline = std::time::Instant::now() + budget;
1131 let remote = git(root, &["remote"])
1132 .ok()
1133 .filter(|out| out.status.success())
1134 .is_some_and(|out| !String::from_utf8_lossy(&out.stdout).trim().is_empty());
1135 if remote {
1136 integrate_remote(root, deadline)?;
1137 } else {
1138 let local_empty = crate::user_rules::read_all().is_ok_and(|rows| rows.is_empty());
1139 if local_empty && repo_rows(root).is_empty() {
1140 return Ok(String::new());
1141 }
1142 }
1143 let mut rows = repo_rows(root);
1144 rows.extend(crate::user_rules::read_all()?);
1145 let merged = crate::user_rules::merge_rows(rows);
1146 crate::user_rules::replace_stored(&merged)?;
1147 let name = machine_name(host);
1148 let rel = format!(".ljos/user-rules/{name}.json");
1149 let path = root.join(&rel);
1150 if let Some(parent) = path.parent() {
1151 std::fs::create_dir_all(parent)?;
1152 }
1153 std::fs::write(&path, crate::user_rules::render_rules(&merged)?)?;
1154 let committed = commit_host(root, &rel, &name, deadline)?;
1155 let mut out = String::new();
1156 if remote {
1157 out.push_str("sync: user rules: fetched\n");
1158 }
1159 if committed || (remote && commits_to_push(root)) {
1160 push_host(root, deadline)?;
1161 out.push_str("sync: user rules: pushed\n");
1162 }
1163 let live = merged.iter().filter(|rule| !rule.deleted).count();
1164 out.push_str(&format!("sync: user rules: {live} on this machine\n"));
1165 Ok(out)
1166}
1167
1168#[cfg(test)]
1169mod tests {
1170 use super::*;
1171
1172 fn atom(id: &str, text: &str, entities: &[&str]) -> Value {
1173 serde_json::json!({"id": id, "text": text, "kind": "lesson",
1174 "entities": entities, "embedding": [0.1, 0.2]})
1175 }
1176
1177 #[test]
1178 fn an_unset_user_rules_sync_is_off_in_tests() {
1179 assert!(user_rules_sync_off_value(None));
1180 assert!(user_rules_sync_off_value(Some("off")));
1181 assert!(!user_rules_sync_off_value(Some("on")));
1182 }
1183
1184 #[test]
1185 fn a_repository_with_no_scope_is_named_only_when_sync_is_asked_for() {
1186 let _scratch = tempfile::tempdir().unwrap();
1187 let root = _scratch.path().to_path_buf();
1188 let asked = sync_one(&root, true, false, true).unwrap();
1189 assert!(asked.contains("names no scope"), "{asked}");
1190 assert_eq!(sync_one(&root, true, false, false).unwrap(), "");
1191 assert_eq!(sync_one(&root, false, true, false).unwrap(), "");
1192 let _ = std::fs::remove_dir(&root);
1193 }
1194
1195 #[test]
1197 fn a_log_with_no_remote_says_how_to_set_one() {
1198 let _g = crate::test_env_lock();
1199 let dir = tempfile::tempdir().unwrap();
1200 let root = dir.path();
1201 let git = |args: &[&str]| {
1202 let out = std::process::Command::new("git")
1203 .arg("-C")
1204 .arg(root)
1205 .args(args)
1206 .output()
1207 .unwrap();
1208 assert!(
1209 out.status.success(),
1210 "git {args:?}: {}",
1211 String::from_utf8_lossy(&out.stderr)
1212 );
1213 };
1214 git(&["init", "-q"]);
1215 git(&["config", "user.email", "seat@example.invalid"]);
1216 git(&["config", "user.name", "seat"]);
1217 git(&["config", "core.hooksPath", "/dev/null"]);
1218 let atoms = root.join(".ljos/atoms");
1219 std::fs::create_dir_all(&atoms).unwrap();
1220 let name = host();
1221 std::fs::write(atoms.join(format!("{name}.jsonl.age")), "sealed\n").unwrap();
1222 std::fs::write(atoms.join(format!("{name}.digest")), "digest\n").unwrap();
1223 let said = commit_log(root, "surf");
1224 assert!(said.contains("no remote is configured"), "{said}");
1225 assert!(said.contains("remote add origin"), "{said}");
1226 assert!(said.contains("git push -u origin HEAD"), "{said}");
1227 assert!(!said.contains("pushed to nothing"), "{said}");
1228 assert_eq!(commit_log(root, "surf"), "");
1229 }
1230
1231 #[test]
1234 fn unchanged_atoms_still_push_a_pending_commit() {
1235 let _g = crate::test_env_lock();
1236 let dir = tempfile::tempdir().unwrap();
1237 let remote = dir.path().join("remote.git");
1238 let root = dir.path().join("local");
1239 let git = |cwd: &std::path::Path, args: &[&str]| {
1240 let out = std::process::Command::new("git")
1241 .arg("-C")
1242 .arg(cwd)
1243 .args(args)
1244 .output()
1245 .unwrap();
1246 assert!(
1247 out.status.success(),
1248 "git {args:?}: {}",
1249 String::from_utf8_lossy(&out.stderr)
1250 );
1251 };
1252 std::fs::create_dir_all(&remote).unwrap();
1253 git(&remote, &["init", "-q", "--bare"]);
1254 std::fs::create_dir_all(&root).unwrap();
1255 git(&root, &["init", "-q"]);
1256 git(&root, &["config", "user.email", "seat@example.invalid"]);
1257 git(&root, &["config", "user.name", "seat"]);
1258 git(&root, &["config", "core.hooksPath", "/dev/null"]);
1259 let atoms = root.join(".ljos/atoms");
1260 std::fs::create_dir_all(&atoms).unwrap();
1261 let name = host();
1262 std::fs::write(atoms.join(format!("{name}.jsonl.age")), "sealed\n").unwrap();
1263 std::fs::write(atoms.join(format!("{name}.digest")), "digest\n").unwrap();
1264 std::fs::write(root.join("README"), "seed\n").unwrap();
1265 git(&root, &["add", "."]);
1266 git(&root, &["commit", "-q", "-m", "seed"]);
1267 git(
1268 &root,
1269 &["remote", "add", "origin", remote.to_str().unwrap()],
1270 );
1271 git(&root, &["push", "-q", "-u", "origin", "HEAD"]);
1272 std::fs::write(root.join(".gitattributes"), "*.org merge=union\n").unwrap();
1273 git(&root, &["add", ".gitattributes"]);
1274 git(
1275 &root,
1276 &[
1277 "commit",
1278 "-q",
1279 "-m",
1280 "chore(tracker): union org files and re-export atoms on merge",
1281 ],
1282 );
1283 let said = commit_log(&root, "surf");
1284 assert!(
1285 said.contains("pushed pending commits"),
1286 "an unchanged atom log must still push: {said}"
1287 );
1288 let remote_log = std::process::Command::new("git")
1289 .arg("-C")
1290 .arg(&remote)
1291 .args(["log", "--format=%s"])
1292 .output()
1293 .unwrap();
1294 let subjects = String::from_utf8_lossy(&remote_log.stdout);
1295 assert!(
1296 subjects.contains("union org files"),
1297 "the pending commit was not pushed: {subjects}"
1298 );
1299 assert_eq!(commit_log(&root, "surf"), "");
1300 }
1301
1302 #[test]
1304 fn a_missing_age_skips_the_seal_without_an_os_error() {
1305 let _hide = hide_age();
1306 let root = tempfile::tempdir().unwrap();
1307 let scope: Scope =
1308 toml::from_str("name = \"surf\"\nrecipients = [\"age1test\"]\n").unwrap();
1309 let said = export(root.path(), &scope, &[atom("a", "kept", &[])]).unwrap();
1310 assert!(said.contains("age is not installed"), "{said}");
1311 assert!(said.contains("install age"), "{said}");
1312 assert!(!said.contains("os error"), "{said}");
1313 assert!(!said.to_lowercase().contains("not found"), "{said}");
1314 assert!(!log_dir(root.path())
1315 .join(format!("{}.jsonl.age", host()))
1316 .is_file());
1317 assert_eq!(commit_if_sealed(root.path(), "surf", &said), "");
1318 }
1319
1320 #[test]
1321 fn a_log_carries_own_atoms_of_its_scope_without_vectors() {
1322 let atoms = vec![
1323 atom("b", "second", &["seat:x"]),
1324 atom("a", "first", &[]),
1325 atom("c", "personal", &["scope:personal"]),
1326 atom("d", "imported", &["sync:otherhost"]),
1327 ];
1328 let plain = log_plaintext(&atoms, "surf", "surf");
1329 let lines: Vec<Value> = plain
1330 .lines()
1331 .map(|l| serde_json::from_str(l).unwrap())
1332 .collect();
1333 assert_eq!(lines.len(), 2, "{plain}");
1334 assert_eq!(lines[0]["id"], "a");
1335 assert_eq!(lines[1]["id"], "b");
1336 assert!(lines.iter().all(|a| a.get("embedding").is_none()));
1337 assert_eq!(log_plaintext(&atoms, "personal", "surf").lines().count(), 1);
1338 }
1339
1340 #[test]
1341 fn a_project_named_in_the_scope_file_takes_its_own_scope() {
1342 let scope: Scope = toml::from_str(
1343 "name = \"personal\"\nrecipients = [\"age1x\"]\n[projects]\ntools = \"shared\"\n",
1344 )
1345 .unwrap();
1346 assert_eq!(scope.for_project("tools"), "shared");
1347 assert_eq!(scope.for_project("garden"), "personal");
1348 let bare: Scope = toml::from_str("name = \"shared\"\nrecipients = []\n").unwrap();
1349 assert!(bare.projects.is_empty());
1350 }
1351
1352 #[test]
1353 fn an_import_tags_the_sender_and_names_what_it_retired() {
1354 let plain = format!(
1355 "{}\n{}\n",
1356 atom("a", "kept", &["seat:x"]),
1357 atom("b", "new", &[])
1358 );
1359 let before: BTreeSet<String> = [crate::work_id("kept"), crate::work_id("dropped")].into();
1360 let got = incoming(&plain, "rglat", &before, &BTreeSet::new());
1361 assert_eq!(got.post.len(), 2);
1362 let again = incoming(&plain, "rglat", &before, &[crate::work_id("kept")].into());
1363 assert_eq!(
1364 again.post.len(),
1365 1,
1366 "a text already held is not posted again"
1367 );
1368 assert_eq!(again.post[0]["text"], "new");
1369 assert!(got.post.iter().all(|a| a.get("id").is_none()));
1370 assert!(got.post.iter().all(|a| a["entities"]
1371 .as_array()
1372 .unwrap()
1373 .iter()
1374 .any(|e| e == "sync:rglat")));
1375 assert!(got.post.iter().all(|a| a["origin"] == "peer"));
1376 assert_eq!(got.retired, vec![crate::work_id("dropped")]);
1377 let claimed = "{\"id\":\"c\",\"text\":\"claimed\",\"kind\":\"lesson\",\"origin\":\"user-declared\",\"entities\":[]}\n";
1378 let overwrote = incoming(claimed, "rglat", &BTreeSet::new(), &BTreeSet::new());
1379 assert_eq!(overwrote.post[0]["origin"], "peer");
1380 }
1381
1382 #[test]
1383 fn a_sealed_log_opens_for_a_recipient_and_not_for_another() {
1384 let _g = crate::test_env_lock();
1385 let dir = tempfile::tempdir().unwrap();
1386 let key = |name: &str| {
1387 let path = dir.path().join(name);
1388 let made = Command::new("age-keygen")
1389 .arg("-o")
1390 .arg(&path)
1391 .output()
1392 .unwrap();
1393 assert!(made.status.success(), "age-keygen must be installed");
1394 let public = Command::new("age-keygen")
1395 .arg("-y")
1396 .arg(&path)
1397 .output()
1398 .unwrap();
1399 (
1400 path,
1401 String::from_utf8_lossy(&public.stdout).trim().to_string(),
1402 )
1403 };
1404 let (mine, my_public) = key("mine.key");
1405 let (other, _) = key("other.key");
1406 let out = dir.path().join("host.jsonl.age");
1407 seal("{\"text\":\"x\"}\n", &[my_public], &out).unwrap();
1408 assert_eq!(
1409 open(&out, &mine).unwrap().as_deref(),
1410 Some("{\"text\":\"x\"}\n")
1411 );
1412 assert_eq!(open(&out, &other).unwrap(), None);
1413 assert!(seal("x", &[], &out).is_err(), "no recipients is refused");
1414 }
1415
1416 #[test]
1417 fn an_atoms_scope_is_its_entity_or_the_default() {
1418 assert_eq!(
1419 atom_scope(&atom("a", "t", &["scope:personal"]), "surf"),
1420 "personal"
1421 );
1422 assert_eq!(atom_scope(&atom("a", "t", &["seat:x"]), "surf"), "surf");
1423 }
1424}