markon-core 0.15.13

markon core - Mark it on.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
use crate::chat::edits::PendingEditStore;
use crate::fswalk::path_to_forward_slash;
use crate::markdown::extract_referenced_assets_for_file;
use crate::search::SearchIndex;
use crate::workspace_fs::WorkspaceFs;
use arc_swap::ArcSwapOption;
use notify::{EventKind, RecursiveMode, Watcher};
use serde::{Deserialize, Serialize};
use std::{
    collections::{HashMap, HashSet},
    path::{Path, PathBuf},
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc, RwLock,
    },
};
use tokio::sync::broadcast;

const LIVE_RELOAD_EXTENSIONS: &[&str] = &[
    "md", "markdown", "png", "jpg", "jpeg", "gif", "webp", "avif", "svg", "css", "js",
];
const LIVE_RELOAD_IGNORED_DIRS: &[&str] = &[".git", "node_modules", "target"];

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkspaceFlags {
    #[serde(default)]
    pub enable_search: bool,
    #[serde(default)]
    pub enable_viewed: bool,
    #[serde(default)]
    pub enable_edit: bool,
    #[serde(default)]
    pub enable_live: bool,
    #[serde(default)]
    pub enable_chat: bool,
    #[serde(default)]
    pub shared_annotation: bool,
}

#[derive(Clone, Default)]
pub struct WorkspaceConfig {
    pub path: PathBuf,
    pub flags: WorkspaceFlags,
    /// `Some(name)` → a single-file workspace rooted at the file's parent
    /// directory. It exposes only `name` plus local assets that file explicitly
    /// references and that canonicalize inside `path`. Used by Open-With on
    /// macOS so opening `~/Downloads/note.md` can render `logo.svg` next to it
    /// without turning `~/Downloads` into an indexed, browsable workspace.
    /// Treated as temporary; settings may persist it so startup policy can
    /// either restore or automatically remove it.
    pub single_file: Option<String>,
    /// Per-workspace collaborator access-code hash (empty = inherit the
    /// server-level collaborator code).
    pub collaborator_access_code_hash: String,
    /// Optional short display name shown instead of the (often long) path.
    /// Purely cosmetic — never part of `hash_id`.
    pub alias: String,
}

pub(crate) struct WorkspaceEntry {
    pub id: String,
    pub fs: Arc<WorkspaceFs>,
    pub enable_search: AtomicBool,
    pub enable_viewed: AtomicBool,
    pub enable_edit: AtomicBool,
    pub enable_live: AtomicBool,
    pub enable_chat: AtomicBool,
    pub shared_annotation: AtomicBool,
    pub config_tx: broadcast::Sender<()>,
    /// Collaboration events are scoped to this workspace by construction.
    /// Channel events are further isolated by document/surface identity;
    /// workspace events (currently file watcher reloads) reach every socket
    /// attached to this entry.
    pub events_tx: broadcast::Sender<WorkspaceEvent>,
    pub search_index: ArcSwapOption<SearchIndex>,
    /// Set for temporary single-file workspaces. Holds the file name (relative
    /// to the filesystem capability root). Serving policy lives in `fs`.
    pub single_file: Option<String>,
    /// In-flight `edit_file` proposals from the chat tool, awaiting the
    /// user's accept/reject. Lives on the workspace so HTTP handlers and
    /// the agent loop can share the same store.
    pub pending_edits: Arc<PendingEditStore>,
    /// Per-workspace collaborator access-code hash (empty = inherit the
    /// server-level collaborator code).
    pub collaborator_access_code_hash: RwLock<String>,
    /// Optional short display name (empty = none). RwLock so the GUI/web can
    /// rename a workspace live without re-registering it.
    pub alias: RwLock<String>,
    /// Shutdown flag for the background watch thread. `remove()` sets it before
    /// dropping the map entry; the watch loop observes it and exits, dropping
    /// its own `Arc<WorkspaceEntry>` so the OS thread and the in-RAM search
    /// index this entry holds are freed instead of leaking after removal.
    stopped: Arc<AtomicBool>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum WorkspaceEvent {
    Channel { channel: String, payload: String },
    Workspace { payload: String },
}

impl WorkspaceEntry {
    pub(crate) fn search_ready(&self) -> bool {
        self.enable_search.load(Ordering::Relaxed) && self.search_index.load().is_some()
    }

    pub(crate) fn flags(&self) -> WorkspaceFlags {
        WorkspaceFlags {
            enable_search: self.enable_search.load(Ordering::Relaxed),
            enable_viewed: self.enable_viewed.load(Ordering::Relaxed),
            enable_edit: self.enable_edit.load(Ordering::Relaxed),
            enable_live: self.enable_live.load(Ordering::Relaxed),
            enable_chat: self.enable_chat.load(Ordering::Relaxed),
            shared_annotation: self.shared_annotation.load(Ordering::Relaxed),
        }
    }

