Skip to main content

lean_ctx_cloud/
bring_local.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Bringing a project's local work into the vault it was just linked to
3//! (`lean-ctx cloud link --bring-local`): its local tasks
4//! ([`crate::tasks::local`]) become proposed tasks of the vault, and its
5//! local doc pages ([`crate::local_docs`]) pages of the vault, once each.
6//!
7//! A local task is brought when it was never shared and is open: Cloud opens
8//! every task an Instance proposes (owner decision 25.10.), so a task that
9//! is only proposed locally stays local until it is accepted, and a claimed
10//! or submitted one stays local so no claim, result or evidence is lost.
11//! Its goal ends with `"Local task #<n>"` as the reference, and it is marked
12//! shared locally with the vault's number, so a second run skips it. Before
13//! a task is sent, a local ledger records it; a run interrupted after Cloud
14//! answered (or after the request left) resumes from that ledger instead
15//! of sending it twice ([`bring_tasks`]).
16//!
17//! A page is brought when it was never shared and the vault has no page with
18//! its slug; `/slug` links between brought pages point at their new vault
19//! ids, links to pages the vault already holds point at those. After the
20//! events are queued, each brought page is marked shared locally (journaled,
21//! by the person, "cloud link"), so a second run skips it. The events reach
22//! Cloud with the next push; the background sync retries what fails.
23
24use std::collections::BTreeMap;
25use std::path::Path;
26
27use serde::Serialize;
28
29use lean_ctx_doc::Page;
30use lean_ctx_doc::links;
31use lean_ctx_doc::local::Author;
32use lean_ctx_doc::write::{self, EventSpec};
33
34use lean_ctx_protocol::cloud::tasks::TaskState;
35use lean_ctx_tasks::LocalTask;
36
37use crate::CloudError;
38use crate::local_docs::{self, LocalPage};
39use crate::tasks::propose::{ProposalKind, QueuedProposal};
40
41/// Who a link import is recorded as: the person runs `cloud link`.
42pub fn author() -> Author {
43    Author::person("cloud link")
44}
45
46/// One local page and what the link does with it.
47#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
48pub struct DocItem {
49    pub local_id: String,
50    pub slug: String,
51    pub title: String,
52    /// `import` | `skip`.
53    pub action: &'static str,
54    /// `already_shared` | `exists_in_vault` for a skip; else `null`.
55    pub reason: Option<&'static str>,
56    /// The vault page it became (or already is, for `already_shared`).
57    pub vault_page_id: Option<String>,
58}
59
60/// What to do with each of `pages`, given the vault's slugs (`slug → id`;
61/// empty when the vault is not read, as on a dry run).
62pub fn plan_docs(pages: &[LocalPage], vault: &BTreeMap<String, String>) -> Vec<DocItem> {
63    pages
64        .iter()
65        .map(|p| {
66            let (action, reason, vault_page_id) = match (&p.shared, vault.get(&p.slug)) {
67                (Some(shared), _) => ("skip", Some("already_shared"), Some(shared.page_id.clone())),
68                (None, Some(_)) => ("skip", Some("exists_in_vault"), None),
69                (None, None) => ("import", None, None),
70            };
71            DocItem {
72                local_id: p.id.clone(),
73                slug: p.slug.clone(),
74                title: p.title.clone(),
75                action,
76                reason,
77                vault_page_id,
78            }
79        })
80        .collect()
81}
82
83/// The vault events that create every `import` item of `items` from its
84/// `raw` page (storage form, `cloud:<local id>` links), choosing its vault
85/// id with `new_id` and filling it into the item.
86pub fn doc_events(
87    items: &mut [DocItem],
88    raw: &[Page],
89    vault: &BTreeMap<String, String>,
90    new_id: &mut dyn FnMut(&str) -> String,
91) -> Vec<EventSpec> {
92    let local_slug: BTreeMap<String, String> = items
93        .iter()
94        .map(|i| (i.local_id.clone(), i.slug.clone()))
95        .collect();
96    let mut ids = vault.clone();
97    for item in items.iter_mut().filter(|i| i.action == "import") {
98        let id = new_id("n");
99        ids.insert(item.slug.clone(), id.clone());
100        item.vault_page_id = Some(id);
101    }
102    let raw_by_slug: BTreeMap<&str, &Page> = raw.iter().map(|p| (p.slug.as_str(), p)).collect();
103    let mut out = Vec::new();
104    for item in items.iter().filter(|i| i.action == "import") {
105        let Some(page) = raw_by_slug.get(item.slug.as_str()) else {
106            continue;
107        };
108        let mut page = (*page).clone();
109        let mut targets = Vec::new();
110        for section in &mut page.sections {
111            let readable = links::to_slugs(&section.text, |id| local_slug.get(id).cloned());
112            section.text = links::to_storage(&readable, |slug| ids.get(slug).cloned()).0;
113            for t in links::targets(&section.text) {
114                if let links::Target::Node { id, .. } = links::classify(t) {
115                    targets.push(id.to_owned());
116                }
117            }
118        }
119        targets.sort();
120        targets.dedup();
121        // `create_page` asks for the page id first: hand it the one chosen.
122        let mut chosen = item.vault_page_id.clone();
123        let mut choose = |prefix: &str| match chosen.take() {
124            Some(id) if prefix == "n" => id,
125            other => {
126                chosen = other;
127                new_id(prefix)
128            }
129        };
130        let (specs, _) = write::create_page(&page, &targets, &mut choose);
131        out.extend(specs);
132    }
133    out
134}
135
136/// Bring the local pages of `root` into its linked vault `vault` (`ns/name`).
137/// Needs the vault's replica on this machine (the first sync makes it).
138pub fn import_docs(root: &str, vault: &str) -> Result<Vec<DocItem>, CloudError> {
139    let pages = local_docs::pages(root)?;
140    if pages.is_empty() {
141        return Ok(Vec::new());
142    }
143    let raw = local_docs::store(root)?.pages()?;
144    crate::docs::require_docs_protocol(&crate::CloudStore::open()?)?;
145    let items = crate::docs::with_vault(root, |v| {
146        let space = crate::docs::space(v.target.replica)?;
147        let mut items = plan_docs(&pages, &space.by_slug);
148        let specs = doc_events(&mut items, &raw, &space.by_slug, &mut |p| {
149            crate::docs::new_id(p)
150        });
151        if !specs.is_empty() {
152            let now = lean_ctx_time::UtcDateTime::now()
153                .timestamp_millis()
154                .unsigned_abs();
155            let mut screen = crate::knowledge::screening::Screen::for_installation();
156            crate::docs::queue_specs(&v.target, specs, &mut screen, now)?;
157        }
158        Ok(items)
159    })?;
160    let author = author();
161    for item in items.iter().filter(|i| i.action == "import") {
162        if let Some(page_id) = &item.vault_page_id {
163            local_docs::mark_shared(root, &item.local_id, vault, page_id, &author)?;
164        }
165    }
166    if items.iter().any(|i| i.action == "import") {
167        // Best effort now; the background sync sends what is still queued.
168        let _ = crate::docs::push_queued(root);
169    }
170    Ok(items)
171}
172
173/// One local task and what the link does with it.
174#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
175pub struct TaskItem {
176    pub local_number: u64,
177    pub title: Option<String>,
178    /// The local state (Cloud's task states).
179    pub state: String,
180    /// `propose` | `skip`.
181    pub action: &'static str,
182    /// For a skip: `already_shared` | `not_accepted` | `in_progress` |
183    /// `done` | `cancelled` | `rejected` | `failed` | `unknown_state` |
184    /// `no_title` | `no_acceptance`; else `null`.
185    pub reason: Option<&'static str>,
186    /// The vault task it became (or already is, for `already_shared`).
187    pub vault_number: Option<u64>,
188    /// Why bringing it did not finish this time (a later link resumes it).
189    pub error: Option<String>,
190}
191
192/// What `--bring-local` brings (or would bring).
193#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
194pub struct Brought {
195    pub tasks: Vec<TaskItem>,
196    pub docs: Vec<DocItem>,
197    /// Why the pages did not go this time (`docs` is then the plan); the
198    /// tasks may have gone all the same.
199    pub docs_error: Option<String>,
200}
201
202impl Brought {
203    /// Every task and page that was to go went.
204    pub fn complete(&self) -> bool {
205        self.docs_error.is_none() && self.tasks.iter().all(|t| t.error.is_none())
206    }
207
208    /// Something went into the vault in this run.
209    pub fn any_applied(&self) -> bool {
210        self.tasks
211            .iter()
212            .any(|t| t.action == "propose" && t.vault_number.is_some())
213            || (self.docs_error.is_none() && self.docs.iter().any(|d| d.action == "import"))
214    }
215}
216
217fn state_name(state: TaskState) -> String {
218    serde_json::to_value(state)
219        .ok()
220        .and_then(|v| v.as_str().map(str::to_owned))
221        .unwrap_or_else(|| "unknown".into())
222}
223
224fn filled(text: Option<&String>) -> bool {
225    text.is_some_and(|t| !t.trim().is_empty())
226}
227
228/// What to do with each local task.
229pub fn plan_tasks(tasks: &[LocalTask]) -> Vec<TaskItem> {
230    tasks
231        .iter()
232        .map(|local| {
233            let task = &local.task;
234            let reason = match (&local.shared, task.state) {
235                (Some(_), _) => Some("already_shared"),
236                (None, TaskState::Done) => Some("done"),
237                (None, TaskState::Cancelled) => Some("cancelled"),
238                (None, TaskState::Rejected) => Some("rejected"),
239                (None, TaskState::Failed) => Some("failed"),
240                (None, TaskState::Unknown) => Some("unknown_state"),
241                (None, TaskState::Proposed) => Some("not_accepted"),
242                (None, TaskState::Claimed | TaskState::Submitted) => Some("in_progress"),
243                _ if !filled(task.title.as_ref()) => Some("no_title"),
244                _ if !filled(task.acceptance.as_ref()) => Some("no_acceptance"),
245                _ => None,
246            };
247            TaskItem {
248                local_number: task.number,
249                title: task.title.clone(),
250                state: state_name(task.state),
251                action: if reason.is_some() { "skip" } else { "propose" },
252                reason,
253                vault_number: local.shared.as_ref().map(|s| s.number),
254                error: None,
255            }
256        })
257        .collect()
258}
259
260/// The vault proposal for local task `local` of the project `stable`.
261pub fn task_proposal(local: &LocalTask, stable: &str, root: &Path) -> QueuedProposal {
262    let task = &local.task;
263    let reference = format!("Local task #{}", task.number);
264    QueuedProposal {
265        kind: ProposalKind::Agent,
266        stable_identity: stable.to_owned(),
267        root: root.to_string_lossy().into_owned(),
268        facts: Vec::new(),
269        title: task.title.clone().unwrap_or_default().trim().to_owned(),
270        goal: Some(match task.goal.as_deref().map(str::trim) {
271            Some(goal) if !goal.is_empty() => format!("{goal}\n\n{reference}"),
272            _ => reference,
273        }),
274        acceptance: task
275            .acceptance
276            .clone()
277            .unwrap_or_default()
278            .trim()
279            .to_owned(),
280        role: task.role.clone(),
281        // A constant label that names no session.
282        session_ref: Some(crate::knowledge::draft::session_ref("cloud-link")),
283        local_number: Some(task.number),
284        ref_keyed: true,
285    }
286}
287
288fn local_tasks(root: &Path) -> Result<Vec<LocalTask>, CloudError> {
289    crate::tasks::local::list(root).map_err(CloudError::Local)
290}
291
292/// The plan for `root` from local state only (`--dry-run`, or before the
293/// vault is shared): pages the vault already holds show as `import` here.
294pub fn plan_local(root: &str) -> Result<Brought, CloudError> {
295    Ok(Brought {
296        tasks: plan_tasks(&local_tasks(Path::new(root))?),
297        docs: plan_docs(&local_docs::pages(root)?, &BTreeMap::new()),
298        docs_error: None,
299    })
300}
301
302/// Cloud replays a proposal's first answer for this long after it (its
303/// instance idempotency keys live 7 days); a ledger entry older than this
304/// is never sent again.
305pub const RESEND_WINDOW_SECS: i64 = 6 * 24 * 60 * 60;
306
307/// A task on its way into a vault, recorded before it is sent.
308#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]
309pub struct InFlight {
310    pub vault_id: String,
311    /// The proposal's idempotency key.
312    pub key: String,
313    /// Unix seconds when it was first sent.
314    pub sent_at: i64,
315    /// Cloud's number once it answered.
316    pub vault_number: Option<u64>,
317}
318
319/// The tasks of one project on their way into a vault, by local number.
320#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, serde::Deserialize)]
321pub struct Ledger {
322    pub tasks: BTreeMap<u64, InFlight>,
323}
324
325fn ledger_name(root: &Path) -> String {
326    format!(
327        "bring-local-{}.json",
328        lean_ctx::core::project_hash::hash_project_root(&root.to_string_lossy())
329    )
330}
331
332/// What [`bring_tasks`] calls on the outside world.
333pub struct TaskSink<'a> {
334    /// Send one proposal; Cloud's number for it.
335    pub propose: &'a mut dyn FnMut(&QueuedProposal) -> Result<u64, CloudError>,
336    /// Record local task `n` as brought as vault task `number`.
337    pub mark: &'a mut dyn FnMut(u64, u64) -> Result<(), lean_ctx_tasks::TaskError>,
338    /// Persist the ledger.
339    pub save: &'a mut dyn FnMut(&Ledger) -> Result<(), CloudError>,
340}
341
342/// Bring every `propose` item of `items` (planned from `tasks`, proposals
343/// from `proposal_of`) into the vault `vault_id`. Each task is entered in
344/// `ledger` before it is sent, gets its number there as soon as Cloud
345/// answers, and leaves it once it is marked shared. A task found in the
346/// ledger resumes from there: a known number is only marked, never sent
347/// again; an unanswered send is repeated with the same key inside
348/// [`RESEND_WINDOW_SECS`] (Cloud replays its first answer) and after that is
349/// reported, never resent, so an interrupted run never makes a second vault
350/// task.
351pub fn bring_tasks(
352    items: &mut [TaskItem],
353    tasks: &[LocalTask],
354    proposal_of: &dyn Fn(&LocalTask) -> QueuedProposal,
355    vault_id: &str,
356    now: i64,
357    ledger: &mut Ledger,
358    sink: &mut TaskSink<'_>,
359) {
360    for (item, local) in items.iter_mut().zip(tasks) {
361        if item.action != "propose" {
362            continue;
363        }
364        let n = item.local_number;
365        // An entry for another vault (a re-link) says nothing about this one.
366        let entry = ledger
367            .tasks
368            .get(&n)
369            .cloned()
370            .filter(|e| e.vault_id == vault_id);
371        let number = match entry {
372            Some(InFlight {
373                vault_number: Some(number),
374                ..
375            }) => Ok(number),
376            Some(sent) if now - sent.sent_at >= RESEND_WINDOW_SECS => Err(format!(
377                "an earlier link sent local task #{n} and was interrupted before LeanCTX Cloud answered; it is not sent again (it may be in the vault already: look for \"Local task #{n}\")"
378            )),
379            earlier => {
380                let proposal = proposal_of(local);
381                ledger.tasks.insert(
382                    n,
383                    InFlight {
384                        vault_id: vault_id.to_owned(),
385                        key: proposal.idempotency_key(),
386                        sent_at: earlier.map_or(now, |e| e.sent_at),
387                        vault_number: None,
388                    },
389                );
390                match (sink.save)(ledger).and_then(|()| (sink.propose)(&proposal)) {
391                    Ok(number) => {
392                        if let Some(entry) = ledger.tasks.get_mut(&n) {
393                            entry.vault_number = Some(number);
394                        }
395                        (sink.save)(ledger)
396                            .map(|()| number)
397                            .map_err(|e| e.to_string())
398                    }
399                    Err(e) if refused_for_good(&e) => {
400                        // Cloud (or the screen before it) said no: no vault
401                        // task exists, so nothing waits to be resumed.
402                        ledger.tasks.remove(&n);
403                        let _ = (sink.save)(ledger);
404                        Err(format!(
405                            "local task #{n} was refused and not created ({e}); change it locally and link again"
406                        ))
407                    }
408                    Err(e) => Err(format!(
409                        "local task #{n} did not get LeanCTX Cloud's answer ({e}); the next link resumes it"
410                    )),
411                }
412            }
413        };
414        let marked = number.and_then(|number| match (sink.mark)(n, number) {
415            Ok(()) => Ok(number),
416            // Marked by the interrupted run already.
417            Err(e) if e.reason() == Some("already_shared") => Ok(number),
418            Err(e) => Err(e.to_string()),
419        });
420        match marked {
421            Ok(number) => {
422                item.vault_number = Some(number);
423                ledger.tasks.remove(&n);
424                if let Err(e) = (sink.save)(ledger) {
425                    item.error = Some(e.to_string());
426                }
427            }
428            Err(e) => item.error = Some(e),
429        }
430    }
431}
432
433/// A refusal after which no vault task exists and none will: the screen
434/// or the request check refused it, or Cloud answered with a 4xx. A lost
435/// connection, a 5xx or an unreadable answer may hide a created task.
436pub fn refused_for_good(error: &CloudError) -> bool {
437    match error {
438        CloudError::Refused(_)
439        | CloudError::Forbidden
440        | CloudError::NotFound
441        | CloudError::Vetoed
442        | CloudError::ScreeningBlocked
443        | CloudError::PolicyDenied(_)
444        | CloudError::PlanRequired(_)
445        | CloudError::Task { .. } => true,
446        CloudError::Server { status, .. } => (400..500).contains(status),
447        _ => false,
448    }
449}
450
451/// A local task the link would strand: only proposed, claimed or submitted
452/// (and not brought yet). Once a project is linked its tasks are Cloud's, so
453/// these are settled locally first.
454#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
455pub struct Unsettled {
456    pub local_number: u64,
457    pub title: Option<String>,
458    pub state: String,
459}
460
461/// The unsettled tasks among `tasks`.
462pub fn unsettled(tasks: &[LocalTask]) -> Vec<Unsettled> {
463    tasks
464        .iter()
465        .filter(|t| {
466            t.shared.is_none()
467                && matches!(
468                    t.task.state,
469                    TaskState::Proposed | TaskState::Claimed | TaskState::Submitted
470                )
471        })
472        .map(|t| Unsettled {
473            local_number: t.task.number,
474            title: t.task.title.clone(),
475            state: state_name(t.task.state),
476        })
477        .collect()
478}
479
480/// The unsettled local tasks of `root`.
481pub fn unsettled_local(root: &Path) -> Result<Vec<Unsettled>, CloudError> {
482    Ok(unsettled(&local_tasks(root)?))
483}
484
485/// Why a link that brings local work is refused while `list` is unsettled.
486pub fn unsettled_message(list: &[Unsettled]) -> String {
487    let named: Vec<String> = list
488        .iter()
489        .map(|u| format!("#{} ({})", u.local_number, u.state))
490        .collect();
491    format!(
492        "local tasks {} are not settled: once the project is linked its tasks are LeanCTX Cloud's, so decide on a proposal (accept or decline) and finish (submit and verify, or release) a claimed or submitted task first, then link again",
493        named.join(", ")
494    )
495}
496
497/// The flag that links a project although local tasks are unsettled; they
498/// then stay local and are reached with `lean-ctx tasks … --local`.
499pub const LEAVE_UNSETTLED_FLAG: &str = "--leave-unsettled-local";
500
501/// Every path that links a project asks this first: the unsettled local
502/// tasks of `root`, or why the link is refused (`leave` is the person's
503/// explicit [`LEAVE_UNSETTLED_FLAG`]).
504pub fn link_gate(root: &Path, leave: bool) -> Result<Vec<Unsettled>, String> {
505    let list = unsettled_local(root).map_err(|e| e.to_string())?;
506    if list.is_empty() || leave {
507        return Ok(list);
508    }
509    Err(format!(
510        "{} (or link with {LEAVE_UNSETTLED_FLAG}: they stay local, reached with `lean-ctx tasks … --local`)",
511        unsettled_message(&list)
512    ))
513}
514
515/// The local tasks of `root` that are neither brought into a vault nor
516/// closed: in a linked project they are "local, not shared" and stay
517/// reachable with `--local` (also when the link came in through git).
518pub fn local_not_shared(root: &Path) -> Result<Vec<Unsettled>, CloudError> {
519    Ok(local_tasks(root)?
520        .iter()
521        .filter(|t| {
522            t.shared.is_none()
523                && matches!(
524                    t.task.state,
525                    TaskState::Proposed
526                        | TaskState::Open
527                        | TaskState::Claimed
528                        | TaskState::Submitted
529                )
530        })
531        .map(|t| Unsettled {
532            local_number: t.task.number,
533            title: t.task.title.clone(),
534            state: state_name(t.task.state),
535        })
536        .collect())
537}
538
539/// One line naming `list` for a linked project's task list; `None` when
540/// there are none.
541pub fn not_shared_note(list: &[Unsettled]) -> Option<String> {
542    if list.is_empty() {
543        return None;
544    }
545    let named: Vec<String> = list
546        .iter()
547        .map(|u| format!("#{} ({})", u.local_number, u.state))
548        .collect();
549    Some(format!(
550        "local, not shared: {} (act on them with `lean-ctx tasks … --local`)",
551        named.join(", ")
552    ))
553}
554
555/// Whether `action` (on local task `number`, when it names one) may act on
556/// the local store of the linked project `root`: reads always; a write only
557/// on a task that was not brought into a vault; new tasks go to Cloud.
558pub fn local_action_in_linked(
559    root: &Path,
560    action: &str,
561    number: Option<u64>,
562) -> Result<(), String> {
563    match action {
564        "list" | "show" => return Ok(()),
565        "propose" => {
566            return Err(
567                "new tasks of a linked project go to LeanCTX Cloud (drop --local: `lean-ctx tasks propose`)"
568                    .into(),
569            );
570        }
571        _ => {}
572    }
573    let Some(n) = number else {
574        return Ok(());
575    };
576    let tasks = local_tasks(root).map_err(|e| e.to_string())?;
577    match tasks.iter().find(|t| t.task.number == n) {
578        None => Err(format!("this project has no local task #{n}")),
579        Some(t) => match &t.shared {
580            Some(shared) => Err(format!(
581                "local task #{n} was brought into {} as task #{}: act on it there (without --local)",
582                shared.vault, shared.number
583            )),
584            None => Ok(()),
585        },
586    }
587}
588
589/// Bring every open local task of `root` into the vault `vault_id`
590/// (`vault` = `ns/name`): [`bring_tasks`] against Cloud, the local task
591/// store and the ledger in this Instance's config.
592pub fn import_tasks(root: &Path, vault: &str, vault_id: &str) -> Result<Vec<TaskItem>, CloudError> {
593    let tasks = local_tasks(root)?;
594    let mut items = plan_tasks(&tasks);
595    if !items.iter().any(|i| i.action == "propose") {
596        return Ok(items);
597    }
598    let identity = crate::vault::project_identity(root).ok_or_else(|| {
599        CloudError::Config(
600            "this repository has no identity LeanCTX Cloud can link to a vault".into(),
601        )
602    })?;
603    let stable = lean_ctx_protocol::cloud::vault::stable_identity(&identity);
604    let store = crate::CloudStore::open()?;
605    let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
606    let config = lean_ctx::core::config::Config::load().cloud.clone();
607    let trust = crate::root_cert::trust_root(&store, &config, &instance.url)?;
608    let session = crate::auth::Session::load(store.clone(), trust)?;
609    let name = ledger_name(root);
610    let mut ledger: Ledger = store.read_config(&name)?.unwrap_or_default();
611    bring_tasks(
612        &mut items,
613        &tasks,
614        &|local| task_proposal(local, &stable, root),
615        vault_id,
616        lean_ctx_time::UtcDateTime::now().timestamp(),
617        &mut ledger,
618        &mut TaskSink {
619            propose: &mut |proposal| {
620                crate::tasks::propose::propose_now(&session, vault_id, proposal).map(|(n, _)| n)
621            },
622            mark: &mut |local, number| {
623                crate::tasks::local::write(root, |board, now| {
624                    board.mark_shared(
625                        local,
626                        &lean_ctx_tasks::Actor::person("person"),
627                        vault,
628                        number,
629                        now,
630                    )
631                })
632                .map(|_| ())
633            },
634            save: &mut |ledger| {
635                if ledger.tasks.is_empty() {
636                    store.remove_config(&name)
637                } else {
638                    store.write_config(&name, ledger)
639                }
640            },
641        },
642    );
643    Ok(items)
644}
645
646/// Bring the local tasks, then the local pages, of `root` into its linked
647/// vault (`vault` = `ns/name`, id `vault_id`). Pages need the vault's
648/// replica here; when they cannot go, the tasks that went stay reported as
649/// gone and `docs_error` says why the pages wait (`docs` is the plan then).
650pub fn import(root: &str, vault: &str, vault_id: &str) -> Result<Brought, CloudError> {
651    let tasks = import_tasks(Path::new(root), vault, vault_id)?;
652    Ok(match import_docs(root, vault) {
653        Ok(docs) => Brought {
654            tasks,
655            docs,
656            docs_error: None,
657        },
658        Err(e) => {
659            let (docs, error) = match local_docs::pages(root) {
660                Ok(pages) => (plan_docs(&pages, &BTreeMap::new()), e.to_string()),
661                Err(read) => (
662                    Vec::new(),
663                    format!("{e}; the local pages cannot be read: {read}"),
664                ),
665            };
666            Brought {
667                tasks,
668                docs,
669                docs_error: Some(error),
670            }
671        }
672    })
673}
674
675#[cfg(test)]
676mod tests {
677    use super::*;
678    use crate::local_docs::SharedTo;
679
680    fn local(id: &str, slug: &str, shared: bool) -> LocalPage {
681        LocalPage {
682            id: id.into(),
683            slug: slug.into(),
684            title: slug.into(),
685            body: String::new(),
686            kind: "reference".into(),
687            status: "draft".into(),
688            updated: None,
689            updated_by: None,
690            shared: shared.then(|| SharedTo {
691                vault: "platform/api".into(),
692                page_id: "n_old".into(),
693                at: "2026-11-04T10:00:00Z".into(),
694            }),
695        }
696    }
697
698    fn raw(slug: &str, text: &str) -> Page {
699        serde_json::from_value(serde_json::json!({
700            "slug": slug, "title": slug, "kind": "reference", "status": "draft",
701            "sections": [{"order": 0, "text": text}],
702        }))
703        .unwrap()
704    }
705
706    /// Each page is brought once: shared ones and slugs the vault holds are
707    /// skipped, and links between brought pages follow their new ids while
708    /// links to a vault page keep pointing at it.
709    #[test]
710    fn local_pages_come_once_with_their_links_pointing_into_the_vault() {
711        let pages = [
712            local("n_la", "guide", false),
713            local("n_lb", "setup", false),
714            local("n_lc", "old", true),
715            local("n_ld", "faq", false),
716        ];
717        let vault = BTreeMap::from([("faq".to_string(), "n_vfaq".to_string())]);
718        let mut items = plan_docs(&pages, &vault);
719        let plan: Vec<(&str, &str, Option<&str>)> = items
720            .iter()
721            .map(|i| (i.slug.as_str(), i.action, i.reason))
722            .collect();
723        assert_eq!(
724            plan,
725            [
726                ("guide", "import", None),
727                ("setup", "import", None),
728                ("old", "skip", Some("already_shared")),
729                ("faq", "skip", Some("exists_in_vault")),
730            ]
731        );
732        let raws = [
733            raw("guide", "See [setup](cloud:n_lb) and [faq](cloud:n_ld)."),
734            raw("setup", "Back to [guide](cloud:n_la)."),
735        ];
736        let mut n = 0;
737        let mut new_id = |prefix: &str| {
738            n += 1;
739            format!("{prefix}_new{n}")
740        };
741        let specs = doc_events(&mut items, &raws, &vault, &mut new_id);
742        assert_eq!(items[0].vault_page_id.as_deref(), Some("n_new1"));
743        assert_eq!(items[1].vault_page_id.as_deref(), Some("n_new2"));
744        assert_eq!(items[2].vault_page_id.as_deref(), Some("n_old"));
745        let text =
746            serde_json::to_string(&specs.iter().map(|s| &s.body).collect::<Vec<_>>()).unwrap();
747        assert!(
748            text.contains("cloud:n_new2") && text.contains("cloud:n_vfaq"),
749            "{text}"
750        );
751        assert!(text.contains("cloud:n_new1"), "{text}");
752        assert!(
753            !text.contains("n_la") && !text.contains("n_lb"),
754            "no local ids reach the vault: {text}"
755        );
756        assert!(
757            specs.iter().any(|s| s.target == "n_new1")
758                && specs.iter().any(|s| s.target == "n_new2")
759        );
760    }
761
762    fn local_task(
763        number: u64,
764        state: &str,
765        acceptance: Option<&str>,
766        shared: Option<u64>,
767    ) -> LocalTask {
768        let path = concat!(
769            env!("CARGO_MANIFEST_DIR"),
770            "/../lean-ctx-protocol/tests/fixtures/cloud/task.claimed.response.json"
771        );
772        let mut task: serde_json::Value =
773            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
774        task["number"] = number.into();
775        task["state"] = state.into();
776        task["claim"] = serde_json::Value::Null;
777        task["acceptance"] = acceptance.map_or(serde_json::Value::Null, Into::into);
778        serde_json::from_value(serde_json::json!({
779            "task": task,
780            "transitions": [],
781            "shared": shared.map(|n| serde_json::json!({
782                "vault": "platform/api", "number": n, "at": "2026-11-04T10:00:00Z"
783            })),
784        }))
785        .unwrap()
786    }
787
788    /// Open local tasks are proposed once each, with the local number kept
789    /// in the goal and in the proposal key; proposed, in-progress, finished,
790    /// shared and incomplete ones are skipped.
791    #[test]
792    fn live_local_tasks_are_proposed_once_with_their_local_number() {
793        let tasks = vec![
794            local_task(1, "open", Some("It works"), None),
795            local_task(2, "open", Some("It works"), None),
796            local_task(3, "done", Some("It works"), None),
797            local_task(4, "cancelled", Some("It works"), None),
798            local_task(5, "rejected", Some("It works"), None),
799            local_task(6, "failed", Some("It works"), None),
800            local_task(7, "open", Some("It works"), Some(12)),
801            local_task(8, "open", None, None),
802            local_task(9, "proposed", Some("It works"), None),
803            local_task(10, "claimed", Some("It works"), None),
804            local_task(11, "submitted", Some("It works"), None),
805        ];
806        let plan: Vec<(u64, &str, Option<&str>, Option<u64>)> = plan_tasks(&tasks)
807            .iter()
808            .map(|i| (i.local_number, i.action, i.reason, i.vault_number))
809            .collect();
810        assert_eq!(
811            plan,
812            [
813                (1, "propose", None, None),
814                (2, "propose", None, None),
815                (3, "skip", Some("done"), None),
816                (4, "skip", Some("cancelled"), None),
817                (5, "skip", Some("rejected"), None),
818                (6, "skip", Some("failed"), None),
819                (7, "skip", Some("already_shared"), Some(12)),
820                (8, "skip", Some("no_acceptance"), None),
821                // Cloud would open it: it waits for acceptance here.
822                (9, "skip", Some("not_accepted"), None),
823                // Its claim, result and evidence stay where they are.
824                (10, "skip", Some("in_progress"), None),
825                (11, "skip", Some("in_progress"), None),
826            ]
827        );
828        let root = Path::new("/code/api");
829        let first = task_proposal(&tasks[0], "stable", root);
830        assert_eq!(first.goal.as_deref(), Some("Local task #1"));
831        assert_eq!(first.title, "Explain the retry budget");
832        let mut with_goal = tasks[1].clone();
833        with_goal.task.goal = Some("Write it down".into());
834        let second = task_proposal(&with_goal, "stable", root);
835        assert_eq!(
836            second.goal.as_deref(),
837            Some("Write it down\n\nLocal task #2")
838        );
839        assert_ne!(
840            first.idempotency_key(),
841            second.idempotency_key(),
842            "same title, two vault tasks"
843        );
844    }
845
846    /// A link interrupted between Cloud's answer and the local mark resumes
847    /// from the ledger: the next run only marks the task, it never sends it
848    /// again. An unanswered send is repeated with the same key while Cloud
849    /// replays it, and is never resent after that.
850    #[test]
851    fn an_interrupted_link_never_sends_a_task_twice() {
852        let tasks = [local_task(1, "open", Some("It works"), None)];
853        let proposal_of = |local: &LocalTask| task_proposal(local, "stable", Path::new("/r"));
854        let key = proposal_of(&tasks[0]).idempotency_key();
855        let mut ledger = Ledger::default();
856        let saved = std::cell::RefCell::new(Vec::<Ledger>::new());
857        let sent = std::cell::RefCell::new(Vec::<String>::new());
858
859        // Run 1: Cloud answers 41, then the run dies before the mark.
860        let mut items = plan_tasks(&tasks);
861        bring_tasks(
862            &mut items,
863            &tasks,
864            &proposal_of,
865            "vlt_api",
866            1_000,
867            &mut ledger,
868            &mut TaskSink {
869                propose: &mut |p| {
870                    sent.borrow_mut().push(p.idempotency_key());
871                    Ok(41)
872                },
873                mark: &mut |_, _| Err(lean_ctx_tasks::TaskError::Store("interrupted".into())),
874                save: &mut |l| {
875                    saved.borrow_mut().push(l.clone());
876                    Ok(())
877                },
878            },
879        );
880        assert_eq!(items[0].error.as_deref(), Some("interrupted"));
881        assert_eq!(sent.borrow().as_slice(), std::slice::from_ref(&key));
882        assert_eq!(
883            saved.borrow()[0].tasks[&1].vault_number,
884            None,
885            "recorded before it was sent"
886        );
887        assert_eq!(ledger.tasks[&1].vault_number, Some(41));
888
889        // Run 2: nothing is sent; the task is marked with Cloud's number.
890        let mut marked = Vec::new();
891        let mut items = plan_tasks(&tasks);
892        bring_tasks(
893            &mut items,
894            &tasks,
895            &proposal_of,
896            "vlt_api",
897            2_000,
898            &mut ledger,
899            &mut TaskSink {
900                propose: &mut |_| panic!("an answered task is never sent again"),
901                mark: &mut |n, number| {
902                    marked.push((n, number));
903                    Ok(())
904                },
905                save: &mut |_| Ok(()),
906            },
907        );
908        assert_eq!(marked, [(1, 41)]);
909        assert_eq!(
910            (items[0].vault_number, items[0].error.as_deref()),
911            (Some(41), None)
912        );
913        assert!(ledger.tasks.is_empty(), "the ledger lets it go once marked");
914
915        // A send Cloud never answered: repeated with the same key in the
916        // window, reported and not sent after it.
917        let unanswered = |sent_at| Ledger {
918            tasks: BTreeMap::from([(
919                1,
920                InFlight {
921                    vault_id: "vlt_api".into(),
922                    key: key.clone(),
923                    sent_at,
924                    vault_number: None,
925                },
926            )]),
927        };
928        let mut fresh = unanswered(1_000);
929        let mut items = plan_tasks(&tasks);
930        let resent = std::cell::RefCell::new(Vec::<String>::new());
931        bring_tasks(
932            &mut items,
933            &tasks,
934            &proposal_of,
935            "vlt_api",
936            1_000 + RESEND_WINDOW_SECS - 1,
937            &mut fresh,
938            &mut TaskSink {
939                propose: &mut |p| {
940                    resent.borrow_mut().push(p.idempotency_key());
941                    Ok(41)
942                },
943                mark: &mut |_, _| Ok(()),
944                save: &mut |_| Ok(()),
945            },
946        );
947        assert_eq!(
948            resent.borrow().as_slice(),
949            std::slice::from_ref(&key),
950            "the same key: LeanCTX Cloud replays"
951        );
952        assert_eq!(items[0].vault_number, Some(41));
953
954        let mut stale = unanswered(1_000);
955        let mut items = plan_tasks(&tasks);
956        bring_tasks(
957            &mut items,
958            &tasks,
959            &proposal_of,
960            "vlt_api",
961            1_000 + RESEND_WINDOW_SECS,
962            &mut stale,
963            &mut TaskSink {
964                propose: &mut |_| panic!("never resent after the window"),
965                mark: &mut |_, _| panic!("nothing to mark"),
966                save: &mut |_| Ok(()),
967            },
968        );
969        assert!(
970            items[0]
971                .error
972                .as_deref()
973                .is_some_and(|e| e.contains("Local task #1")),
974            "{:?}",
975            items[0].error
976        );
977        assert_eq!(
978            stale.tasks[&1].vault_number, None,
979            "kept for the person to check"
980        );
981    }
982
983    /// A ledger entry for another vault is not reused (a re-link sends the
984    /// task to the new vault); a refusal for good leaves no entry behind;
985    /// an earlier mark counts by its code.
986    #[test]
987    fn the_ledger_is_per_vault_and_forgets_refused_tasks() {
988        use lean_ctx_tasks::TaskError;
989        let tasks = [local_task(1, "open", Some("It works"), None)];
990        let proposal_of = |local: &LocalTask| task_proposal(local, "stable", Path::new("/r"));
991        let run = |ledger: &mut Ledger,
992                   propose: &mut dyn FnMut(&QueuedProposal) -> Result<u64, CloudError>,
993                   mark: &mut dyn FnMut(u64, u64) -> Result<(), TaskError>| {
994            let mut items = plan_tasks(&tasks);
995            bring_tasks(
996                &mut items,
997                &tasks,
998                &proposal_of,
999                "vlt_b",
1000                1_000,
1001                ledger,
1002                &mut TaskSink {
1003                    propose,
1004                    mark,
1005                    save: &mut |_| Ok(()),
1006                },
1007            );
1008            items.remove(0)
1009        };
1010        let in_a = || Ledger {
1011            tasks: BTreeMap::from([(
1012                1,
1013                InFlight {
1014                    vault_id: "vlt_a".into(),
1015                    key: "k".into(),
1016                    sent_at: 900,
1017                    vault_number: Some(41),
1018                },
1019            )]),
1020        };
1021
1022        let mut ledger = in_a();
1023        let item = run(&mut ledger, &mut |_| Ok(7), &mut |_, _| Ok(()));
1024        assert_eq!(item.vault_number, Some(7), "vault A's number is not reused");
1025
1026        let mut ledger = Ledger::default();
1027        let item = run(
1028            &mut ledger,
1029            &mut |_| {
1030                Err(CloudError::Refused(
1031                    "the goal was not sent: it contains a secret".into(),
1032                ))
1033            },
1034            &mut |_, _| panic!("nothing to mark"),
1035        );
1036        assert!(ledger.tasks.is_empty(), "nothing waits to be resumed");
1037        assert!(
1038            item.error
1039                .as_deref()
1040                .is_some_and(|e| e.contains("not created")),
1041            "{:?}",
1042            item.error
1043        );
1044
1045        let mut ledger = Ledger::default();
1046        let item = run(
1047            &mut ledger,
1048            &mut |_| Err(CloudError::Offline("down".into())),
1049            &mut |_, _| panic!("nothing to mark"),
1050        );
1051        assert!(
1052            ledger.tasks.contains_key(&1),
1053            "a lost answer is kept to resume"
1054        );
1055        assert!(item.error.is_some());
1056
1057        let mut ledger = Ledger::default();
1058        let item = run(&mut ledger, &mut |_| Ok(7), &mut |n, _| {
1059            Err(TaskError::InvalidState {
1060                number: n,
1061                reason: "already_shared",
1062            })
1063        });
1064        assert_eq!((item.vault_number, item.error), (Some(7), None));
1065    }
1066
1067    /// Proposed, claimed and submitted local tasks hold a link back until
1068    /// they are settled; once a proposal is accepted locally, the next link
1069    /// brings it.
1070    #[test]
1071    fn unsettled_local_tasks_hold_the_link_until_settled() {
1072        let fixtures = [
1073            local_task(1, "proposed", Some("It works"), None),
1074            local_task(2, "claimed", Some("It works"), None),
1075            local_task(3, "submitted", Some("It works"), None),
1076            local_task(4, "open", Some("It works"), None),
1077            local_task(5, "proposed", Some("It works"), Some(9)),
1078        ];
1079        let named: Vec<(u64, String)> = unsettled(&fixtures)
1080            .into_iter()
1081            .map(|u| (u.local_number, u.state))
1082            .collect();
1083        assert_eq!(
1084            named,
1085            [
1086                (1, "proposed".to_string()),
1087                (2, "claimed".to_string()),
1088                (3, "submitted".to_string()),
1089            ]
1090        );
1091        assert!(unsettled_message(&unsettled(&fixtures)).contains("#3 (submitted)"));
1092
1093        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1094        let project = tempfile::tempdir().unwrap();
1095        let root = project.path();
1096        let person = lean_ctx_tasks::Actor::person("person");
1097        crate::tasks::local::write(root, |board, now| {
1098            board.propose(
1099                &person,
1100                lean_ctx_tasks::Proposal {
1101                    title: "Explain the retry budget".into(),
1102                    goal: None,
1103                    acceptance: "It works".into(),
1104                    role: None,
1105                },
1106                now,
1107            )
1108        })
1109        .unwrap();
1110        let held = unsettled_local(root).unwrap();
1111        assert_eq!(
1112            held.iter().map(|u| u.local_number).collect::<Vec<_>>(),
1113            [1],
1114            "a link now is refused"
1115        );
1116        crate::tasks::local::write(root, |board, now| board.decide(1, &person, true, None, now))
1117            .unwrap();
1118        assert!(
1119            unsettled_local(root).unwrap().is_empty(),
1120            "the link may go now"
1121        );
1122        let plan = plan_tasks(&local_tasks(root).unwrap());
1123        assert_eq!(
1124            (plan[0].action, plan[0].reason),
1125            ("propose", None),
1126            "and brings it"
1127        );
1128    }
1129
1130    fn propose_local(root: &Path, title: &str) {
1131        let person = lean_ctx_tasks::Actor::person("person");
1132        crate::tasks::local::write(root, |board, now| {
1133            board.propose(
1134                &person,
1135                lean_ctx_tasks::Proposal {
1136                    title: title.into(),
1137                    goal: None,
1138                    acceptance: "It works".into(),
1139                    role: None,
1140                },
1141                now,
1142            )
1143        })
1144        .unwrap();
1145    }
1146
1147    /// Every link asks one gate; after a link that left tasks local (or a
1148    /// link file that came in through git) the tasks not brought stay
1149    /// listed as "local, not shared" and keep working with --local, while
1150    /// a brought one is acted on in the vault only.
1151    #[test]
1152    fn a_linked_project_keeps_its_local_not_shared_tasks_reachable() {
1153        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1154        let project = tempfile::tempdir().unwrap();
1155        let root = project.path();
1156        let person = lean_ctx_tasks::Actor::person("person");
1157        for title in ["Proposed only", "Accepted", "Brought"] {
1158            propose_local(root, title);
1159        }
1160        crate::tasks::local::write(root, |board, now| {
1161            board.decide(2, &person, true, None, now)?;
1162            board.decide(3, &person, true, None, now)?;
1163            board.mark_shared(3, &person, "platform/api", 41, now)
1164        })
1165        .unwrap();
1166
1167        let refused = link_gate(root, false).unwrap_err();
1168        assert!(
1169            refused.contains("#1 (proposed)") && refused.contains(LEAVE_UNSETTLED_FLAG),
1170            "{refused}"
1171        );
1172        let left = link_gate(root, true).unwrap();
1173        assert_eq!(left.iter().map(|u| u.local_number).collect::<Vec<_>>(), [1]);
1174
1175        let not_shared: Vec<(u64, String)> = local_not_shared(root)
1176            .unwrap()
1177            .into_iter()
1178            .map(|u| (u.local_number, u.state))
1179            .collect();
1180        assert_eq!(not_shared, [(1, "proposed".into()), (2, "open".into())]);
1181        assert!(
1182            not_shared_note(&local_not_shared(root).unwrap())
1183                .is_some_and(|n| n.contains("#1 (proposed), #2 (open)"))
1184        );
1185
1186        assert!(local_action_in_linked(root, "list", None).is_ok());
1187        assert!(local_action_in_linked(root, "decide", Some(1)).is_ok());
1188        assert!(local_action_in_linked(root, "claim", Some(2)).is_ok());
1189        let brought = local_action_in_linked(root, "claim", Some(3)).unwrap_err();
1190        assert!(brought.contains("platform/api as task #41"), "{brought}");
1191        assert!(local_action_in_linked(root, "propose", None).is_err());
1192        assert!(local_action_in_linked(root, "decide", Some(9)).is_err());
1193    }
1194}