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 LeanCTX 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 LeanCTX 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 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",
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 LeanCTX 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(
601            "this repository has no identity LeanCTX Cloud can link to a vault".into(),
602        )
603    })?;
604    let stable = lean_ctx_protocol::cloud::vault::stable_identity(&identity);
605    let store = crate::CloudStore::open()?;
606    let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
607    let config = lean_ctx::core::config::Config::load().cloud.clone();
608    let trust = crate::root_cert::trust_root(&store, &config, &instance.url)?;
609    let session = crate::auth::Session::load(store.clone(), trust)?;
610    let name = ledger_name(root);
611    let mut ledger: Ledger = store.read_config(&name)?.unwrap_or_default();
612    bring_tasks(
613        &mut items,
614        &tasks,
615        &|local| task_proposal(local, &stable, root),
616        vault_id,
617        lean_ctx_time::UtcDateTime::now().timestamp(),
618        &mut ledger,
619        &mut TaskSink {
620            propose: &mut |proposal| {
621                crate::tasks::propose::propose_now(&session, vault_id, proposal).map(|(n, _)| n)
622            },
623            mark: &mut |local, number| {
624                crate::tasks::local::write(root, |board, now| {
625                    board.mark_shared(
626                        local,
627                        &lean_ctx_tasks::Actor::person("person"),
628                        vault,
629                        number,
630                        now,
631                    )
632                })
633                .map(|_| ())
634            },
635            save: &mut |ledger| {
636                if ledger.tasks.is_empty() {
637                    store.remove_config(&name)
638                } else {
639                    store.write_config(&name, ledger)
640                }
641            },
642        },
643    );
644    Ok(items)
645}
646
647/// Bring the local tasks, then the local pages, of `root` into its linked
648/// vault (`vault` = `ns/name`, id `vault_id`). Pages need the vault's
649/// replica here; when they cannot go, the tasks that went stay reported as
650/// gone and `docs_error` says why the pages wait (`docs` is the plan then).
651pub fn import(root: &str, vault: &str, vault_id: &str) -> Result<Brought, CloudError> {
652    let tasks = import_tasks(Path::new(root), vault, vault_id)?;
653    Ok(match import_docs(root, vault) {
654        Ok(docs) => Brought {
655            tasks,
656            docs,
657            docs_error: None,
658        },
659        Err(e) => {
660            let (docs, error) = match local_docs::pages(root) {
661                Ok(pages) => (plan_docs(&pages, &BTreeMap::new()), e.to_string()),
662                Err(read) => (
663                    Vec::new(),
664                    format!("{e}; the local pages cannot be read: {read}"),
665                ),
666            };
667            Brought {
668                tasks,
669                docs,
670                docs_error: Some(error),
671            }
672        }
673    })
674}
675
676#[cfg(test)]
677mod tests {
678    use super::*;
679    use crate::local_docs::SharedTo;
680
681    fn local(id: &str, slug: &str, shared: bool) -> LocalPage {
682        LocalPage {
683            id: id.into(),
684            slug: slug.into(),
685            title: slug.into(),
686            body: String::new(),
687            kind: "reference".into(),
688            status: "draft".into(),
689            updated: None,
690            updated_by: None,
691            shared: shared.then(|| SharedTo {
692                vault: "platform/api".into(),
693                page_id: "n_old".into(),
694                at: "2026-11-04T10:00:00Z".into(),
695            }),
696        }
697    }
698
699    fn raw(slug: &str, text: &str) -> Page {
700        serde_json::from_value(serde_json::json!({
701            "slug": slug, "title": slug, "kind": "reference", "status": "draft",
702            "sections": [{"order": 0, "text": text}],
703        }))
704        .unwrap()
705    }
706
707    /// Each page is brought once: shared ones and slugs the vault holds are
708    /// skipped, and links between brought pages follow their new ids while
709    /// links to a vault page keep pointing at it.
710    #[test]
711    fn local_pages_come_once_with_their_links_pointing_into_the_vault() {
712        let pages = [
713            local("n_la", "guide", false),
714            local("n_lb", "setup", false),
715            local("n_lc", "old", true),
716            local("n_ld", "faq", false),
717        ];
718        let vault = BTreeMap::from([("faq".to_string(), "n_vfaq".to_string())]);
719        let mut items = plan_docs(&pages, &vault);
720        let plan: Vec<(&str, &str, Option<&str>)> = items
721            .iter()
722            .map(|i| (i.slug.as_str(), i.action, i.reason))
723            .collect();
724        assert_eq!(
725            plan,
726            [
727                ("guide", "import", None),
728                ("setup", "import", None),
729                ("old", "skip", Some("already_shared")),
730                ("faq", "skip", Some("exists_in_vault")),
731            ]
732        );
733        let raws = [
734            raw("guide", "See [setup](cloud:n_lb) and [faq](cloud:n_ld)."),
735            raw("setup", "Back to [guide](cloud:n_la)."),
736        ];
737        let mut n = 0;
738        let mut new_id = |prefix: &str| {
739            n += 1;
740            format!("{prefix}_new{n}")
741        };
742        let specs = doc_events(&mut items, &raws, &vault, &mut new_id);
743        assert_eq!(items[0].vault_page_id.as_deref(), Some("n_new1"));
744        assert_eq!(items[1].vault_page_id.as_deref(), Some("n_new2"));
745        assert_eq!(items[2].vault_page_id.as_deref(), Some("n_old"));
746        let text =
747            serde_json::to_string(&specs.iter().map(|s| &s.body).collect::<Vec<_>>()).unwrap();
748        assert!(
749            text.contains("cloud:n_new2") && text.contains("cloud:n_vfaq"),
750            "{text}"
751        );
752        assert!(text.contains("cloud:n_new1"), "{text}");
753        assert!(
754            !text.contains("n_la") && !text.contains("n_lb"),
755            "no local ids reach the vault: {text}"
756        );
757        assert!(
758            specs.iter().any(|s| s.target == "n_new1")
759                && specs.iter().any(|s| s.target == "n_new2")
760        );
761    }
762
763    fn local_task(
764        number: u64,
765        state: &str,
766        acceptance: Option<&str>,
767        shared: Option<u64>,
768    ) -> LocalTask {
769        let path = concat!(
770            env!("CARGO_MANIFEST_DIR"),
771            "/../lean-ctx-protocol/tests/fixtures/cloud/task.claimed.response.json"
772        );
773        let mut task: serde_json::Value =
774            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
775        task["number"] = number.into();
776        task["state"] = state.into();
777        task["claim"] = serde_json::Value::Null;
778        task["acceptance"] = acceptance.map_or(serde_json::Value::Null, Into::into);
779        serde_json::from_value(serde_json::json!({
780            "task": task,
781            "transitions": [],
782            "shared": shared.map(|n| serde_json::json!({
783                "vault": "platform/api", "number": n, "at": "2026-11-04T10:00:00Z"
784            })),
785        }))
786        .unwrap()
787    }
788
789    /// Open local tasks are proposed once each, with the local number kept
790    /// in the goal and in the proposal key; proposed, in-progress, finished,
791    /// shared and incomplete ones are skipped.
792    #[test]
793    fn live_local_tasks_are_proposed_once_with_their_local_number() {
794        let tasks = vec![
795            local_task(1, "open", Some("It works"), None),
796            local_task(2, "open", Some("It works"), None),
797            local_task(3, "done", Some("It works"), None),
798            local_task(4, "cancelled", Some("It works"), None),
799            local_task(5, "rejected", Some("It works"), None),
800            local_task(6, "failed", Some("It works"), None),
801            local_task(7, "open", Some("It works"), Some(12)),
802            local_task(8, "open", None, None),
803            local_task(9, "proposed", Some("It works"), None),
804            local_task(10, "claimed", Some("It works"), None),
805            local_task(11, "submitted", Some("It works"), None),
806        ];
807        let plan: Vec<(u64, &str, Option<&str>, Option<u64>)> = plan_tasks(&tasks)
808            .iter()
809            .map(|i| (i.local_number, i.action, i.reason, i.vault_number))
810            .collect();
811        assert_eq!(
812            plan,
813            [
814                (1, "propose", None, None),
815                (2, "propose", None, None),
816                (3, "skip", Some("done"), None),
817                (4, "skip", Some("cancelled"), None),
818                (5, "skip", Some("rejected"), None),
819                (6, "skip", Some("failed"), None),
820                (7, "skip", Some("already_shared"), Some(12)),
821                (8, "skip", Some("no_acceptance"), None),
822                // Cloud would open it: it waits for acceptance here.
823                (9, "skip", Some("not_accepted"), None),
824                // Its claim, result and evidence stay where they are.
825                (10, "skip", Some("in_progress"), None),
826                (11, "skip", Some("in_progress"), None),
827            ]
828        );
829        let root = Path::new("/code/api");
830        let first = task_proposal(&tasks[0], "stable", root);
831        assert_eq!(first.goal.as_deref(), Some("Local task #1"));
832        assert_eq!(first.title, "Explain the retry budget");
833        let mut with_goal = tasks[1].clone();
834        with_goal.task.goal = Some("Write it down".into());
835        let second = task_proposal(&with_goal, "stable", root);
836        assert_eq!(
837            second.goal.as_deref(),
838            Some("Write it down\n\nLocal task #2")
839        );
840        assert_ne!(
841            first.idempotency_key(),
842            second.idempotency_key(),
843            "same title, two vault tasks"
844        );
845    }
846
847    /// A link interrupted between Cloud's answer and the local mark resumes
848    /// from the ledger: the next run only marks the task, it never sends it
849    /// again. An unanswered send is repeated with the same key while Cloud
850    /// replays it, and is never resent after that.
851    #[test]
852    fn an_interrupted_link_never_sends_a_task_twice() {
853        let tasks = [local_task(1, "open", Some("It works"), None)];
854        let proposal_of = |local: &LocalTask| task_proposal(local, "stable", Path::new("/r"));
855        let key = proposal_of(&tasks[0]).idempotency_key();
856        let mut ledger = Ledger::default();
857        let saved = std::cell::RefCell::new(Vec::<Ledger>::new());
858        let sent = std::cell::RefCell::new(Vec::<String>::new());
859
860        // Run 1: Cloud answers 41, then the run dies before the mark.
861        let mut items = plan_tasks(&tasks);
862        bring_tasks(
863            &mut items,
864            &tasks,
865            &proposal_of,
866            "vlt_api",
867            1_000,
868            &mut ledger,
869            &mut TaskSink {
870                propose: &mut |p| {
871                    sent.borrow_mut().push(p.idempotency_key());
872                    Ok(41)
873                },
874                mark: &mut |_, _| Err(lean_ctx_tasks::TaskError::Store("interrupted".into())),
875                save: &mut |l| {
876                    saved.borrow_mut().push(l.clone());
877                    Ok(())
878                },
879            },
880        );
881        assert_eq!(items[0].error.as_deref(), Some("interrupted"));
882        assert_eq!(sent.borrow().as_slice(), std::slice::from_ref(&key));
883        assert_eq!(
884            saved.borrow()[0].tasks[&1].vault_number,
885            None,
886            "recorded before it was sent"
887        );
888        assert_eq!(ledger.tasks[&1].vault_number, Some(41));
889
890        // Run 2: nothing is sent; the task is marked with Cloud's number.
891        let mut marked = Vec::new();
892        let mut items = plan_tasks(&tasks);
893        bring_tasks(
894            &mut items,
895            &tasks,
896            &proposal_of,
897            "vlt_api",
898            2_000,
899            &mut ledger,
900            &mut TaskSink {
901                propose: &mut |_| panic!("an answered task is never sent again"),
902                mark: &mut |n, number| {
903                    marked.push((n, number));
904                    Ok(())
905                },
906                save: &mut |_| Ok(()),
907            },
908        );
909        assert_eq!(marked, [(1, 41)]);
910        assert_eq!(
911            (items[0].vault_number, items[0].error.as_deref()),
912            (Some(41), None)
913        );
914        assert!(ledger.tasks.is_empty(), "the ledger lets it go once marked");
915
916        // A send Cloud never answered: repeated with the same key in the
917        // window, reported and not sent after it.
918        let unanswered = |sent_at| Ledger {
919            tasks: BTreeMap::from([(
920                1,
921                InFlight {
922                    vault_id: "vlt_api".into(),
923                    key: key.clone(),
924                    sent_at,
925                    vault_number: None,
926                },
927            )]),
928        };
929        let mut fresh = unanswered(1_000);
930        let mut items = plan_tasks(&tasks);
931        let resent = std::cell::RefCell::new(Vec::<String>::new());
932        bring_tasks(
933            &mut items,
934            &tasks,
935            &proposal_of,
936            "vlt_api",
937            1_000 + RESEND_WINDOW_SECS - 1,
938            &mut fresh,
939            &mut TaskSink {
940                propose: &mut |p| {
941                    resent.borrow_mut().push(p.idempotency_key());
942                    Ok(41)
943                },
944                mark: &mut |_, _| Ok(()),
945                save: &mut |_| Ok(()),
946            },
947        );
948        assert_eq!(
949            resent.borrow().as_slice(),
950            std::slice::from_ref(&key),
951            "the same key: LeanCTX Cloud replays"
952        );
953        assert_eq!(items[0].vault_number, Some(41));
954
955        let mut stale = unanswered(1_000);
956        let mut items = plan_tasks(&tasks);
957        bring_tasks(
958            &mut items,
959            &tasks,
960            &proposal_of,
961            "vlt_api",
962            1_000 + RESEND_WINDOW_SECS,
963            &mut stale,
964            &mut TaskSink {
965                propose: &mut |_| panic!("never resent after the window"),
966                mark: &mut |_, _| panic!("nothing to mark"),
967                save: &mut |_| Ok(()),
968            },
969        );
970        assert!(
971            items[0]
972                .error
973                .as_deref()
974                .is_some_and(|e| e.contains("Local task #1")),
975            "{:?}",
976            items[0].error
977        );
978        assert_eq!(
979            stale.tasks[&1].vault_number, None,
980            "kept for the person to check"
981        );
982    }
983
984    /// A ledger entry for another vault is not reused (a re-link sends the
985    /// task to the new vault); a refusal for good leaves no entry behind;
986    /// an earlier mark counts by its code.
987    #[test]
988    fn the_ledger_is_per_vault_and_forgets_refused_tasks() {
989        use lean_ctx_tasks::TaskError;
990        let tasks = [local_task(1, "open", Some("It works"), None)];
991        let proposal_of = |local: &LocalTask| task_proposal(local, "stable", Path::new("/r"));
992        let run = |ledger: &mut Ledger,
993                   propose: &mut dyn FnMut(&QueuedProposal) -> Result<u64, CloudError>,
994                   mark: &mut dyn FnMut(u64, u64) -> Result<(), TaskError>| {
995            let mut items = plan_tasks(&tasks);
996            bring_tasks(
997                &mut items,
998                &tasks,
999                &proposal_of,
1000                "vlt_b",
1001                1_000,
1002                ledger,
1003                &mut TaskSink {
1004                    propose,
1005                    mark,
1006                    save: &mut |_| Ok(()),
1007                },
1008            );
1009            items.remove(0)
1010        };
1011        let in_a = || Ledger {
1012            tasks: BTreeMap::from([(
1013                1,
1014                InFlight {
1015                    vault_id: "vlt_a".into(),
1016                    key: "k".into(),
1017                    sent_at: 900,
1018                    vault_number: Some(41),
1019                },
1020            )]),
1021        };
1022
1023        let mut ledger = in_a();
1024        let item = run(&mut ledger, &mut |_| Ok(7), &mut |_, _| Ok(()));
1025        assert_eq!(item.vault_number, Some(7), "vault A's number is not reused");
1026
1027        let mut ledger = Ledger::default();
1028        let item = run(
1029            &mut ledger,
1030            &mut |_| {
1031                Err(CloudError::Refused(
1032                    "the goal was not sent: it contains a secret".into(),
1033                ))
1034            },
1035            &mut |_, _| panic!("nothing to mark"),
1036        );
1037        assert!(ledger.tasks.is_empty(), "nothing waits to be resumed");
1038        assert!(
1039            item.error
1040                .as_deref()
1041                .is_some_and(|e| e.contains("not created")),
1042            "{:?}",
1043            item.error
1044        );
1045
1046        let mut ledger = Ledger::default();
1047        let item = run(
1048            &mut ledger,
1049            &mut |_| Err(CloudError::Offline("down".into())),
1050            &mut |_, _| panic!("nothing to mark"),
1051        );
1052        assert!(
1053            ledger.tasks.contains_key(&1),
1054            "a lost answer is kept to resume"
1055        );
1056        assert!(item.error.is_some());
1057
1058        let mut ledger = Ledger::default();
1059        let item = run(&mut ledger, &mut |_| Ok(7), &mut |n, _| {
1060            Err(TaskError::InvalidState {
1061                number: n,
1062                reason: "already_shared",
1063            })
1064        });
1065        assert_eq!((item.vault_number, item.error), (Some(7), None));
1066    }
1067
1068    /// Proposed, claimed and submitted local tasks hold a link back until
1069    /// they are settled; once a proposal is accepted locally, the next link
1070    /// brings it.
1071    #[test]
1072    fn unsettled_local_tasks_hold_the_link_until_settled() {
1073        let fixtures = [
1074            local_task(1, "proposed", Some("It works"), None),
1075            local_task(2, "claimed", Some("It works"), None),
1076            local_task(3, "submitted", Some("It works"), None),
1077            local_task(4, "open", Some("It works"), None),
1078            local_task(5, "proposed", Some("It works"), Some(9)),
1079        ];
1080        let named: Vec<(u64, String)> = unsettled(&fixtures)
1081            .into_iter()
1082            .map(|u| (u.local_number, u.state))
1083            .collect();
1084        assert_eq!(
1085            named,
1086            [
1087                (1, "proposed".to_string()),
1088                (2, "claimed".to_string()),
1089                (3, "submitted".to_string()),
1090            ]
1091        );
1092        assert!(unsettled_message(&unsettled(&fixtures)).contains("#3 (submitted)"));
1093
1094        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1095        let project = tempfile::tempdir().unwrap();
1096        let root = project.path();
1097        let person = lean_ctx_tasks::Actor::person("person");
1098        crate::tasks::local::write(root, |board, now| {
1099            board.propose(
1100                &person,
1101                lean_ctx_tasks::Proposal {
1102                    title: "Explain the retry budget".into(),
1103                    goal: None,
1104                    acceptance: "It works".into(),
1105                    role: None,
1106                },
1107                now,
1108            )
1109        })
1110        .unwrap();
1111        let held = unsettled_local(root).unwrap();
1112        assert_eq!(
1113            held.iter().map(|u| u.local_number).collect::<Vec<_>>(),
1114            [1],
1115            "a link now is refused"
1116        );
1117        crate::tasks::local::write(root, |board, now| board.decide(1, &person, true, None, now))
1118            .unwrap();
1119        assert!(
1120            unsettled_local(root).unwrap().is_empty(),
1121            "the link may go now"
1122        );
1123        let plan = plan_tasks(&local_tasks(root).unwrap());
1124        assert_eq!(
1125            (plan[0].action, plan[0].reason),
1126            ("propose", None),
1127            "and brings it"
1128        );
1129    }
1130
1131    fn propose_local(root: &Path, title: &str) {
1132        let person = lean_ctx_tasks::Actor::person("person");
1133        crate::tasks::local::write(root, |board, now| {
1134            board.propose(
1135                &person,
1136                lean_ctx_tasks::Proposal {
1137                    title: title.into(),
1138                    goal: None,
1139                    acceptance: "It works".into(),
1140                    role: None,
1141                },
1142                now,
1143            )
1144        })
1145        .unwrap();
1146    }
1147
1148    /// Every link asks one gate; after a link that left tasks local (or a
1149    /// link file that came in through git) the tasks not brought stay
1150    /// listed as "local, not shared" and keep working with --local, while
1151    /// a brought one is acted on in the vault only.
1152    #[test]
1153    fn a_linked_project_keeps_its_local_not_shared_tasks_reachable() {
1154        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1155        let project = tempfile::tempdir().unwrap();
1156        let root = project.path();
1157        let person = lean_ctx_tasks::Actor::person("person");
1158        for title in ["Proposed only", "Accepted", "Brought"] {
1159            propose_local(root, title);
1160        }
1161        crate::tasks::local::write(root, |board, now| {
1162            board.decide(2, &person, true, None, now)?;
1163            board.decide(3, &person, true, None, now)?;
1164            board.mark_shared(3, &person, "platform/api", 41, now)
1165        })
1166        .unwrap();
1167
1168        let refused = link_gate(root, false).unwrap_err();
1169        assert!(
1170            refused.contains("#1 (proposed)") && refused.contains(LEAVE_UNSETTLED_FLAG),
1171            "{refused}"
1172        );
1173        let left = link_gate(root, true).unwrap();
1174        assert_eq!(left.iter().map(|u| u.local_number).collect::<Vec<_>>(), [1]);
1175
1176        let not_shared: Vec<(u64, String)> = local_not_shared(root)
1177            .unwrap()
1178            .into_iter()
1179            .map(|u| (u.local_number, u.state))
1180            .collect();
1181        assert_eq!(not_shared, [(1, "proposed".into()), (2, "open".into())]);
1182        assert!(
1183            not_shared_note(&local_not_shared(root).unwrap())
1184                .is_some_and(|n| n.contains("#1 (proposed), #2 (open)"))
1185        );
1186
1187        assert!(local_action_in_linked(root, "list", None).is_ok());
1188        assert!(local_action_in_linked(root, "decide", Some(1)).is_ok());
1189        assert!(local_action_in_linked(root, "claim", Some(2)).is_ok());
1190        let brought = local_action_in_linked(root, "claim", Some(3)).unwrap_err();
1191        assert!(brought.contains("platform/api as task #41"), "{brought}");
1192        assert!(local_action_in_linked(root, "propose", None).is_err());
1193        assert!(local_action_in_linked(root, "decide", Some(9)).is_err());
1194    }
1195}