    pub(crate) fn is_ephemeral(&self) -> bool {
        self.fs.is_single_file()
    }

    pub(crate) fn collaborator_access_code_hash(&self) -> String {
        self.collaborator_access_code_hash.read().unwrap().clone()
    }

    pub(crate) fn alias(&self) -> String {
        self.alias.read().unwrap().clone()
    }
}

/// Workspace info as serialized to JSON by `GET /api/workspaces`. Lives here
/// because it's built from [`WorkspaceEntry`] state, but its only public
/// contract is the wire format — see `crate::server::api` for the canonical
/// re-export.
#[derive(Serialize)]
pub struct WorkspaceInfo {
    pub id: String,
    /// Workspace **serving root** — what `/{id}/…` resolves under. For
    /// temporary single-file workspaces this is the parent directory, not
    /// the file itself; the file name lives in `single_file`. Consumers that
    /// render a user-visible path **must** join the two for ephemeral entries
    /// (or filter ephemeral entries out entirely).
    pub path: String,
    #[serde(flatten)]
    pub flags: WorkspaceFlags,
    pub search_ready: bool,
    /// True for temporary single-file workspaces created by Open-With.
    pub ephemeral: bool,
    /// `Some(filename)` only when ephemeral, for callers that want to display
    /// or re-derive the URL. Omitted from the wire format when None.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub single_file: Option<String>,
    /// Per-workspace collaborator access-code hash (empty = inherit the server code).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub collaborator_access_code_hash: String,
    /// Optional short display name (empty = none).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub alias: String,
}

/// Invoked whenever the registry mutates (add / update_flags / remove).
/// The host (GUI or CLI daemon) wires this to persist workspaces to
/// `~/.markon/settings.json` so CLI-driven and GUI-driven changes are
/// treated identically.
pub type PersistHook = Arc<dyn Fn(&WorkspaceRegistry) + Send + Sync>;

pub struct WorkspaceRegistry {
    inner: RwLock<HashMap<String, Arc<WorkspaceEntry>>>,
    pub(crate) salt: String,
    persist: RwLock<Option<PersistHook>>,
}

/// Stable workspace id: truncated SHA-256 of salt + path.
pub fn hash_id(path: &Path, salt: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut h = Sha256::new();
    h.update(salt.as_bytes());
    h.update(b"\0");
    h.update(path.as_os_str().to_string_lossy().as_bytes());
    let digest = h.finalize();
    format!(
        "{:02x}{:02x}{:02x}{:02x}",
        digest[0], digest[1], digest[2], digest[3]
    )
}

/// Hash an access code for storage and comparison. Salted with the per-install
/// salt (so the stored value isn't a bare SHA-256 of a often-weak code, and so
/// it can't be precomputed without reading the 0600 settings file) and
/// domain-separated from workspace-id hashing.
///
/// The result is truncated to **as many leading hex chars as the code has
/// characters**, so the stored length equals the code length — the panel uses
/// that to render the right number of `•` in the "code is set" token without
/// being able to recover the code. Verification stays consistent because both
/// store and check route through this function: the candidate is truncated by
/// *its own* length, so the correct code (same length) still matches, and a
/// wrong-length guess can't. Trade-off: very short codes are checked against
/// only a few hex chars — rely on a reasonable code length (the per-IP unlock
/// cooldown also throttles guessing).
pub fn hash_access_code(salt: &str, code: &str) -> String {
    let hex = access_code_digest(salt, code);
    let n = code.chars().count().min(hex.len());
    hex[..n].to_string()
}

/// Full (untruncated) salted digest of an access code, as 64 hex chars.
fn access_code_digest(salt: &str, code: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut h = Sha256::new();
    h.update(salt.as_bytes());
    h.update(b"\0mk-access\0");
    h.update(code.as_bytes());
    h.finalize().iter().map(|b| format!("{b:02x}")).collect()
}

/// Verify a submitted access code against a stored hash. Owns both schemes:
/// the current length-truncated form (see [`hash_access_code`]) and, when the
/// stored value is a full 64-char digest, the legacy untruncated form written
/// before truncation existed — so codes set by older builds keep unlocking
/// after an upgrade instead of silently never matching.
pub fn access_code_matches(salt: &str, code: &str, stored: &str) -> bool {
    if stored.is_empty() {
        return false;
    }
    let full = access_code_digest(salt, code);
    let n = code.chars().count().min(full.len());
    if ct_eq(&full.as_bytes()[..n], stored.as_bytes()) {
        return true;
    }
    stored.len() == full.len() && ct_eq(full.as_bytes(), stored.as_bytes())
}

/// Constant-time byte comparison (length leak is fine — lengths aren't secret).
pub(crate) fn ct_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff = 0u8;
    for (x, y) in a.iter().zip(b) {
        diff |= x ^ y;
    }
    diff == 0
}

