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        signed: None,
286    }
287}
288
289fn local_tasks(root: &Path) -> Result<Vec<LocalTask>, CloudError> {
290    crate::tasks::local::list(root).map_err(CloudError::Local)
291}
292
293/// The plan for `root` from local state only (`--dry-run`, or before the
294/// vault is shared): pages the vault already holds show as `import` here.
295pub fn plan_local(root: &str) -> Result<Brought, CloudError> {
296    Ok(Brought {
297        tasks: plan_tasks(&local_tasks(Path::new(root))?),
298        docs: plan_docs(&local_docs::pages(root)?, &BTreeMap::new()),
299        docs_error: None,
300    })
301}
302
303/// Cloud replays a proposal's first answer for this long after it (its
304/// instance idempotency keys live 7 days); a ledger entry older than this
305/// is never sent again.
306pub const RESEND_WINDOW_SECS: i64 = 6 * 24 * 60 * 60;
307
308/// A task on its way into a vault, recorded before it is sent.
309#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]
310pub struct InFlight {
311    pub vault_id: String,
312    /// The proposal's idempotency key.
313    pub key: String,
314    /// Unix seconds when it was first sent.
315    pub sent_at: i64,
316    /// Cloud's number once it answered.
317    pub vault_number: Option<u64>,
318}
319
320/// The tasks of one project on their way into a vault, by local number.
321#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, serde::Deserialize)]
322pub struct Ledger {
323    pub tasks: BTreeMap<u64, InFlight>,
324}
325
326fn ledger_name(root: &Path) -> String {
327    format!(
328        "bring-local-{}.json",
329        lean_ctx::core::project_hash::hash_project_root(&root.to_string_lossy())
330    )
331}
332
333/// What [`bring_tasks`] calls on the outside world.
334pub struct TaskSink<'a> {
335    /// Send one proposal; Cloud's number for it.
336    pub propose: &'a mut dyn FnMut(&QueuedProposal) -> Result<u64, CloudError>,
337    /// Record local task `n` as brought as vault task `number`.
338    pub mark: &'a mut dyn FnMut(u64, u64) -> Result<(), lean_ctx_tasks::TaskError>,
339    /// Persist the ledger.
340    pub save: &'a mut dyn FnMut(&Ledger) -> Result<(), CloudError>,
341}
342
343/// Bring every `propose` item of `items` (planned from `tasks`, proposals
344/// from `proposal_of`) into the vault `vault_id`. Each task is entered in
345/// `ledger` before it is sent, gets its number there as soon as Cloud
346/// answers, and leaves it once it is marked shared. A task found in the
347/// ledger resumes from there: a known number is only marked, never sent
348/// again; an unanswered send is repeated with the same key inside
349/// [`RESEND_WINDOW_SECS`] (Cloud replays its first answer) and after that is
350/// reported, never resent, so an interrupted run never makes a second vault
351/// task.
352pub fn bring_tasks(
353    items: &mut [TaskItem],
354    tasks: &[LocalTask],
355    proposal_of: &dyn Fn(&LocalTask) -> QueuedProposal,
356    vault_id: &str,
357    now: i64,
358    ledger: &mut Ledger,
359    sink: &mut TaskSink<'_>,
360) {
361    for (item, local) in items.iter_mut().zip(tasks) {
362        if item.action != "propose" {
363            continue;
364        }
365        let n = item.local_number;
366        // An entry for another vault (a re-link) says nothing about this one.
367        let entry = ledger
368            .tasks
369            .get(&n)
370            .cloned()
371            .filter(|e| e.vault_id == vault_id);
372        let number = match entry {
373            Some(InFlight {
374                vault_number: Some(number),
375                ..
376            }) => Ok(number),
377            Some(sent) if now - sent.sent_at >= RESEND_WINDOW_SECS => Err(format!(
378                "an earlier link sent local task #{n} and was interrupted before the Cloud answered; it is not sent again (it may be in the vault already: look for \"Local task #{n}\")"
379            )),
380            earlier => {
381                let proposal = proposal_of(local);
382                ledger.tasks.insert(
383                    n,
384                    InFlight {
385                        vault_id: vault_id.to_owned(),
386                        key: proposal.idempotency_key(),
387                        sent_at: earlier.map_or(now, |e| e.sent_at),
388                        vault_number: None,
389                    },
390                );
391                match (sink.save)(ledger).and_then(|()| (sink.propose)(&proposal)) {
392                    Ok(number) => {
393                        if let Some(entry) = ledger.tasks.get_mut(&n) {
394                            entry.vault_number = Some(number);
395                        }
396                        (sink.save)(ledger)
397                            .map(|()| number)
398                            .map_err(|e| e.to_string())
399                    }
400                    Err(e) if refused_for_good(&e) => {
401                        // Cloud (or the screen before it) said no: no vault
402                        // task exists, so nothing waits to be resumed.
403                        ledger.tasks.remove(&n);
404                        let _ = (sink.save)(ledger);
405                        Err(format!(
406                            "local task #{n} was refused and not created ({e}); change it locally and link again"
407                        ))
408                    }
409                    Err(e) => Err(format!(
410                        "local task #{n} did not get the Cloud's answer ({e}); the next link resumes it"
411                    )),
412                }
413            }
414        };
415        let marked = number.and_then(|number| match (sink.mark)(n, number) {
416            Ok(()) => Ok(number),
417            // Marked by the interrupted run already.
418            Err(e) if e.reason() == Some("already_shared") => Ok(number),
419            Err(e) => Err(e.to_string()),
420        });
421        match marked {
422            Ok(number) => {
423                item.vault_number = Some(number);
424                ledger.tasks.remove(&n);
425                if let Err(e) = (sink.save)(ledger) {
426                    item.error = Some(e.to_string());
427                }
428            }
429            Err(e) => item.error = Some(e),
430        }
431    }
432}
433
434/// A refusal after which no vault task exists and none will: the screen
435/// or the request check refused it, or Cloud answered with a 4xx. A lost
436/// connection, a 5xx or an unreadable answer may hide a created task.
437pub fn refused_for_good(error: &CloudError) -> bool {
438    match error {
439        CloudError::Refused(_)
440        | CloudError::Forbidden
441        | CloudError::NotFound
442        | CloudError::Vetoed
443        | CloudError::ScreeningBlocked
444        | CloudError::PolicyDenied(_)
445        | CloudError::PlanRequired(_)
446        | CloudError::Task { .. } => true,
447        CloudError::Server { status, .. } => (400..500).contains(status),
448        _ => false,
449    }
450}
451
452/// A local task the link would strand: only proposed, claimed or submitted
453/// (and not brought yet). Once a project is linked its tasks are Cloud's, so
454/// these are settled locally first.
455#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
456pub struct Unsettled {
457    pub local_number: u64,
458    pub title: Option<String>,
459    pub state: String,
460}
461
462/// The unsettled tasks among `tasks`.
463pub fn unsettled(tasks: &[LocalTask]) -> Vec<Unsettled> {
464    tasks
465        .iter()
466        .filter(|t| {
467            t.shared.is_none()
468                && matches!(
469                    t.task.state,
470                    TaskState::Proposed | TaskState::Claimed | TaskState::Submitted
471                )
472        })
473        .map(|t| Unsettled {
474            local_number: t.task.number,
475            title: t.task.title.clone(),
476            state: state_name(t.task.state),
477        })
478        .collect()
479}
480
481/// The unsettled local tasks of `root`.
482pub fn unsettled_local(root: &Path) -> Result<Vec<Unsettled>, CloudError> {
483    Ok(unsettled(&local_tasks(root)?))
484}
485
486/// Why a link that brings local work is refused while `list` is unsettled.
487pub fn unsettled_message(list: &[Unsettled]) -> String {
488    let named: Vec<String> = list
489        .iter()
490        .map(|u| format!("#{} ({})", u.local_number, u.state))
491        .collect();
492    format!(
493        "local tasks {} are not settled: once the project is linked its tasks are the 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",
494        named.join(", ")
495    )
496}
497
498/// The flag that links a project although local tasks are unsettled; they
499/// then stay local and are reached with `lean-ctx tasks … --local`.
500pub const LEAVE_UNSETTLED_FLAG: &str = "--leave-unsettled-local";
501
502/// Every path that links a project asks this first: the unsettled local
503/// tasks of `root`, or why the link is refused (`leave` is the person's
504/// explicit [`LEAVE_UNSETTLED_FLAG`]).
505pub fn link_gate(root: &Path, leave: bool) -> Result<Vec<Unsettled>, String> {
506    let list = unsettled_local(root).map_err(|e| e.to_string())?;
507    if list.is_empty() || leave {
508        return Ok(list);
509    }
510    Err(format!(
511        "{} (or link with {LEAVE_UNSETTLED_FLAG}: they stay local, reached with `lean-ctx tasks … --local`)",
512        unsettled_message(&list)
513    ))
514}
515
516/// The local tasks of `root` that are neither brought into a vault nor
517/// closed: in a linked project they are "local, not shared" and stay
518/// reachable with `--local` (also when the link came in through git).
519pub fn local_not_shared(root: &Path) -> Result<Vec<Unsettled>, CloudError> {
520    Ok(local_tasks(root)?
521        .iter()
522        .filter(|t| {
523            t.shared.is_none()
524                && matches!(
525                    t.task.state,
526                    TaskState::Proposed
527                        | TaskState::Open
528                        | TaskState::Claimed
529                        | TaskState::Submitted
530                )
531        })
532        .map(|t| Unsettled {
533            local_number: t.task.number,
534            title: t.task.title.clone(),
535            state: state_name(t.task.state),
536        })
537        .collect())
538}
539
540/// One line naming `list` for a linked project's task list; `None` when
541/// there are none.
542pub fn not_shared_note(list: &[Unsettled]) -> Option<String> {
543    if list.is_empty() {
544        return None;
545    }
546    let named: Vec<String> = list
547        .iter()
548        .map(|u| format!("#{} ({})", u.local_number, u.state))
549        .collect();
550    Some(format!(
551        "local, not shared: {} (act on them with `lean-ctx tasks … --local`)",
552        named.join(", ")
553    ))
554}
555
556/// Whether `action` (on local task `number`, when it names one) may act on
557/// the local store of the linked project `root`: reads always; a write only
558/// on a task that was not brought into a vault; new tasks go to Cloud.
559pub fn local_action_in_linked(
560    root: &Path,
561    action: &str,
562    number: Option<u64>,
563) -> Result<(), String> {
564    match action {
565        "list" | "show" => return Ok(()),
566        "propose" => {
567            return Err(
568                "new tasks of a linked project go to the Cloud (drop --local: `lean-ctx tasks propose`)"
569                    .into(),
570            );
571        }
572        _ => {}
573    }
574    let Some(n) = number else {
575        return Ok(());
576    };
577    let tasks = local_tasks(root).map_err(|e| e.to_string())?;
578    match tasks.iter().find(|t| t.task.number == n) {
579        None => Err(format!("this project has no local task #{n}")),
580        Some(t) => match &t.shared {
581            Some(shared) => Err(format!(
582                "local task #{n} was brought into {} as task #{}: act on it there (without --local)",
583                shared.vault, shared.number
584            )),
585            None => Ok(()),
586        },
587    }
588}
589
590/// Bring every open local task of `root` into the vault `vault_id`
591/// (`vault` = `ns/name`): [`bring_tasks`] against Cloud, the local task
592/// store and the ledger in this Instance's config.
593pub fn import_tasks(root: &Path, vault: &str, vault_id: &str) -> Result<Vec<TaskItem>, CloudError> {
594    let tasks = local_tasks(root)?;
595    let mut items = plan_tasks(&tasks);
596    if !items.iter().any(|i| i.action == "propose") {
597        return Ok(items);
598    }
599    let identity = crate::vault::project_identity(root).ok_or_else(|| {
600        CloudError::Config("this repository has no identity the Cloud can link to a vault".into())
601    })?;
602    let stable = lean_ctx_protocol::cloud::vault::stable_identity(&identity);
603    let store = crate::CloudStore::open()?;
604    let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
605    let config = lean_ctx::core::config::Config::load().cloud.clone();
606    let trust = crate::root_cert::trust_root(&store, &config, &instance.url)?;
607    let session = crate::auth::Session::load(store.clone(), trust)?;
608    let name = ledger_name(root);
609    let mut ledger: Ledger = store.read_config(&name)?.unwrap_or_default();
610    bring_tasks(
611        &mut items,
612        &tasks,
613        &|local| task_proposal(local, &stable, root),
614        vault_id,
615        lean_ctx_time::UtcDateTime::now().timestamp(),
616        &mut ledger,
617        &mut TaskSink {
618            propose: &mut |proposal| {
619                crate::tasks::propose::propose_now(&session, vault_id, proposal).map(|(n, _)| n)
620            },
621            mark: &mut |local, number| {
622                crate::tasks::local::write(root, |board, now| {
623                    board.mark_shared(
624                        local,
625                        &lean_ctx_tasks::Actor::person("person"),
626                        vault,
627                        number,
628                        now,
629                    )
630                })
631                .map(|_| ())
632            },
633            save: &mut |ledger| {
634                if ledger.tasks.is_empty() {
635                    store.remove_config(&name)
636                } else {
637                    store.write_config(&name, ledger)
638                }
639            },
640        },
641    );
642    Ok(items)
643}
644
645/// Bring the local tasks, then the local pages, of `root` into its linked
646/// vault (`vault` = `ns/name`, id `vault_id`). Pages need the vault's
647/// replica here; when they cannot go, the tasks that went stay reported as
648/// gone and `docs_error` says why the pages wait (`docs` is the plan then).
649pub fn import(root: &str, vault: &str, vault_id: &str) -> Result<Brought, CloudError> {
650    let tasks = import_tasks(Path::new(root), vault, vault_id)?;
651    Ok(match import_docs(root, vault) {
652        Ok(docs) => Brought {
653            tasks,
654            docs,
655            docs_error: None,
656        },
657        Err(e) => {
658            let (docs, error) = match local_docs::pages(root) {
659                Ok(pages) => (plan_docs(&pages, &BTreeMap::new()), e.to_string()),
660                Err(read) => (
661                    Vec::new(),
662                    format!("{e}; the local pages cannot be read: {read}"),
663                ),
664            };
665            Brought {
666                tasks,
667                docs,
668                docs_error: Some(error),
669            }
670        }
671    })
672}
673
674#[cfg(test)]
675mod tests {
676    use super::*;
677    use crate::local_docs::SharedTo;
678
679    fn local(id: &str, slug: &str, shared: bool) -> LocalPage {
680        LocalPage {
681            id: id.into(),
682            slug: slug.into(),
683            title: slug.into(),
684            body: String::new(),
685            kind: "reference".into(),
686            status: "draft".into(),
687            updated: None,
688            updated_by: None,
689            shared: shared.then(|| SharedTo {
690                vault: "platform/api".into(),
691                page_id: "n_old".into(),
692                at: "2026-11-04T10:00:00Z".into(),
693            }),
694        }
695    }
696
697    fn raw(slug: &str, text: &str) -> Page {
698        serde_json::from_value(serde_json::json!({
699            "slug": slug, "title": slug, "kind": "reference", "status": "draft",
700            "sections": [{"order": 0, "text": text}],
701        }))
702        .unwrap()
703    }
704
705    /// Each page is brought once: shared ones and slugs the vault holds are
706    /// skipped, and links between brought pages follow their new ids while
707    /// links to a vault page keep pointing at it.
708    #[test]
709    fn local_pages_come_once_with_their_links_pointing_into_the_vault() {
710        let pages = [
711            local("n_la", "guide", false),
712            local("n_lb", "setup", false),
713            local("n_lc", "old", true),
714            local("n_ld", "faq", false),
715        ];
716        let vault = BTreeMap::from([("faq".to_string(), "n_vfaq".to_string())]);
717        let mut items = plan_docs(&pages, &vault);
718        let plan: Vec<(&str, &str, Option<&str>)> = items
719            .iter()
720            .map(|i| (i.slug.as_str(), i.action, i.reason))
721            .collect();
722        assert_eq!(
723            plan,
724            [
725                ("guide", "import", None),
726                ("setup", "import", None),
727                ("old", "skip", Some("already_shared")),
728                ("faq", "skip", Some("exists_in_vault")),
729            ]
730        );
731        let raws = [
732            raw("guide", "See [setup](cloud:n_lb) and [faq](cloud:n_ld)."),
733            raw("setup", "Back to [guide](cloud:n_la)."),
734        ];
735        let mut n = 0;
736        let mut new_id = |prefix: &str| {
737            n += 1;
738            format!("{prefix}_new{n}")
739        };
740        let specs = doc_events(&mut items, &raws, &vault, &mut new_id);
741        assert_eq!(items[0].vault_page_id.as_deref(), Some("n_new1"));
742        assert_eq!(items[1].vault_page_id.as_deref(), Some("n_new2"));
743        assert_eq!(items[2].vault_page_id.as_deref(), Some("n_old"));
744        let text =
745            serde_json::to_string(&specs.iter().map(|s| &s.body).collect::<Vec<_>>()).unwrap();
746        assert!(
747            text.contains("cloud:n_new2") && text.contains("cloud:n_vfaq"),
748            "{text}"
749        );
750        assert!(text.contains("cloud:n_new1"), "{text}");
751        assert!(
752            !text.contains("n_la") && !text.contains("n_lb"),
753            "no local ids reach the vault: {text}"
754        );
755        assert!(
756            specs.iter().any(|s| s.target == "n_new1")
757                && specs.iter().any(|s| s.target == "n_new2")
758        );
759    }
760
761    fn local_task(
762        number: u64,
763        state: &str,
764        acceptance: Option<&str>,
765        shared: Option<u64>,
766    ) -> LocalTask {
767        let path = concat!(
768            env!("CARGO_MANIFEST_DIR"),
769            "/../lean-ctx-protocol/tests/fixtures/cloud/task.claimed.response.json"
770        );
771        let mut task: serde_json::Value =
772            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
773        task["number"] = number.into();
774        task["state"] = state.into();
775        task["claim"] = serde_json::Value::Null;
776        task["acceptance"] = acceptance.map_or(serde_json::Value::Null, Into::into);
777        serde_json::from_value(serde_json::json!({
778            "task": task,
779            "transitions": [],
780            "shared": shared.map(|n| serde_json::json!({
781                "vault": "platform/api", "number": n, "at": "2026-11-04T10:00:00Z"
782            })),
783        }))
784        .unwrap()
785    }
786
787    /// Open local tasks are proposed once each, with the local number kept
788    /// in the goal and in the proposal key; proposed, in-progress, finished,
789    /// shared and incomplete ones are skipped.
790    #[test]
791    fn live_local_tasks_are_proposed_once_with_their_local_number() {
792        let tasks = vec![
793            local_task(1, "open", Some("It works"), None),
794            local_task(2, "open", Some("It works"), None),
795            local_task(3, "done", Some("It works"), None),
796            local_task(4, "cancelled", Some("It works"), None),
797            local_task(5, "rejected", Some("It works"), None),
798            local_task(6, "failed", Some("It works"), None),
799            local_task(7, "open", Some("It works"), Some(12)),
800            local_task(8, "open", None, None),
801            local_task(9, "proposed", Some("It works"), None),
802            local_task(10, "claimed", Some("It works"), None),
803            local_task(11, "submitted", Some("It works"), None),
804        ];
805        let plan: Vec<(u64, &str, Option<&str>, Option<u64>)> = plan_tasks(&tasks)
806            .iter()
807            .map(|i| (i.local_number, i.action, i.reason, i.vault_number))
808            .collect();
809        assert_eq!(
810            plan,
811            [
812                (1, "propose", None, None),
813                (2, "propose", None, None),
814                (3, "skip", Some("done"), None),
815                (4, "skip", Some("cancelled"), None),
816                (5, "skip", Some("rejected"), None),
817                (6, "skip", Some("failed"), None),
818                (7, "skip", Some("already_shared"), Some(12)),
819                (8, "skip", Some("no_acceptance"), None),
820                // Cloud would open it: it waits for acceptance here.
821                (9, "skip", Some("not_accepted"), None),
822                // Its claim, result and evidence stay where they are.
823                (10, "skip", Some("in_progress"), None),
824                (11, "skip", Some("in_progress"), None),
825            ]
826        );
827        let root = Path::new("/code/api");
828        let first = task_proposal(&tasks[0], "stable", root);
829        assert_eq!(first.goal.as_deref(), Some("Local task #1"));
830        assert_eq!(first.title, "Explain the retry budget");
831        let mut with_goal = tasks[1].clone();
832        with_goal.task.goal = Some("Write it down".into());
833        let second = task_proposal(&with_goal, "stable", root);
834        assert_eq!(
835            second.goal.as_deref(),
836            Some("Write it down\n\nLocal task #2")
837        );
838        assert_ne!(
839            first.idempotency_key(),
840            second.idempotency_key(),
841            "same title, two vault tasks"
842        );
843    }
844
845    /// A link interrupted between Cloud's answer and the local mark resumes
846    /// from the ledger: the next run only marks the task, it never sends it
847    /// again. An unanswered send is repeated with the same key while Cloud
848    /// replays it, and is never resent after that.
849    #[test]
850    fn an_interrupted_link_never_sends_a_task_twice() {
851        let tasks = [local_task(1, "open", Some("It works"), None)];
852        let proposal_of = |local: &LocalTask| task_proposal(local, "stable", Path::new("/r"));
853        let key = proposal_of(&tasks[0]).idempotency_key();
854        let mut ledger = Ledger::default();
855        let saved = std::cell::RefCell::new(Vec::<Ledger>::new());
856        let sent = std::cell::RefCell::new(Vec::<String>::new());
857
858        // Run 1: Cloud answers 41, then the run dies before the mark.
859        let mut items = plan_tasks(&tasks);
860        bring_tasks(
861            &mut items,
862            &tasks,
863            &proposal_of,
864            "vlt_api",
865            1_000,
866            &mut ledger,
867            &mut TaskSink {
868                propose: &mut |p| {
869                    sent.borrow_mut().push(p.idempotency_key());
870                    Ok(41)
871                },
872                mark: &mut |_, _| Err(lean_ctx_tasks::TaskError::Store("interrupted".into())),
873                save: &mut |l| {
874                    saved.borrow_mut().push(l.clone());
875                    Ok(())
876                },
877            },
878        );
879        assert_eq!(items[0].error.as_deref(), Some("interrupted"));
880        assert_eq!(sent.borrow().as_slice(), std::slice::from_ref(&key));
881        assert_eq!(
882            saved.borrow()[0].tasks[&1].vault_number,
883            None,
884            "recorded before it was sent"
885        );
886        assert_eq!(ledger.tasks[&1].vault_number, Some(41));
887
888        // Run 2: nothing is sent; the task is marked with Cloud's number.
889        let mut marked = Vec::new();
890        let mut items = plan_tasks(&tasks);
891        bring_tasks(
892            &mut items,
893            &tasks,
894            &proposal_of,
895            "vlt_api",
896            2_000,
897            &mut ledger,
898            &mut TaskSink {
899                propose: &mut |_| panic!("an answered task is never sent again"),
900                mark: &mut |n, number| {
901                    marked.push((n, number));
902                    Ok(())
903                },
904                save: &mut |_| Ok(()),
905            },
906        );
907        assert_eq!(marked, [(1, 41)]);
908        assert_eq!(
909            (items[0].vault_number, items[0].error.as_deref()),
910            (Some(41), None)
911        );
912        assert!(ledger.tasks.is_empty(), "the ledger lets it go once marked");
913
914        // A send Cloud never answered: repeated with the same key in the
915        // window, reported and not sent after it.
916        let unanswered = |sent_at| Ledger {
917            tasks: BTreeMap::from([(
918                1,
919                InFlight {
920                    vault_id: "vlt_api".into(),
921                    key: key.clone(),
922                    sent_at,
923                    vault_number: None,
924                },
925            )]),
926        };
927        let mut fresh = unanswered(1_000);
928        let mut items = plan_tasks(&tasks);
929        let resent = std::cell::RefCell::new(Vec::<String>::new());
930        bring_tasks(
931            &mut items,
932            &tasks,
933            &proposal_of,
934            "vlt_api",
935            1_000 + RESEND_WINDOW_SECS - 1,
936            &mut fresh,
937            &mut TaskSink {
938                propose: &mut |p| {
939                    resent.borrow_mut().push(p.idempotency_key());
940                    Ok(41)
941                },
942                mark: &mut |_, _| Ok(()),
943                save: &mut |_| Ok(()),
944            },
945        );
946        assert_eq!(
947            resent.borrow().as_slice(),
948            std::slice::from_ref(&key),
949            "the same key: the Cloud replays"
950        );
951        assert_eq!(items[0].vault_number, Some(41));
952
953        let mut stale = unanswered(1_000);
954        let mut items = plan_tasks(&tasks);
955        bring_tasks(
956            &mut items,
957            &tasks,
958            &proposal_of,
959            "vlt_api",
960            1_000 + RESEND_WINDOW_SECS,
961            &mut stale,
962            &mut TaskSink {
963                propose: &mut |_| panic!("never resent after the window"),
964                mark: &mut |_, _| panic!("nothing to mark"),
965                save: &mut |_| Ok(()),
966            },
967        );
968        assert!(
969            items[0]
970                .error
971                .as_deref()
972                .is_some_and(|e| e.contains("Local task #1")),
973            "{:?}",
974            items[0].error
975        );
976        assert_eq!(
977            stale.tasks[&1].vault_number, None,
978            "kept for the person to check"
979        );
980    }
981
982    /// A ledger entry for another vault is not reused (a re-link sends the
983    /// task to the new vault); a refusal for good leaves no entry behind;
984    /// an earlier mark counts by its code.
985    #[test]
986    fn the_ledger_is_per_vault_and_forgets_refused_tasks() {
987        use lean_ctx_tasks::TaskError;
988        let tasks = [local_task(1, "open", Some("It works"), None)];
989        let proposal_of = |local: &LocalTask| task_proposal(local, "stable", Path::new("/r"));
990        let run = |ledger: &mut Ledger,
991                   propose: &mut dyn FnMut(&QueuedProposal) -> Result<u64, CloudError>,
992                   mark: &mut dyn FnMut(u64, u64) -> Result<(), TaskError>| {
993            let mut items = plan_tasks(&tasks);
994            bring_tasks(
995                &mut items,
996                &tasks,
997                &proposal_of,
998                "vlt_b",
999                1_000,
1000                ledger,
1001                &mut TaskSink {
1002                    propose,
1003                    mark,
1004                    save: &mut |_| Ok(()),
1005                },
1006            );
1007            items.remove(0)
1008        };
1009        let in_a = || Ledger {
1010            tasks: BTreeMap::from([(
1011                1,
1012                InFlight {
1013                    vault_id: "vlt_a".into(),
1014                    key: "k".into(),
1015                    sent_at: 900,
1016                    vault_number: Some(41),
1017                },
1018            )]),
1019        };
1020
1021        let mut ledger = in_a();
1022        let item = run(&mut ledger, &mut |_| Ok(7), &mut |_, _| Ok(()));
1023        assert_eq!(item.vault_number, Some(7), "vault A's number is not reused");
1024
1025        let mut ledger = Ledger::default();
1026        let item = run(
1027            &mut ledger,
1028            &mut |_| {
1029                Err(CloudError::Refused(
1030                    "the goal was not sent: it contains a secret".into(),
1031                ))
1032            },
1033            &mut |_, _| panic!("nothing to mark"),
1034        );
1035        assert!(ledger.tasks.is_empty(), "nothing waits to be resumed");
1036        assert!(
1037            item.error
1038                .as_deref()
1039                .is_some_and(|e| e.contains("not created")),
1040            "{:?}",
1041            item.error
1042        );
1043
1044        let mut ledger = Ledger::default();
1045        let item = run(
1046            &mut ledger,
1047            &mut |_| Err(CloudError::Offline("down".into())),
1048            &mut |_, _| panic!("nothing to mark"),
1049        );
1050        assert!(
1051            ledger.tasks.contains_key(&1),
1052            "a lost answer is kept to resume"
1053        );
1054        assert!(item.error.is_some());
1055
1056        let mut ledger = Ledger::default();
1057        let item = run(&mut ledger, &mut |_| Ok(7), &mut |n, _| {
1058            Err(TaskError::InvalidState {
1059                number: n,
1060                reason: "already_shared",
1061            })
1062        });
1063        assert_eq!((item.vault_number, item.error), (Some(7), None));
1064    }
1065
1066    /// Proposed, claimed and submitted local tasks hold a link back until
1067    /// they are settled; once a proposal is accepted locally, the next link
1068    /// brings it.
1069    #[test]
1070    fn unsettled_local_tasks_hold_the_link_until_settled() {
1071        let fixtures = [
1072            local_task(1, "proposed", Some("It works"), None),
1073            local_task(2, "claimed", Some("It works"), None),
1074            local_task(3, "submitted", Some("It works"), None),
1075            local_task(4, "open", Some("It works"), None),
1076            local_task(5, "proposed", Some("It works"), Some(9)),
1077        ];
1078        let named: Vec<(u64, String)> = unsettled(&fixtures)
1079            .into_iter()
1080            .map(|u| (u.local_number, u.state))
1081            .collect();
1082        assert_eq!(
1083            named,
1084            [
1085                (1, "proposed".to_string()),
1086                (2, "claimed".to_string()),
1087                (3, "submitted".to_string()),
1088            ]
1089        );
1090        assert!(unsettled_message(&unsettled(&fixtures)).contains("#3 (submitted)"));
1091
1092        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1093        let project = tempfile::tempdir().unwrap();
1094        let root = project.path();
1095        let person = lean_ctx_tasks::Actor::person("person");
1096        crate::tasks::local::write(root, |board, now| {
1097            board.propose(
1098                &person,
1099                lean_ctx_tasks::Proposal {
1100                    title: "Explain the retry budget".into(),
1101                    goal: None,
1102                    acceptance: "It works".into(),
1103                    role: None,
1104                },
1105                now,
1106            )
1107        })
1108        .unwrap();
1109        let held = unsettled_local(root).unwrap();
1110        assert_eq!(
1111            held.iter().map(|u| u.local_number).collect::<Vec<_>>(),
1112            [1],
1113            "a link now is refused"
1114        );
1115        crate::tasks::local::write(root, |board, now| board.decide(1, &person, true, None, now))
1116            .unwrap();
1117        assert!(
1118            unsettled_local(root).unwrap().is_empty(),
1119            "the link may go now"
1120        );
1121        let plan = plan_tasks(&local_tasks(root).unwrap());
1122        assert_eq!(
1123            (plan[0].action, plan[0].reason),
1124            ("propose", None),
1125            "and brings it"
1126        );
1127    }
1128
1129    fn propose_local(root: &Path, title: &str) {
1130        let person = lean_ctx_tasks::Actor::person("person");
1131        crate::tasks::local::write(root, |board, now| {
1132            board.propose(
1133                &person,
1134                lean_ctx_tasks::Proposal {
1135                    title: title.into(),
1136                    goal: None,
1137                    acceptance: "It works".into(),
1138                    role: None,
1139                },
1140                now,
1141            )
1142        })
1143        .unwrap();
1144    }
1145
1146    /// Every link asks one gate; after a link that left tasks local (or a
1147    /// link file that came in through git) the tasks not brought stay
1148    /// listed as "local, not shared" and keep working with --local, while
1149    /// a brought one is acted on in the vault only.
1150    #[test]
1151    fn a_linked_project_keeps_its_local_not_shared_tasks_reachable() {
1152        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1153        let project = tempfile::tempdir().unwrap();
1154        let root = project.path();
1155        let person = lean_ctx_tasks::Actor::person("person");
1156        for title in ["Proposed only", "Accepted", "Brought"] {
1157            propose_local(root, title);
1158        }
1159        crate::tasks::local::write(root, |board, now| {
1160            board.decide(2, &person, true, None, now)?;
1161            board.decide(3, &person, true, None, now)?;
1162            board.mark_shared(3, &person, "platform/api", 41, now)
1163        })
1164        .unwrap();
1165
1166        let refused = link_gate(root, false).unwrap_err();
1167        assert!(
1168            refused.contains("#1 (proposed)") && refused.contains(LEAVE_UNSETTLED_FLAG),
1169            "{refused}"
1170        );
1171        let left = link_gate(root, true).unwrap();
1172        assert_eq!(left.iter().map(|u| u.local_number).collect::<Vec<_>>(), [1]);
1173
1174        let not_shared: Vec<(u64, String)> = local_not_shared(root)
1175            .unwrap()
1176            .into_iter()
1177            .map(|u| (u.local_number, u.state))
1178            .collect();
1179        assert_eq!(not_shared, [(1, "proposed".into()), (2, "open".into())]);
1180        assert!(
1181            not_shared_note(&local_not_shared(root).unwrap())
1182                .is_some_and(|n| n.contains("#1 (proposed), #2 (open)"))
1183        );
1184
1185        assert!(local_action_in_linked(root, "list", None).is_ok());
1186        assert!(local_action_in_linked(root, "decide", Some(1)).is_ok());
1187        assert!(local_action_in_linked(root, "claim", Some(2)).is_ok());
1188        let brought = local_action_in_linked(root, "claim", Some(3)).unwrap_err();
1189        assert!(brought.contains("platform/api as task #41"), "{brought}");
1190        assert!(local_action_in_linked(root, "propose", None).is_err());
1191        assert!(local_action_in_linked(root, "decide", Some(9)).is_err());
1192    }
1193}