-
Notifications
You must be signed in to change notification settings - Fork 202
Expand file tree
/
Copy pathtest_project_context.py
More file actions
2650 lines (2156 loc) · 93.1 KB
/
test_project_context.py
File metadata and controls
2650 lines (2156 loc) · 93.1 KB
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
"""Tests for project context utilities (no standard-library mock usage).
These functions are config/env driven, so we use the real ConfigManager-backed
test config file and pytest monkeypatch for environment variables.
"""
from __future__ import annotations
from contextlib import asynccontextmanager
from typing import Any, AsyncIterator, cast
import pytest
class _ContextState:
"""Minimal FastMCP context-state stub for unit tests."""
def __init__(self):
self._state: dict[str, object] = {}
async def get_state(self, key: str):
return self._state.get(key)
async def set_state(self, key: str, value: object, **kwargs) -> None:
self._state[key] = value
async def info(self, message: str) -> None:
self._state["info_message"] = message
def _ctx(context: _ContextState) -> Any:
return cast(Any, context)
def _workspace(
*,
tenant_id: str,
workspace_type: str,
name: str,
role: str,
slug: str | None = None,
is_default: bool = False,
):
from basic_memory.schemas.cloud import WorkspaceInfo
return WorkspaceInfo(
tenant_id=tenant_id,
workspace_type=workspace_type,
slug=slug or name.casefold().replace(" ", "-"),
name=name,
role=role,
is_default=is_default,
)
def _project(
name: str,
*,
id: int = 1,
external_id: str = "11111111-1111-1111-1111-111111111111",
is_default: bool = False,
):
from basic_memory.schemas.project_info import ProjectItem
return ProjectItem(
id=id,
external_id=external_id,
name=name,
path=f"/{name}",
is_default=is_default,
)
@pytest.mark.asyncio
async def test_returns_none_when_no_default_and_no_project(config_manager, monkeypatch):
from basic_memory.mcp.project_context import resolve_project_parameter
cfg = config_manager.load_config()
cfg.default_project = None
config_manager.save_config(cfg)
monkeypatch.delenv("BASIC_MEMORY_MCP_PROJECT", raising=False)
# Prevent API fallback from returning a project via stale dependency overrides
async def _no_api_fallback():
return None
monkeypatch.setattr(
"basic_memory.mcp.project_context._resolve_default_project_from_api",
_no_api_fallback,
)
assert await resolve_project_parameter(project=None, allow_discovery=False) is None
@pytest.mark.asyncio
async def test_allows_discovery_when_enabled(config_manager, monkeypatch):
from basic_memory.mcp.project_context import resolve_project_parameter
cfg = config_manager.load_config()
cfg.default_project = None
config_manager.save_config(cfg)
# Prevent API fallback from returning a project via stale dependency overrides
async def _no_api_fallback():
return None
monkeypatch.setattr(
"basic_memory.mcp.project_context._resolve_default_project_from_api",
_no_api_fallback,
)
assert await resolve_project_parameter(project=None, allow_discovery=True) is None
@pytest.mark.asyncio
async def test_returns_project_when_specified(config_manager):
from basic_memory.mcp.project_context import resolve_project_parameter
cfg = config_manager.load_config()
config_manager.save_config(cfg)
assert await resolve_project_parameter(project="my-project") == "my-project"
@pytest.mark.asyncio
async def test_uses_env_var_priority(config_manager, monkeypatch):
from basic_memory.mcp.project_context import resolve_project_parameter
cfg = config_manager.load_config()
config_manager.save_config(cfg)
monkeypatch.setenv("BASIC_MEMORY_MCP_PROJECT", "env-project")
assert await resolve_project_parameter(project="explicit-project") == "env-project"
@pytest.mark.asyncio
async def test_uses_explicit_project_when_no_env(config_manager, monkeypatch):
from basic_memory.mcp.project_context import resolve_project_parameter
cfg = config_manager.load_config()
config_manager.save_config(cfg)
monkeypatch.delenv("BASIC_MEMORY_MCP_PROJECT", raising=False)
assert await resolve_project_parameter(project="explicit-project") == "explicit-project"
@pytest.mark.asyncio
async def test_canonicalizes_case_insensitive_project_reference(
config_manager, config_home, monkeypatch
):
from basic_memory.config import ProjectEntry
from basic_memory.mcp.project_context import resolve_project_parameter
cfg = config_manager.load_config()
project_name = "Personal-Project"
project_path = config_home / "personal-project"
project_path.mkdir(parents=True, exist_ok=True)
cfg.projects[project_name] = ProjectEntry(path=str(project_path))
config_manager.save_config(cfg)
monkeypatch.delenv("BASIC_MEMORY_MCP_PROJECT", raising=False)
assert await resolve_project_parameter(project="personal-project") == project_name
assert await resolve_project_parameter(project="PERSONAL-PROJECT") == project_name
@pytest.mark.asyncio
async def test_uses_default_project(config_manager, config_home, monkeypatch):
from basic_memory.mcp.project_context import resolve_project_parameter
from basic_memory.config import ProjectEntry
cfg = config_manager.load_config()
(config_home / "default-project").mkdir(parents=True, exist_ok=True)
cfg.projects["default-project"] = ProjectEntry(path=str(config_home / "default-project"))
cfg.default_project = "default-project"
config_manager.save_config(cfg)
monkeypatch.delenv("BASIC_MEMORY_MCP_PROJECT", raising=False)
assert await resolve_project_parameter(project=None) == "default-project"
@pytest.mark.asyncio
async def test_returns_none_when_no_default(config_manager, monkeypatch):
from basic_memory.mcp.project_context import resolve_project_parameter
cfg = config_manager.load_config()
cfg.default_project = None
config_manager.save_config(cfg)
monkeypatch.delenv("BASIC_MEMORY_MCP_PROJECT", raising=False)
# Prevent API fallback from returning a project via stale dependency overrides
async def _no_api_fallback():
return None
monkeypatch.setattr(
"basic_memory.mcp.project_context._resolve_default_project_from_api",
_no_api_fallback,
)
assert await resolve_project_parameter(project=None) is None
@pytest.mark.asyncio
async def test_env_constraint_overrides_default(config_manager, config_home, monkeypatch):
from basic_memory.mcp.project_context import resolve_project_parameter
from basic_memory.config import ProjectEntry
cfg = config_manager.load_config()
(config_home / "default-project").mkdir(parents=True, exist_ok=True)
cfg.projects["default-project"] = ProjectEntry(path=str(config_home / "default-project"))
cfg.default_project = "default-project"
config_manager.save_config(cfg)
monkeypatch.setenv("BASIC_MEMORY_MCP_PROJECT", "env-project")
assert await resolve_project_parameter(project=None) == "env-project"
@pytest.mark.asyncio
async def test_workspace_auto_selects_single_and_caches(monkeypatch):
from basic_memory.mcp.project_context import resolve_workspace_parameter
context = _ContextState()
only_workspace = _workspace(
tenant_id="11111111-1111-1111-1111-111111111111",
workspace_type="personal",
slug="personal",
name="Personal",
role="owner",
is_default=True,
)
async def fake_get_available_workspaces(context=None):
return [only_workspace]
monkeypatch.setattr(
"basic_memory.mcp.project_context.get_available_workspaces",
fake_get_available_workspaces,
)
resolved = await resolve_workspace_parameter(context=_ctx(context))
assert resolved.tenant_id == only_workspace.tenant_id
assert await context.get_state("active_workspace") == only_workspace.model_dump()
@pytest.mark.asyncio
async def test_workspace_requires_user_choice_when_multiple(monkeypatch):
from basic_memory.mcp.project_context import resolve_workspace_parameter
workspaces = [
_workspace(
tenant_id="11111111-1111-1111-1111-111111111111",
workspace_type="personal",
slug="personal",
name="Personal",
role="owner",
is_default=True,
),
_workspace(
tenant_id="22222222-2222-2222-2222-222222222222",
workspace_type="organization",
slug="team",
name="Team",
role="editor",
),
]
async def fake_get_available_workspaces(context=None):
return workspaces
monkeypatch.setattr(
"basic_memory.mcp.project_context.get_available_workspaces",
fake_get_available_workspaces,
)
with pytest.raises(ValueError, match="Multiple workspaces are available"):
await resolve_workspace_parameter(context=_ctx(_ContextState()))
@pytest.mark.asyncio
async def test_workspace_explicit_selection_by_tenant_id_or_name(monkeypatch):
from basic_memory.mcp.project_context import resolve_workspace_parameter
team_workspace = _workspace(
tenant_id="22222222-2222-2222-2222-222222222222",
workspace_type="organization",
slug="team",
name="Team",
role="editor",
)
workspaces = [
_workspace(
tenant_id="11111111-1111-1111-1111-111111111111",
workspace_type="personal",
slug="personal",
name="Personal",
role="owner",
is_default=True,
),
team_workspace,
]
async def fake_get_available_workspaces(context=None):
return workspaces
monkeypatch.setattr(
"basic_memory.mcp.project_context.get_available_workspaces",
fake_get_available_workspaces,
)
resolved_by_id = await resolve_workspace_parameter(workspace=team_workspace.tenant_id)
assert resolved_by_id.tenant_id == team_workspace.tenant_id
resolved_by_name = await resolve_workspace_parameter(workspace="team")
assert resolved_by_name.tenant_id == team_workspace.tenant_id
@pytest.mark.asyncio
async def test_workspace_invalid_selection_lists_choices(monkeypatch):
from basic_memory.mcp.project_context import resolve_workspace_parameter
workspaces = [
_workspace(
tenant_id="11111111-1111-1111-1111-111111111111",
workspace_type="personal",
slug="personal",
name="Personal",
role="owner",
is_default=True,
)
]
async def fake_get_available_workspaces(context=None):
return workspaces
monkeypatch.setattr(
"basic_memory.mcp.project_context.get_available_workspaces",
fake_get_available_workspaces,
)
with pytest.raises(ValueError, match="Workspace 'missing-workspace' was not found"):
await resolve_workspace_parameter(workspace="missing-workspace")
@pytest.mark.asyncio
async def test_workspace_ambiguous_type_selection_lists_matching_choices(monkeypatch):
from basic_memory.mcp.project_context import resolve_workspace_parameter
workspaces = [
_workspace(
tenant_id="11111111-1111-1111-1111-111111111111",
workspace_type="personal",
slug="personal",
name="Personal",
role="owner",
is_default=True,
),
_workspace(
tenant_id="22222222-2222-2222-2222-222222222222",
workspace_type="organization",
slug="team-alpha",
name="Team Alpha",
role="editor",
),
_workspace(
tenant_id="33333333-3333-3333-3333-333333333333",
workspace_type="organization",
slug="team-beta",
name="Team Beta",
role="owner",
),
]
async def fake_get_available_workspaces(context=None):
return workspaces
monkeypatch.setattr(
"basic_memory.mcp.project_context.get_available_workspaces",
fake_get_available_workspaces,
)
with pytest.raises(ValueError) as exc_info:
await resolve_workspace_parameter(workspace="organization")
message = str(exc_info.value)
assert "Workspace 'organization' matches multiple workspaces" in message
assert "workspace: team-alpha" in message
assert "workspace: team-beta" in message
assert "workspace: personal" not in message
@pytest.mark.asyncio
async def test_workspace_type_selection_ignores_cached_workspace_for_ambiguity(monkeypatch):
from basic_memory.mcp.project_context import resolve_workspace_parameter
cached_workspace = _workspace(
tenant_id="22222222-2222-2222-2222-222222222222",
workspace_type="organization",
slug="team-alpha",
name="Team Alpha",
role="editor",
)
workspaces = [
_workspace(
tenant_id="11111111-1111-1111-1111-111111111111",
workspace_type="personal",
slug="personal",
name="Personal",
role="owner",
is_default=True,
),
cached_workspace,
_workspace(
tenant_id="33333333-3333-3333-3333-333333333333",
workspace_type="organization",
slug="team-beta",
name="Team Beta",
role="owner",
),
]
context = _ContextState()
await context.set_state("active_workspace", cached_workspace.model_dump())
fetches = 0
async def fake_get_available_workspaces(context=None):
nonlocal fetches
fetches += 1
return workspaces
monkeypatch.setattr(
"basic_memory.mcp.project_context.get_available_workspaces",
fake_get_available_workspaces,
)
with pytest.raises(ValueError) as exc_info:
await resolve_workspace_parameter(workspace="organization", context=_ctx(context))
message = str(exc_info.value)
assert fetches == 1
assert "Workspace 'organization' matches multiple workspaces" in message
assert "workspace: team-alpha" in message
assert "workspace: team-beta" in message
@pytest.mark.asyncio
async def test_workspace_uses_cached_workspace_without_fetch(monkeypatch):
from basic_memory.mcp.project_context import resolve_workspace_parameter
cached_workspace = _workspace(
tenant_id="11111111-1111-1111-1111-111111111111",
workspace_type="personal",
slug="personal",
name="Personal",
role="owner",
is_default=True,
)
context = _ContextState()
await context.set_state("active_workspace", cached_workspace.model_dump())
async def fail_if_called(context=None): # pragma: no cover
raise AssertionError("Workspace fetch should not run when cache is available")
monkeypatch.setattr(
"basic_memory.mcp.project_context.get_available_workspaces",
fail_if_called,
)
resolved = await resolve_workspace_parameter(context=_ctx(context))
assert resolved.tenant_id == cached_workspace.tenant_id
@pytest.mark.asyncio
async def test_workspace_project_index_caches_and_invalidates(monkeypatch):
import basic_memory.mcp.project_context as project_context
from basic_memory.mcp.project_context import (
WorkspaceProjectEntry,
_ensure_workspace_project_index,
invalidate_workspace_project_index,
)
context = _ContextState()
personal = _workspace(
tenant_id="personal-tenant",
workspace_type="personal",
slug="personal",
name="Personal",
role="owner",
is_default=True,
)
acme = _workspace(
tenant_id="acme-tenant",
workspace_type="organization",
slug="acme",
name="Acme",
role="editor",
)
calls: list[str] = []
async def fake_get_available_workspaces(context=None):
return [personal, acme]
async def fake_fetch_workspace_project_entries(workspace, context=None):
calls.append(workspace.slug)
project = _project(
f"{workspace.slug}-notes",
id=len(calls),
external_id=f"{workspace.slug}-project-id",
)
return (WorkspaceProjectEntry(workspace=workspace, project=project),)
monkeypatch.setattr(project_context, "get_available_workspaces", fake_get_available_workspaces)
monkeypatch.setattr(
project_context,
"_fetch_workspace_project_entries",
fake_fetch_workspace_project_entries,
)
first = await _ensure_workspace_project_index(context=_ctx(context))
second = await _ensure_workspace_project_index(context=_ctx(context))
assert [entry.qualified_name for entry in first.entries] == [
"personal/personal-notes",
"acme/acme-notes",
]
assert second.entries == first.entries
assert calls == ["personal", "acme"]
await invalidate_workspace_project_index(_ctx(context))
await _ensure_workspace_project_index(context=_ctx(context))
assert calls == ["personal", "acme", "personal", "acme"]
@pytest.mark.asyncio
async def test_workspace_project_index_keeps_successes_when_workspace_fetch_fails(
monkeypatch,
):
import basic_memory.mcp.project_context as project_context
from basic_memory.mcp.project_context import (
WorkspaceProjectEntry,
_ensure_workspace_project_index,
resolve_workspace_project_identifier,
)
context = _ContextState()
personal = _workspace(
tenant_id="personal-tenant",
workspace_type="personal",
slug="personal",
name="Personal",
role="owner",
is_default=True,
)
acme = _workspace(
tenant_id="acme-tenant",
workspace_type="organization",
slug="acme",
name="Acme",
role="editor",
)
project = _project("Meeting Notes", id=7, external_id="personal-meeting-notes")
async def fake_get_available_workspaces(context=None):
return [personal, acme]
async def fake_fetch_workspace_project_entries(workspace, context=None):
if workspace.slug == "acme":
raise RuntimeError("acme unavailable")
return (WorkspaceProjectEntry(workspace=workspace, project=project),)
monkeypatch.setattr(project_context, "get_available_workspaces", fake_get_available_workspaces)
monkeypatch.setattr(
project_context,
"_fetch_workspace_project_entries",
fake_fetch_workspace_project_entries,
)
index = await _ensure_workspace_project_index(context=_ctx(context))
assert [entry.qualified_name for entry in index.entries] == ["personal/meeting-notes"]
assert [workspace.slug for workspace in index.failed_workspaces] == ["acme"]
resolved = await resolve_workspace_project_identifier(
"personal/meeting-notes",
context=_ctx(context),
)
assert resolved.project.external_id == "personal-meeting-notes"
with pytest.raises(ValueError, match="Use 'personal/meeting-notes'"):
await resolve_workspace_project_identifier(
"meeting-notes",
context=_ctx(context),
)
@pytest.mark.asyncio
async def test_workspace_project_index_raises_when_all_workspace_fetches_fail(
monkeypatch,
):
import basic_memory.mcp.project_context as project_context
from basic_memory.mcp.project_context import _ensure_workspace_project_index
personal = _workspace(
tenant_id="personal-tenant",
workspace_type="personal",
slug="personal",
name="Personal",
role="owner",
is_default=True,
)
async def fake_get_available_workspaces(context=None):
return [personal]
async def fake_fetch_workspace_project_entries(workspace, context=None):
raise RuntimeError("tenant unavailable")
monkeypatch.setattr(project_context, "get_available_workspaces", fake_get_available_workspaces)
monkeypatch.setattr(
project_context,
"_fetch_workspace_project_entries",
fake_fetch_workspace_project_entries,
)
with pytest.raises(ValueError, match="Unable to discover projects"):
await _ensure_workspace_project_index()
@pytest.mark.asyncio
async def test_fetch_workspace_project_entries_copies_default_project(monkeypatch):
import basic_memory.mcp.async_client as async_client
from basic_memory.mcp.project_context import _fetch_workspace_project_entries
from basic_memory.schemas.project_info import ProjectList
workspace = _workspace(
tenant_id="personal-tenant",
workspace_type="personal",
slug="personal",
name="Personal",
role="owner",
is_default=True,
)
project = _project("Default Notes", id=3, external_id="default-notes-id")
project_list = ProjectList(projects=[project], default_project="Default Notes")
@asynccontextmanager
async def fake_get_client(*args, **kwargs) -> AsyncIterator[object]:
yield object()
async def fake_list_projects(self):
return project_list
monkeypatch.setattr(async_client, "is_factory_mode", lambda: True)
monkeypatch.setattr(async_client, "get_client", fake_get_client)
monkeypatch.setattr(
"basic_memory.mcp.clients.project.ProjectClient.list_projects",
fake_list_projects,
)
entries = await _fetch_workspace_project_entries(workspace)
assert project.is_default is False
assert entries[0].project is not project
assert entries[0].project.is_default is True
@pytest.mark.asyncio
async def test_resolve_workspace_project_identifier_handles_qualified_and_collisions(monkeypatch):
import basic_memory.mcp.project_context as project_context
from basic_memory.mcp.project_context import (
WorkspaceProjectEntry,
_build_workspace_project_index,
resolve_workspace_project_identifier,
)
personal = _workspace(
tenant_id="personal-tenant",
workspace_type="personal",
slug="personal",
name="Personal",
role="owner",
is_default=True,
)
acme = _workspace(
tenant_id="acme-tenant",
workspace_type="organization",
slug="acme",
name="Acme",
role="editor",
)
entries = (
WorkspaceProjectEntry(
workspace=personal,
project=_project("Meeting Notes", id=1, external_id="personal-project-id"),
),
WorkspaceProjectEntry(
workspace=acme,
project=_project("Meeting Notes", id=2, external_id="acme-project-id"),
),
)
index = _build_workspace_project_index((personal, acme), entries)
async def fake_index(context=None):
return index
monkeypatch.setattr(project_context, "_ensure_workspace_project_index", fake_index)
resolved = await resolve_workspace_project_identifier("acme/meeting-notes")
assert resolved.workspace.slug == "acme"
assert resolved.project.external_id == "acme-project-id"
# Ambiguous name resolves to the default workspace (personal)
resolved = await resolve_workspace_project_identifier("meeting-notes")
assert resolved.workspace.slug == "personal"
assert resolved.project.external_id == "personal-project-id"
@pytest.mark.asyncio
async def test_detect_project_from_memory_url_prefix_resolves_workspace_slug(monkeypatch):
import basic_memory.mcp.project_context as project_context
from basic_memory.config import BasicMemoryConfig
from basic_memory.mcp.project_context import (
WorkspaceProjectEntry,
_build_workspace_project_index,
detect_project_from_memory_url_prefix,
)
personal = _workspace(
tenant_id="personal-tenant",
workspace_type="personal",
slug="personal",
name="Personal",
role="owner",
is_default=True,
)
team = _workspace(
tenant_id="team-tenant",
workspace_type="organization",
slug="team-paul",
name="Team Paul",
role="editor",
)
entries = (
WorkspaceProjectEntry(
workspace=personal,
project=_project("main", id=1, external_id="personal-main-id"),
),
WorkspaceProjectEntry(
workspace=team,
project=_project("main", id=2, external_id="team-main-id"),
),
)
index = _build_workspace_project_index((personal, team), entries)
async def fake_index(context=None):
return index
monkeypatch.setattr(project_context, "_ensure_workspace_project_index", fake_index)
monkeypatch.setattr("basic_memory.mcp.async_client.is_factory_mode", lambda: True)
resolved = await detect_project_from_memory_url_prefix(
"memory://team-paul/main/notes/foo",
BasicMemoryConfig(projects={}),
)
assert resolved == "team-paul/main"
@pytest.mark.asyncio
async def test_detect_project_from_memory_url_prefix_prefers_local_project_prefix(
monkeypatch,
):
import basic_memory.mcp.project_context as project_context
from basic_memory.config import BasicMemoryConfig, ProjectEntry
from basic_memory.mcp.project_context import detect_project_from_memory_url_prefix
async def fail_if_called(context=None): # pragma: no cover
raise AssertionError("Local project-prefixed memory URLs must not discover workspaces")
monkeypatch.setattr(project_context, "_ensure_workspace_project_index", fail_if_called)
resolved = await detect_project_from_memory_url_prefix(
"memory://main/notes/foo",
BasicMemoryConfig(
projects={"main": ProjectEntry(path="/tmp/main")},
cloud_api_key="bmc_test123",
),
)
assert resolved == "main"
@pytest.mark.asyncio
async def test_detect_project_from_memory_url_prefix_skips_workspace_discovery_for_local_config(
monkeypatch,
):
import basic_memory.mcp.project_context as project_context
from basic_memory.config import BasicMemoryConfig, ProjectEntry
from basic_memory.mcp.project_context import detect_project_from_memory_url_prefix
async def fail_if_called(context=None): # pragma: no cover
raise AssertionError("Saved cloud credentials must not force local workspace discovery")
monkeypatch.setattr(project_context, "_ensure_workspace_project_index", fail_if_called)
resolved = await detect_project_from_memory_url_prefix(
"memory://notes/foo/bar",
BasicMemoryConfig(
projects={"main": ProjectEntry(path="/tmp/main")},
cloud_api_key="bmc_test123",
),
)
assert resolved is None
@pytest.mark.asyncio
async def test_resolve_workspace_qualified_memory_url_ignores_workspace_project_miss(
monkeypatch,
):
import basic_memory.mcp.project_context as project_context
from basic_memory.mcp.project_context import (
WorkspaceProjectEntry,
_build_workspace_project_index,
resolve_workspace_qualified_memory_url,
)
workspace = _workspace(
tenant_id="main-tenant",
workspace_type="organization",
slug="main",
name="Main Workspace",
role="editor",
)
entries = (
WorkspaceProjectEntry(
workspace=workspace,
project=_project("research", id=1, external_id="research-project-id"),
),
)
index = _build_workspace_project_index((workspace,), entries)
async def fake_index(context=None):
return index
monkeypatch.setattr(project_context, "_ensure_workspace_project_index", fake_index)
resolved = await resolve_workspace_qualified_memory_url("memory://main/notes/foo")
assert resolved is None
@pytest.mark.asyncio
async def test_resolve_workspace_qualified_memory_url_fails_on_duplicate_project_permalink(
monkeypatch,
):
import basic_memory.mcp.project_context as project_context
from basic_memory.mcp.project_context import (
WorkspaceProjectEntry,
_build_workspace_project_index,
resolve_workspace_qualified_memory_url,
)
team = _workspace(
tenant_id="team-tenant",
workspace_type="organization",
slug="team-paul",
name="Team Paul",
role="editor",
)
entries = (
WorkspaceProjectEntry(
workspace=team,
project=_project("main", id=1, external_id="team-main-id-1"),
),
WorkspaceProjectEntry(
workspace=team,
project=_project("Main", id=2, external_id="team-main-id-2"),
),
)
index = _build_workspace_project_index((team,), entries)
async def fake_index(context=None):
return index
monkeypatch.setattr(project_context, "_ensure_workspace_project_index", fake_index)
with pytest.raises(ValueError, match="matched multiple projects"):
await resolve_workspace_qualified_memory_url("memory://team-paul/main/notes/foo")
@pytest.mark.asyncio
async def test_resolve_workspace_qualified_memory_url_uses_personal_canonical_path(
config_manager,
monkeypatch,
):
import basic_memory.mcp.project_context as project_context
from basic_memory.mcp.project_context import (
WorkspaceProjectEntry,
_build_workspace_project_index,
resolve_workspace_qualified_memory_url,
)
config = config_manager.load_config()
config.permalinks_include_project = True
config_manager.save_config(config)
personal = _workspace(
tenant_id="personal-tenant",
workspace_type="personal",
slug="personal",
name="Personal",
role="owner",
is_default=True,
)
entries = (
WorkspaceProjectEntry(
workspace=personal,
project=_project("main", id=1, external_id="personal-main-id"),
),
)
index = _build_workspace_project_index((personal,), entries)
async def fake_index(context=None):
return index
monkeypatch.setattr(project_context, "_ensure_workspace_project_index", fake_index)
resolved = await resolve_workspace_qualified_memory_url("memory://personal/main/notes/foo")
assert resolved is not None
assert resolved.canonical_path == "personal/main/notes/foo"
@pytest.mark.asyncio
async def test_resolve_workspace_qualified_memory_url_keeps_org_canonical_path_without_project_prefix(
config_manager,
monkeypatch,
):
import basic_memory.mcp.project_context as project_context
from basic_memory.mcp.project_context import (
WorkspaceProjectEntry,
_build_workspace_project_index,
resolve_workspace_qualified_memory_url,
)
config = config_manager.load_config()
config.permalinks_include_project = False
config_manager.save_config(config)
team = _workspace(
tenant_id="team-tenant",
workspace_type="organization",
slug="team-paul",
name="Team Paul",
role="editor",
)
entries = (
WorkspaceProjectEntry(
workspace=team,
project=_project("main", id=1, external_id="team-main-id"),
),
)
index = _build_workspace_project_index((team,), entries)
async def fake_index(context=None):
return index
monkeypatch.setattr(project_context, "_ensure_workspace_project_index", fake_index)
resolved = await resolve_workspace_qualified_memory_url("memory://team-paul/main/notes/foo")
assert resolved is not None
assert resolved.canonical_path == "team-paul/main/notes/foo"
@pytest.mark.asyncio
async def test_get_project_client_routes_duplicate_project_through_workspace_slug(
config_manager,
monkeypatch,
):
from basic_memory.mcp.project_context import (
WorkspaceProjectEntry,
get_project_client,
)
config = config_manager.load_config()
config.projects = {}
config.cloud_api_key = "bmc_test123"
config_manager.save_config(config)
_workspace(
tenant_id="personal-tenant",
workspace_type="personal",
slug="personal",
name="Personal",
role="owner",
is_default=True,
)
team = _workspace(
tenant_id="team-tenant",
workspace_type="organization",
slug="team-paul",