/// Cryptographically-random 32-hex-char token. Used as the management API
/// bearer (`X-Markon-Token`) and as the per-install salt for workspace IDs.
/// Backed by `uuid::Uuid::new_v4` which sources 122 bits of entropy from the
/// OS RNG — a meaningful upgrade over a hash of `SystemTime + pid`.
pub(crate) fn generate_token() -> String {
    uuid::Uuid::new_v4().simple().to_string()
}

/// Write a file that holds secrets (management token, salt, provider api keys)
/// with owner-only (0600) permissions and **no world-readable window**, and
/// **atomically** — a crash mid-write must never leave a truncated
/// `settings.json` (which holds the per-install salt and provider API keys).
///
/// Strategy: write the full contents into a uniquely-named temp file in the
/// **same directory** (so `rename` stays on one filesystem and is therefore
/// atomic), fsync it, then `rename` it over the destination. `rename(2)`
/// atomically replaces the destination inode, so a reader/observer always sees
/// either the old complete file or the new complete file — never a partial one.
/// On Unix the temp is created with mode 0600 up front (closing the
/// create-then-chmod TOCTOU gap); since `rename` swaps in that fresh inode, the
/// destination ends up 0600 regardless of any looser bits it previously had. On
/// non-Unix we temp+rename as well — files under the user profile inherit
/// restrictive per-user ACLs. On any error the temp file is removed.
pub(crate) fn write_file_user_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
    use std::io::Write;
    // Unique temp name in the destination directory: pid + a process-global
    // counter guarantees no collision between concurrent or repeated writes.
    static TMP_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let dir = path.parent().unwrap_or_else(|| Path::new("."));
    let stem = path
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("settings");
    let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
    let tmp = dir.join(format!(".{stem}.tmp.{}.{seq}", std::process::id()));

    let write_tmp = || -> std::io::Result<()> {
        let mut opts = std::fs::OpenOptions::new();
        opts.write(true).create_new(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            opts.mode(0o600);
        }
        let mut f = opts.open(&tmp)?;
        f.write_all(contents)?;
        f.sync_all()?;
        Ok(())
    };

    if let Err(e) = write_tmp() {
        let _ = std::fs::remove_file(&tmp);
        return Err(e);
    }
    if let Err(e) = std::fs::rename(&tmp, path) {
        tracing::warn!(
            "atomic rename of {} onto {} failed: {e}",
            tmp.display(),
            path.display()
        );
        let _ = std::fs::remove_file(&tmp);
        return Err(e);
    }
    Ok(())
}

/// Expand `~` / `~` and canonicalize (dunce strips the `\\?\` verbatim prefix
/// on Windows so UI-visible paths stay clean).
pub fn expand_and_canonicalize(raw: &str) -> std::io::Result<PathBuf> {
    let normalized = if raw.starts_with('') {
        raw.replacen('', "~", 1)
    } else {
        raw.to_string()
    };
    let expanded = if normalized.starts_with("~/") || normalized == "~" {
        dirs::home_dir()
            .map(|home| {
                if normalized == "~" {
                    home
                } else {
                    home.join(&normalized[2..])
                }
            })
            .unwrap_or_else(|| PathBuf::from(&normalized))
    } else {
        PathBuf::from(&normalized)
    };
    dunce::canonicalize(&expanded).or(Ok(expanded))
}

impl WorkspaceRegistry {
    pub fn new(salt: String) -> Self {
        Self {
            inner: RwLock::new(HashMap::new()),
            salt,
            persist: RwLock::new(None),
        }
    }
    pub fn set_persist_hook(&self, hook: PersistHook) {
        *self.persist.write().unwrap() = Some(hook);
    }
    fn notify_persist(&self) {
        let hook = self.persist.read().unwrap().clone();
        if let Some(hook) = hook {
            hook(self);
        }
    }
    pub fn add(&self, config: WorkspaceConfig) -> String {
        // Hash on the workspace's identity, not its serving root: a single-file
        // workspace and an enclosing directory workspace coexist with distinct
        // ids even though they share the same `root` (parent dir). Same file
        // re-opened → same id → idempotent reuse.
        let identity = match &config.single_file {
            Some(name) => config.path.join(name),
            None => config.path.clone(),
        };
        let id = hash_id(&identity, &self.salt);
        // Idempotent: same identity registered twice just updates flags on the
        // existing entry instead of spawning a second indexer thread.
        if self.inner.read().unwrap().contains_key(&id) {
            self.update_flags(&id, config.flags);
            self.notify_persist();
            return id;
        }
        let (config_tx, _) = broadcast::channel(4);
        let (events_tx, _) = broadcast::channel(100);
        let single_file = config.single_file.clone();
        let workspace_fs = Arc::new(WorkspaceFs::new(
            config.path.clone(),
            single_file.as_deref(),
        ));
        let entry = Arc::new(WorkspaceEntry {
            id: id.clone(),
            fs: workspace_fs,
            enable_search: AtomicBool::new(config.flags.enable_search),
            enable_viewed: AtomicBool::new(config.flags.enable_viewed),
            enable_edit: AtomicBool::new(config.flags.enable_edit),
            enable_live: AtomicBool::new(config.flags.enable_live),
            enable_chat: AtomicBool::new(config.flags.enable_chat),
            shared_annotation: AtomicBool::new(config.flags.shared_annotation),
            config_tx,
            events_tx,
            search_index: ArcSwapOption::empty(),
            single_file: single_file.clone(),
            pending_edits: Arc::new(PendingEditStore::new()),
            collaborator_access_code_hash: RwLock::new(config.collaborator_access_code_hash),
            alias: RwLock::new(config.alias),
            stopped: Arc::new(AtomicBool::new(false)),
        });
        self.inner
            .write()
            .unwrap()
            .insert(id.clone(), entry.clone());
        match single_file {
            Some(name) => {
                // Seed scoped assets from the file's current content, then watch
                // for external edits to keep it fresh. When search is enabled,
                // build an index scoped to ONLY this file (no parent WalkDir, no
                // sibling leakage); the single-file watcher refreshes it on edit.
                refresh_allowed_assets(&entry, &name);
                if config.flags.enable_search {
                    spawn_search_indexer(entry.clone());
                }
                spawn_single_file_watcher(config.path, entry.clone(), name);
            }
            None => {
                if config.flags.enable_search {
                    spawn_search_indexer(entry.clone());
                }
                spawn_directory_watcher(config.path, entry.clone());
            }
        }
        self.notify_persist();
        id
    }
    pub fn update_flags(&self, id: &str, flags: WorkspaceFlags) -> bool {
        let guard = self.inner.read().unwrap();
        let Some(entry) = guard.get(id).cloned() else {
            return false;
        };
        drop(guard);
        let was_search = entry
            .enable_search
            .swap(flags.enable_search, Ordering::Relaxed);
        entry
            .enable_viewed
            .store(flags.enable_viewed, Ordering::Relaxed);
        entry
            .enable_edit
            .store(flags.enable_edit, Ordering::Relaxed);
        entry
            .enable_live
            .store(flags.enable_live, Ordering::Relaxed);
        entry
            .enable_chat
            .store(flags.enable_chat, Ordering::Relaxed);
        entry
            .shared_annotation
            .store(flags.shared_annotation, Ordering::Relaxed);
        let _ = entry.config_tx.send(());
        // Mirror the spawn/clear semantics for both directory and single-file
        // workspaces: turning search on spawns the appropriate indexer, turning
        // it off drops the index so we stop serving stale results and free RAM.
        if flags.enable_search && !was_search && entry.search_index.load().is_none() {
            spawn_search_indexer(entry);
        } else if !flags.enable_search && was_search {
            entry.search_index.store(None);
        }
        self.notify_persist();
        true
    }
    pub fn remove(&self, id: &str) -> bool {
        let removed = self.inner.write().unwrap().remove(id);
        if let Some(entry) = &removed {
            // Existing HTTP lookups stop immediately when the entry leaves the
            // registry. Wake all config/collaboration sockets as well so an
            // already-upgraded connection cannot outlive a detached workspace.
            entry.stopped.store(true, Ordering::Relaxed);
            let _ = entry.config_tx.send(());
            self.notify_persist();
        }
        removed.is_some()
    }
    pub(crate) fn get(&self, id: &str) -> Option<Arc<WorkspaceEntry>> {
        self.inner.read().unwrap().get(id).cloned()
    }
    /// Set (or clear) a workspace's collaborator access-code hash and persist.
    /// Returns false if the id isn't registered.
    pub fn set_collaborator_access_code(&self, id: &str, hash: &str) -> bool {
        let guard = self.inner.read().unwrap();
        let Some(entry) = guard.get(id) else {
            return false;
        };
        *entry.collaborator_access_code_hash.write().unwrap() = hash.to_string();
        let _ = entry.config_tx.send(());
        drop(guard);
        self.notify_persist();
        true
    }

    /// Set (or clear, with an empty string) a workspace's alias and persist.
    /// Returns false if the id isn't registered.
    pub fn set_alias(&self, id: &str, alias: &str) -> bool {
        let guard = self.inner.read().unwrap();
        let Some(entry) = guard.get(id) else {
            return false;
        };
        *entry.alias.write().unwrap() = alias.to_string();
        drop(guard);
        self.notify_persist();
        true
    }
    pub(crate) fn list(&self) -> Vec<Arc<WorkspaceEntry>> {
        let mut v: Vec<_> = self.inner.read().unwrap().values().cloned().collect();
        // HashMap iteration order is non-deterministic, which leaked into the
        // workspace list (GUI + `GET /api/workspaces`) and `settings.json`
        // (re-written in a different order each save). Sort by serving root,
        // then pinned file name, so the order is stable and path-alphabetical —
        // single-file entries group under their parent dir. (root, single_file)
        // is the workspace identity, so this key is unique and total.
        v.sort_by(|a, b| {
            a.fs.ambient_root()
                .cmp(b.fs.ambient_root())
                .then_with(|| a.single_file.cmp(&b.single_file))
        });
        v
    }
    pub fn info_list(&self) -> Vec<WorkspaceInfo> {
        self.list()
            .into_iter()
            .map(|e| WorkspaceInfo {
                id: e.id.clone(),
                path: e.fs.ambient_root().to_string_lossy().to_string(),
                flags: e.flags(),
                search_ready: e.search_ready(),
                ephemeral: e.is_ephemeral(),
                single_file: e.single_file.clone(),
                collaborator_access_code_hash: e.collaborator_access_code_hash(),
                alias: e.alias(),
            })
            .collect()
    }
}

/// Read the single-file's current content and replace its scoped asset map
/// with the local asset paths it explicitly references. Errors (file gone,
/// unreadable) clear the set — a missing source can't legitimately bless any
/// sibling.
fn refresh_allowed_assets(entry: &WorkspaceEntry, file_name: &str) {
    let root = entry.fs.ambient_root();
    let abs = root.join(file_name);
    let new_set = match std::fs::read_to_string(&abs) {
        Ok(content) => extract_referenced_assets_for_file(&content, &abs, root),
        Err(_) => HashSet::new(),
    };
    entry.fs.replace_assets(new_set);
}

/// Shared scaffold for the notify-based watchers below: spawn a thread that
/// owns the channel and watcher, forward Ok events, and run `on_event` for
/// each one. The thread exits (dropping the watcher) when the watch cannot
/// be established, the channel closes, or `stopped` is set (workspace removed).
fn spawn_watch_thread(
    root: PathBuf,
    mode: RecursiveMode,
    stopped: Arc<AtomicBool>,
    mut on_event: impl FnMut(notify::Event) + Send + 'static,
) {
    std::thread::spawn(move || {
        let (tx, rx) = std::sync::mpsc::channel();
        let Ok(mut watcher) = notify::recommended_watcher(move |res| {
            if let Ok(e) = res {
                let _ = tx.send(e);
            }
        }) else {
            return;
        };
        if watcher.watch(&root, mode).is_err() {
            return;
        }
        // Poll with a timeout rather than a bare `recv()` so the thread wakes
        // periodically to observe `stopped` even when no filesystem events
        // arrive. A removed workspace would otherwise block here forever,
        // leaking the OS thread and the in-RAM search index it pins.
        loop {
            if stopped.load(Ordering::Relaxed) {
                return;
            }
            match rx.recv_timeout(std::time::Duration::from_millis(500)) {
                Ok(event) => {
                    if stopped.load(Ordering::Relaxed) {
                        return;
                    }
                    on_event(event);
                }
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => return,
            }
        }
    });
}

/// Watch the parent directory of a single-file workspace and:
///   * filter events down to `{file_name} ∪ scoped assets`
///   * on changes to `file_name`, re-derive the asset allowlist so that newly
///     referenced local assets become accessible (and removed ones stop being)
///   * push a `file_changed` WS message so the open browser tab reloads.
///
/// `notify` cannot reliably watch a single file across platforms, so the
/// minimum viable scope is the parent directory — non-recursive.
fn spawn_single_file_watcher(root: PathBuf, entry: Arc<WorkspaceEntry>, file_name: String) {
    let target = root.join(&file_name);
    let stopped = entry.stopped.clone();
    spawn_watch_thread(
        root.clone(),
        RecursiveMode::NonRecursive,
        stopped,
        move |event: notify::Event| {
            for path in event.paths {
                let Ok(rel) = path.strip_prefix(&root) else {
                    continue;
                };
                let rel_str = rel.to_string_lossy().to_string();
                let touched_pinned = path == target;
                let touched_asset = entry.fs.is_asset(rel);
                if !(touched_pinned || touched_asset) {
                    continue;
                }
                let mut should_broadcast = false;
                match event.kind {
                    EventKind::Create(_) | EventKind::Modify(_) => {
                        if touched_pinned {
                            refresh_allowed_assets(&entry, &file_name);
                            // Keep the file-scoped search index in sync. No-op
                            // when search is disabled (no index loaded).
                            if let Some(idx) = entry.search_index.load_full() {
                                let _ = idx.update_file(&target);
                            }
                        }
                        should_broadcast = true;
                    }
                    // Don't broadcast for Remove: the file just went away,
                    // reloading would 404 the tab.
                    EventKind::Remove(_) if touched_pinned => {
                        entry.fs.clear_assets();
                        if let Some(idx) = entry.search_index.load_full() {
                            let _ = idx.delete_file(&target);
                        }
                    }
                    _ => {}
                }
                if should_broadcast {
                    let file_payload = serde_json::json!({
                        "type": "file_changed",
                        "workspace_id": entry.id,
                        "path": rel_str,
                    })
                    .to_string();
                    let _ = entry.events_tx.send(WorkspaceEvent::Workspace {
                        payload: file_payload,
                    });
                }
            }
        },
    );
}

fn spawn_search_indexer(entry: Arc<WorkspaceEntry>) {
    std::thread::spawn(move || {
        if let Ok(idx) = SearchIndex::for_workspace(entry.fs.clone()) {
            entry.search_index.store(Some(Arc::new(idx)));
        }
    });
}

fn spawn_directory_watcher(root: PathBuf, entry: Arc<WorkspaceEntry>) {
    let stopped = entry.stopped.clone();
    spawn_watch_thread(
        root.clone(),
        RecursiveMode::Recursive,
        stopped,
        move |event: notify::Event| {
            let event_kind = event.kind;
            for path in event.paths {
                match &event_kind {
                    EventKind::Create(_) | EventKind::Modify(_) => {
                        if let Some(idx) = entry.search_index.load_full() {
                            let _ = idx.update_file(&path);
                        }
                    }
                    EventKind::Remove(_) => {
                        if let Some(idx) = entry.search_index.load_full() {
                            let _ = idx.delete_file(&path);
                        }
                    }
                    _ => continue,
                }
                if let Some(rel_str) = directory_live_reload_path(&root, &path) {
                    let payload = serde_json::json!({
                        "type": "file_changed",
                        "workspace_id": entry.id,
                        "path": rel_str,
                    })
                    .to_string();
                    let _ = entry.events_tx.send(WorkspaceEvent::Workspace { payload });
                }
            }
        },
    );
}

fn directory_live_reload_path(root: &Path, path: &Path) -> Option<String> {
    let rel = path.strip_prefix(root).ok()?;
    if rel.as_os_str().is_empty()
        || rel.components().any(|component| {
            let name = component.as_os_str().to_string_lossy();
            LIVE_RELOAD_IGNORED_DIRS
                .iter()
                .any(|ignored| name.eq_ignore_ascii_case(ignored))
        })
    {
        return None;
    }
    let ext = rel.extension()?.to_string_lossy().to_ascii_lowercase();
    if !LIVE_RELOAD_EXTENSIONS.contains(&ext.as_str()) {
        return None;
    }
    Some(path_to_forward_slash(rel))
}

#[derive(serde::Serialize, serde::Deserialize)]
pub struct ServerLock {
    pub port: u16,
    pub token: String,
    /// Bind host the daemon was started with (e.g. `0.0.0.0`). Lets a CLI that
    /// registers a workspace into an already-running daemon reproduce the same
    /// reachable/featured URLs. `#[serde(default)]` keeps old lock files (which
    /// predate this field) readable — they deserialize to an empty string,
    /// which callers treat as loopback.
    #[serde(default)]
    pub host: String,
}
impl ServerLock {
    pub(crate) fn path() -> PathBuf {
        dirs::home_dir()
            .expect("HOME directory required")
            .join(".markon")
            .join("server.lock")
    }
    pub(crate) fn write(&self) -> std::io::Result<()> {
        let path = Self::path();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        write_file_user_private(&path, serde_json::to_string(self).unwrap().as_bytes())
    }
    pub fn read() -> Option<Self> {
        let path = Self::path();
        let content = match std::fs::read_to_string(&path) {
            Ok(c) => c,
            Err(e) => {
                if e.kind() != std::io::ErrorKind::NotFound {
                    tracing::warn!("cannot read server lock {}: {e}", path.display());
                }
                return None;
            }
        };
        match serde_json::from_str(&content) {
            Ok(v) => Some(v),
            Err(e) => {
                tracing::warn!(
                    "corrupted server lock file {}: {e}; ignoring",
                    path.display()
                );
                None
            }
        }
    }
    pub(crate) fn remove() {
        let _ = std::fs::remove_file(Self::path());
    }
    pub fn is_alive(&self) -> bool {
        let connect_host = if crate::net::host_is_wildcard_v6(&self.host) {
            "::1"
        } else if crate::net::host_is_wildcard_v4(&self.host) {
            "127.0.0.1"
        } else {
            self.host.as_str()
        };
        let Ok(addr) = crate::net::bind_socket_addr(connect_host, self.port) else {
            return false;
        };
        std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(500)).is_ok()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn hash_id_is_deterministic() {
        let p = std::path::Path::new("/tmp/test");
        assert_eq!(hash_id(p, "s"), hash_id(p, "s"));
    }

    #[test]
    fn hash_id_depends_on_salt() {
        let p = std::path::Path::new("/tmp/test");
        assert_ne!(hash_id(p, "a"), hash_id(p, "b"));
    }

    #[test]
    fn registry_directory_id_matches_hash_contract() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let root = temp_dir.path().to_path_buf();
        let salt = "contract-salt";
        let registry = WorkspaceRegistry::new(salt.into());

        let id = registry.add(WorkspaceConfig {
            path: root.clone(),
            flags: WorkspaceFlags::default(),
            single_file: None,
            collaborator_access_code_hash: String::new(),
            ..Default::default()
        });

        assert_eq!(id, hash_id(&root, salt));
    }

    #[test]
    fn access_code_hash_len_equals_code_len() {
        assert_eq!(hash_access_code("s", "test123").len(), 7);
        assert_eq!(hash_access_code("s", "").len(), 0);
    }

    #[test]
    fn access_code_matches_current_scheme() {
        let stored = hash_access_code("s", "test123");
        assert!(access_code_matches("s", "test123", &stored));
        assert!(!access_code_matches("s", "test124", &stored));
        // Wrong length can't match a truncated hash.
        assert!(!access_code_matches("s", "test1234", &stored));
        // Empty stored hash gates nothing.
        assert!(!access_code_matches("s", "anything", ""));
    }

    #[test]
    fn access_code_matches_legacy_full_hash() {
        // Pre-truncation builds stored the full 64-char digest; those codes
        // must keep unlocking after an upgrade.
        let legacy = access_code_digest("s", "test123");
        assert_eq!(legacy.len(), 64);
        assert!(access_code_matches("s", "test123", &legacy));
        assert!(!access_code_matches("s", "wrong", &legacy));
    }

    #[test]
    fn directory_live_reload_filter_tracks_docs_and_assets_only() {
        let root = Path::new("/repo");

        assert_eq!(
            directory_live_reload_path(root, &root.join("docs").join("a.md")).as_deref(),
            Some("docs/a.md")
        );
        assert_eq!(
            directory_live_reload_path(root, &root.join("assets").join("app.js")).as_deref(),
            Some("assets/app.js")
        );
        assert_eq!(
            directory_live_reload_path(root, &root.join("img").join("hero.PNG")).as_deref(),
            Some("img/hero.PNG")
        );

        assert!(directory_live_reload_path(root, &root.join(".git").join("HEAD")).is_none());
        assert!(
            directory_live_reload_path(root, &root.join("node_modules").join("x.md")).is_none()
        );
        assert!(directory_live_reload_path(root, &root.join("target").join("x.css")).is_none());
        assert!(directory_live_reload_path(root, &root.join("README")).is_none());
        assert!(directory_live_reload_path(root, &root.join("notes.txt")).is_none());
    }

    /// Regression for #32: the workspace list must be deterministically ordered
    /// (by path), not in HashMap iteration order. Scrambled inserts → stable,
    /// path-sorted output, with single-file entries grouped under their dir.
    #[test]
    fn workspace_list_is_deterministically_ordered_by_path() {
        let tmp = tempfile::TempDir::new().unwrap();
        let base = tmp.path();
        std::fs::create_dir_all(base.join("alpha")).unwrap();
        std::fs::create_dir_all(base.join("charlie")).unwrap();
        std::fs::write(base.join("alpha").join("a.md"), "# a").unwrap();
        std::fs::write(base.join("alpha").join("z.md"), "# z").unwrap();

        let reg = WorkspaceRegistry::new("salt".into());
        let mk = |path: PathBuf, single: Option<&str>| WorkspaceConfig {
            path,
            flags: WorkspaceFlags::default(),
            single_file: single.map(str::to_string),
            collaborator_access_code_hash: String::new(),
            ..Default::default()
        };
        // Insert in a scrambled order.
        reg.add(mk(base.join("charlie"), None));
        reg.add(mk(base.join("alpha"), Some("z.md")));
        reg.add(mk(base.join("alpha"), None));
        reg.add(mk(base.join("alpha"), Some("a.md")));

        let order: Vec<(PathBuf, Option<String>)> = reg
            .list()
            .iter()
            .map(|e| (e.fs.ambient_root().to_path_buf(), e.single_file.clone()))
            .collect();
        assert_eq!(
            order,
            vec![
                (base.join("alpha"), None),
                (base.join("alpha"), Some("a.md".into())),
                (base.join("alpha"), Some("z.md".into())),
                (base.join("charlie"), None),
            ],
            "list() must be sorted by (root, single_file)"
        );

        // Stable across repeated calls.
        let a: Vec<String> = reg.list().iter().map(|e| e.id.clone()).collect();
        let b: Vec<String> = reg.list().iter().map(|e| e.id.clone()).collect();
        assert_eq!(a, b);
    }

    #[test]
    fn server_lock_host_defaults_when_absent() {
        // Old lock files predate the `host` field; they must still deserialize.
        let old = r#"{"port":6419,"token":"abc"}"#;
        let lock: ServerLock = serde_json::from_str(old).unwrap();
        assert_eq!(lock.port, 6419);
        assert_eq!(lock.token, "abc");
        assert_eq!(lock.host, "");
    }

    #[test]
    fn server_lock_host_round_trips() {
        let lock = ServerLock {
            port: 6419,
            token: "tok".into(),
            host: "0.0.0.0".into(),
        };
        let json = serde_json::to_string(&lock).unwrap();
        let back: ServerLock = serde_json::from_str(&json).unwrap();
        assert_eq!(back.host, "0.0.0.0");
        assert_eq!(back.port, 6419);
        assert_eq!(back.token, "tok");
    }

    /// Block until the entry's search index is populated (it's built on a
    /// background thread), or fail the test after a generous timeout.
    fn wait_for_index(entry: &Arc<WorkspaceEntry>) -> Arc<SearchIndex> {
        for _ in 0..200 {
            if let Some(idx) = entry.search_index.load_full() {
                return idx;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        panic!("search index was not built in time");
    }

    /// SECURITY: a single-file workspace with search enabled must index ONLY
    /// the pinned file. A sibling `.md` carrying a unique term must never be
    /// findable through that workspace's index, proving the parent directory is
    /// not walked.
    #[test]
    fn single_file_workspace_search_no_sibling_leakage() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let dir = temp_dir.path();
        std::fs::write(
            dir.join("pinned.md"),
            "# Pinned\nuniquepinnedtoken is here.",
        )
        .unwrap();
        std::fs::write(
            dir.join("sibling.md"),
            "# Sibling\nuniquesiblingtoken stays private.",
        )
        .unwrap();

        let registry = WorkspaceRegistry::new("test-salt".into());
        let id = registry.add(WorkspaceConfig {
            path: dir.to_path_buf(),
            flags: WorkspaceFlags {
                enable_search: true,
                ..Default::default()
            },
            single_file: Some("pinned.md".into()),
            collaborator_access_code_hash: String::new(),
            ..Default::default()
        });

        let entry = registry.get(&id).unwrap();
        assert!(entry.is_ephemeral());
        let idx = wait_for_index(&entry);

        assert_eq!(
            idx.search("uniquesiblingtoken", 10).unwrap().len(),
            0,
            "single-file workspace leaked a sibling through search"
        );
        assert_eq!(
            idx.search("uniquepinnedtoken", 10).unwrap().len(),
            1,
            "pinned file should be searchable"
        );
    }

    /// The search toggle must work for single-file workspaces too: turning it
    /// on spawns the file-scoped indexer, turning it off clears the index.
    #[test]
    fn single_file_workspace_search_toggle_spawns_and_clears() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let dir = temp_dir.path();
        std::fs::write(dir.join("note.md"), "# Note\ntoggletoken here.").unwrap();

        let registry = WorkspaceRegistry::new("test-salt".into());
        // Start with search OFF.
        let id = registry.add(WorkspaceConfig {
            path: dir.to_path_buf(),
            flags: WorkspaceFlags::default(),
            single_file: Some("note.md".into()),
            collaborator_access_code_hash: String::new(),
            ..Default::default()
        });
        let entry = registry.get(&id).unwrap();
        assert!(entry.search_index.load().is_none());

        // Turn search ON → file-scoped index appears.
        registry.update_flags(
            &id,
            WorkspaceFlags {
                enable_search: true,
                ..Default::default()
            },
        );
        let idx = wait_for_index(&entry);
        assert_eq!(idx.search("toggletoken", 10).unwrap().len(), 1);

        // Turn search OFF → index is cleared.
        registry.update_flags(&id, WorkspaceFlags::default());
        assert!(
            entry.search_index.load().is_none(),
            "disabling search must clear the single-file index"
        );
    }
}