Repository navigation
Expand file tree
/
Copy pathmain_test.go
More file actions
5213 lines (4654 loc) · 177 KB
/
Copy pathmain_test.go
File metadata and controls
5213 lines (4654 loc) · 177 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
// PARALLEL SAFETY: Tests in this file MUST NOT use t.Parallel().
// They mutate the package-level logger output for log assertions.
// Some tests (TestEnsureOllama_BinaryNotFound) also manipulate PATH.
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime/debug"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/charmbracelet/log"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/unbound-force/dewey/v3/curate"
"github.com/unbound-force/dewey/v3/embed"
"github.com/unbound-force/dewey/v3/llm"
"github.com/unbound-force/dewey/v3/store"
"github.com/unbound-force/dewey/v3/tools"
"github.com/unbound-force/dewey/v3/types"
)
// --- resolveBackendType tests (T014) ---
// TestResolveBackendType_FlagValue verifies the flag value is returned
// when non-empty, regardless of environment variable state.
func TestResolveBackendType_FlagValue(t *testing.T) {
t.Setenv("DEWEY_BACKEND", "obsidian")
got := resolveBackendType("logseq")
if got != "logseq" {
t.Errorf("resolveBackendType(%q) = %q, want %q", "logseq", got, "logseq")
}
}
// TestResolveBackendType_EnvFallback verifies the DEWEY_BACKEND environment
// variable is used when the flag value is empty.
func TestResolveBackendType_EnvFallback(t *testing.T) {
t.Setenv("DEWEY_BACKEND", "obsidian")
got := resolveBackendType("")
if got != "obsidian" {
t.Errorf("resolveBackendType(%q) = %q, want %q", "", got, "obsidian")
}
}
// TestResolveBackendType_DefaultObsidian verifies "obsidian" is returned
// when both flag value and environment variable are empty.
func TestResolveBackendType_DefaultObsidian(t *testing.T) {
t.Setenv("DEWEY_BACKEND", "")
got := resolveBackendType("")
if got != "obsidian" {
t.Errorf("resolveBackendType(%q) = %q, want %q", "", got, "obsidian")
}
}
// TestResolveBackendType_ArbitraryValue verifies arbitrary backend types
// are passed through without validation (validation happens in executeServe).
func TestResolveBackendType_ArbitraryValue(t *testing.T) {
got := resolveBackendType("custom-backend")
if got != "custom-backend" {
t.Errorf("resolveBackendType(%q) = %q, want %q", "custom-backend", got, "custom-backend")
}
}
// TestResolveBackendType_Table verifies all resolution precedence rules
// in a single table-driven test.
func TestResolveBackendType_Table(t *testing.T) {
tests := []struct {
name string
flagValue string
envValue string
want string
}{
{"flag takes precedence", "obsidian", "logseq", "obsidian"},
{"env fallback", "", "obsidian", "obsidian"},
{"default obsidian", "", "", "obsidian"},
{"flag with no env", "obsidian", "", "obsidian"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("DEWEY_BACKEND", tc.envValue)
got := resolveBackendType(tc.flagValue)
if got != tc.want {
t.Errorf("resolveBackendType(%q) with DEWEY_BACKEND=%q = %q, want %q",
tc.flagValue, tc.envValue, got, tc.want)
}
})
}
}
// --- initLogseqBackend tests (T014) ---
// TestInitLogseqBackend_ReturnsNonNil verifies initLogseqBackend returns
// a non-nil backend. The function creates a Logseq client and calls
// checkGraphVersionControl, which is best-effort and silently returns
// when the API is unreachable (no Logseq running in test).
func TestInitLogseqBackend_ReturnsNonNil(t *testing.T) {
// Suppress log output from checkGraphVersionControl's HTTP error.
var logBuf bytes.Buffer
logger.SetOutput(&logBuf)
defer logger.SetOutput(os.Stderr)
b := initLogseqBackend()
if b == nil {
t.Fatal("initLogseqBackend() returned nil")
}
}
// TestInitLogseqBackend_ImplementsBackend verifies the returned value
// satisfies the backend.Backend interface by checking it has the
// expected methods (compile-time check is implicit via return type,
// but this validates runtime behavior).
func TestInitLogseqBackend_ImplementsBackend(t *testing.T) {
var logBuf bytes.Buffer
logger.SetOutput(&logBuf)
defer logger.SetOutput(os.Stderr)
b := initLogseqBackend()
// The returned backend should be a *client.Client which implements
// backend.Backend and backend.HasDataScript.
if _, ok := b.(interface{ Ping(context.Context) error }); !ok {
t.Error("initLogseqBackend() result does not have Ping method")
}
}
// --- executeServe tests (T014) ---
// TestExecuteServe_UnknownBackend verifies executeServe returns an error
// for an unknown backend type.
func TestExecuteServe_UnknownBackend(t *testing.T) {
err := executeServe(false, "unknown-backend", "", "", "", false)
if err == nil {
t.Fatal("executeServe with unknown backend should return error")
}
want := `unknown backend "unknown-backend" (use logseq or obsidian)`
if got := err.Error(); got != want {
t.Errorf("error = %q, want %q", got, want)
}
}
// TestExecuteServe_ObsidianRequiresVault verifies executeServe returns
// an error when obsidian backend is selected without vault path.
func TestExecuteServe_ObsidianRequiresVault(t *testing.T) {
t.Setenv("OBSIDIAN_VAULT_PATH", "")
err := executeServe(false, "obsidian", "", "", "", false)
if err == nil {
t.Fatal("executeServe with obsidian and no vault path should return error")
}
if !strings.Contains(err.Error(), "--vault or OBSIDIAN_VAULT_PATH required") {
t.Errorf("error = %q, want vault path required message", err.Error())
}
}
// --- runServer tests (T014) ---
// TestRunServer_HTTPTransport_InvalidAddr verifies runServer returns an
// error when given an invalid HTTP address that cannot be bound.
func TestRunServer_HTTPTransport_InvalidAddr(t *testing.T) {
// Create a minimal server — we just need it to attempt ListenAndServe.
srv := mcp.NewServer(
&mcp.Implementation{Name: "test", Version: "0.0.1"},
nil,
)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Use an address that will fail — port 0 on an invalid host.
err := runServer(ctx, srv, "invalid-host:99999")
if err == nil {
t.Fatal("runServer with invalid address should return error")
}
}
// TestRunServer_HTTPTransport_ContextCancellation verifies that the HTTP
// server shuts down gracefully when the context is cancelled.
func TestRunServer_HTTPTransport_ContextCancellation(t *testing.T) {
srv := mcp.NewServer(
&mcp.Implementation{Name: "test", Version: "0.0.1"},
nil,
)
// Find a free port.
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("net.Listen: %v", err)
}
addr := listener.Addr().String()
_ = listener.Close()
ctx, cancel := context.WithCancel(context.Background())
errCh := make(chan error, 1)
go func() {
errCh <- runServer(ctx, srv, addr)
}()
// Give the server a moment to start.
time.Sleep(50 * time.Millisecond)
// Cancel context to trigger graceful shutdown.
cancel()
select {
case err := <-errCh:
// Should return nil (ErrServerClosed is swallowed by runServer).
if err != nil {
t.Errorf("runServer returned error after context cancellation: %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("runServer did not return after context cancellation (timeout)")
}
}
// --- initObsidianBackend tests (T014) ---
// TestInitObsidianBackend_MissingVaultPath verifies initObsidianBackend
// returns an error when no vault path is provided via flag or env var.
func TestInitObsidianBackend_MissingVaultPath(t *testing.T) {
t.Setenv("OBSIDIAN_VAULT_PATH", "")
_, _, _, _, err := initObsidianBackend("", "daily notes", false)
if err == nil {
t.Fatal("initObsidianBackend with no vault path should return error")
}
if !strings.Contains(err.Error(), "--vault or OBSIDIAN_VAULT_PATH required") {
t.Errorf("error = %q, want vault path required message", err.Error())
}
}
// TestInitObsidianBackend_EnvVaultPath verifies initObsidianBackend uses
// the OBSIDIAN_VAULT_PATH environment variable when the flag is empty.
func TestInitObsidianBackend_EnvVaultPath(t *testing.T) {
tmpDir := t.TempDir()
t.Setenv("OBSIDIAN_VAULT_PATH", tmpDir)
// Suppress log output from embedder availability check.
var logBuf bytes.Buffer
logger.SetOutput(&logBuf)
defer logger.SetOutput(os.Stderr)
// Pass noEmbeddings=true because Ollama is not running in test env.
b, opts, cleanup, _, err := initObsidianBackend("", "daily notes", true)
if err != nil {
t.Fatalf("initObsidianBackend failed: %v", err)
}
defer cleanup()
if b == nil {
t.Fatal("initObsidianBackend returned nil backend")
}
// With noEmbeddings=true, no embedder option is added.
// opts may be empty (no store, no embedder).
_ = opts
}
// TestInitObsidianBackend_WithPersistentStore verifies that when .uf/dewey/
// exists in the vault path, a persistent store is initialized and included
// in the server options.
func TestInitObsidianBackend_WithPersistentStore(t *testing.T) {
tmpDir := t.TempDir()
// Create .uf/dewey/ directory to trigger store initialization.
deweyDir := filepath.Join(tmpDir, deweyWorkspaceDir)
if err := os.MkdirAll(deweyDir, 0o755); err != nil {
t.Fatalf("mkdir .uf/dewey: %v", err)
}
var logBuf bytes.Buffer
logger.SetOutput(&logBuf)
defer logger.SetOutput(os.Stderr)
// Pass noEmbeddings=true because Ollama is not running in test env.
b, opts, cleanup, _, err := initObsidianBackend(tmpDir, "daily notes", true)
if err != nil {
t.Fatalf("initObsidianBackend failed: %v", err)
}
defer cleanup()
if b == nil {
t.Fatal("initObsidianBackend returned nil backend")
}
// With .uf/dewey/ present and noEmbeddings=true, should have at least 1 option (persistent store).
if len(opts) < 1 {
t.Errorf("expected at least 1 server option (store), got %d", len(opts))
}
}
// TestInitObsidianBackend_EmbedderEnvConfig verifies that the DEWEY_EMBEDDING_MODEL
// and DEWEY_EMBEDDING_ENDPOINT env vars are used when set, and default values are
// used when unset. The function always creates an embedder (graceful degradation).
func TestInitObsidianBackend_EmbedderEnvConfig(t *testing.T) {
tmpDir := t.TempDir()
// Set custom embedding config via env vars.
t.Setenv("OBSIDIAN_VAULT_PATH", "")
t.Setenv("DEWEY_EMBEDDING_MODEL", "custom-model:latest")
t.Setenv("DEWEY_EMBEDDING_ENDPOINT", "http://localhost:99999")
var logBuf bytes.Buffer
logger.SetOutput(&logBuf)
defer logger.SetOutput(os.Stderr)
// Pass noEmbeddings=true because Ollama is not running in test env
// (custom endpoint http://localhost:99999 is unreachable).
b, _, cleanup, _, err := initObsidianBackend(tmpDir, "daily notes", true)
if err != nil {
t.Fatalf("initObsidianBackend failed: %v", err)
}
defer cleanup()
if b == nil {
t.Fatal("initObsidianBackend returned nil backend")
}
// Log output should mention embeddings disabled.
logOutput := logBuf.String()
if logOutput == "" {
t.Error("expected log output about embeddings disabled")
}
}
// TestInitObsidianBackend_WithMarkdownFiles verifies that initObsidianBackend
// returns quickly without indexing (spec 012, T003), and that calling the
// returned deferredIndex function populates the in-memory index.
func TestInitObsidianBackend_WithMarkdownFiles(t *testing.T) {
tmpDir := t.TempDir()
// Create some test markdown files.
if err := os.WriteFile(tmpDir+"/test-page.md", []byte("# Test Page\n\nContent."), 0o644); err != nil {
t.Fatalf("WriteFile: %v", err)
}
var logBuf bytes.Buffer
logger.SetOutput(&logBuf)
defer logger.SetOutput(os.Stderr)
// Pass noEmbeddings=true because Ollama is not running in test env.
initStart := time.Now()
b, _, cleanup, deferredIndex, err := initObsidianBackend(tmpDir, "daily notes", true)
initElapsed := time.Since(initStart)
if err != nil {
t.Fatalf("initObsidianBackend failed: %v", err)
}
defer cleanup()
// T006: Verify initObsidianBackend returns quickly (< 1 second) because
// indexing is deferred. The function only resolves paths, opens the store,
// and creates the vault client — no file walking or indexing.
if initElapsed >= 1*time.Second {
t.Errorf("initObsidianBackend took %v, want < 1s (indexing should be deferred)", initElapsed)
}
// T006: Verify pages are NOT indexed immediately after initObsidianBackend.
// The in-memory index should be empty because indexing is deferred.
pagesBeforeIndex, err := b.GetAllPages(context.Background())
if err != nil {
t.Fatalf("GetAllPages (before deferred index): %v", err)
}
if len(pagesBeforeIndex) != 0 {
t.Errorf("expected 0 pages before deferredIndex, got %d", len(pagesBeforeIndex))
}
// T006: Verify deferredIndex is non-nil and calling it populates the index.
if deferredIndex == nil {
t.Fatal("deferredIndex should be non-nil")
}
if err := deferredIndex(); err != nil {
t.Fatalf("deferredIndex failed: %v", err)
}
// Verify pages were indexed by querying through the backend.
pages, err := b.GetAllPages(context.Background())
if err != nil {
t.Fatalf("GetAllPages: %v", err)
}
if len(pages) == 0 {
t.Error("expected at least 1 page after deferredIndex")
}
// Verify the specific page is accessible.
page, err := b.GetPage(context.Background(), "test-page")
if err != nil {
t.Fatalf("GetPage: %v", err)
}
if page == nil {
t.Error("test-page should be found after deferredIndex")
}
}
// TestInitObsidianBackend_FlagTakesPrecedence verifies that the vaultPath
// flag takes precedence over the OBSIDIAN_VAULT_PATH env var.
func TestInitObsidianBackend_FlagTakesPrecedence(t *testing.T) {
tmpDir := t.TempDir()
// Set env to a different (non-existent) path — flag should take precedence.
t.Setenv("OBSIDIAN_VAULT_PATH", "/nonexistent/should-not-be-used")
var logBuf bytes.Buffer
logger.SetOutput(&logBuf)
defer logger.SetOutput(os.Stderr)
// Pass noEmbeddings=true because Ollama is not running in test env.
b, _, cleanup, _, err := initObsidianBackend(tmpDir, "daily notes", true)
if err != nil {
t.Fatalf("initObsidianBackend failed: %v", err)
}
defer cleanup()
if b == nil {
t.Fatal("initObsidianBackend returned nil backend")
}
}
// --- --no-embeddings tests ---
// TestInitObsidianBackend_NoEmbeddings_Succeeds verifies that serve starts
// without error when Ollama is unavailable and noEmbeddings is true.
func TestInitObsidianBackend_NoEmbeddings_Succeeds(t *testing.T) {
tmpDir := t.TempDir()
// Point to an unreachable Ollama endpoint.
t.Setenv("DEWEY_EMBEDDING_ENDPOINT", "http://localhost:99999")
var logBuf bytes.Buffer
logger.SetOutput(&logBuf)
defer logger.SetOutput(os.Stderr)
b, _, cleanup, _, err := initObsidianBackend(tmpDir, "daily notes", true)
if err != nil {
t.Fatalf("initObsidianBackend with noEmbeddings=true should succeed, got: %v", err)
}
defer cleanup()
if b == nil {
t.Fatal("initObsidianBackend returned nil backend")
}
// Log should mention embeddings disabled.
logOutput := logBuf.String()
if !strings.Contains(logOutput, "embeddings disabled") {
t.Errorf("log should mention embeddings disabled, got:\n%s", logOutput)
}
}
// TestInitObsidianBackend_GracefulDegradation_WhenOllamaUnavailable verifies that
// serve succeeds in keyword-only mode when Ollama is unavailable (not running at
// a remote endpoint). This tests the 007-ollama-autostart graceful degradation:
// instead of a hard error, Dewey logs the unavailability and proceeds without
// embeddings.
func TestInitObsidianBackend_GracefulDegradation_WhenOllamaUnavailable(t *testing.T) {
tmpDir := t.TempDir()
// Point to a remote (non-local) unreachable endpoint so ensureOllama
// skips the auto-start attempt and returns OllamaUnavailable immediately.
t.Setenv("DEWEY_EMBEDDING_ENDPOINT", "http://remote-host:99999")
t.Setenv("DEWEY_EMBEDDING_MODEL", "granite-embedding:30m")
var logBuf bytes.Buffer
logger.SetOutput(&logBuf)
defer logger.SetOutput(os.Stderr)
_, _, cleanup, _, err := initObsidianBackend(tmpDir, "daily notes", false)
if err != nil {
t.Fatalf("initObsidianBackend should succeed with graceful degradation, got error: %v", err)
}
if cleanup != nil {
defer cleanup()
}
logOutput := logBuf.String()
// Should log that semantic search is unavailable.
if !strings.Contains(logOutput, "semantic search unavailable") {
t.Errorf("log should contain 'semantic search unavailable', got: %q", logOutput)
}
// Should log the ollama state as unavailable.
if !strings.Contains(logOutput, "unavailable") {
t.Errorf("log should contain 'unavailable' state, got: %q", logOutput)
}
}
// newMockOllamaServer returns an httptest.Server that responds to /api/tags.
// When models is empty, Available() returns false (model not pulled).
// When models contains entries, Available() returns true.
func newMockOllamaServer(models string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/tags" {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"models":[` + models + `]}`))
return
}
http.NotFound(w, r)
}))
}
// assertDegradationLog checks that log output contains the expected
// model name, endpoint, pull instructions, and semantic search warning.
func assertDegradationLog(t *testing.T, logOutput, endpoint string) {
t.Helper()
checks := []struct {
substr string
desc string
}{
{"granite-embedding:30m", "model name"},
{endpoint, "endpoint"},
{"ollama pull", "pull instructions"},
{"semantic search is unavailable", "semantic search warning"},
{"embedding model not available", "degradation warning"},
}
for _, c := range checks {
if !strings.Contains(logOutput, c.substr) {
t.Errorf("log should contain %s %q, got: %q", c.desc, c.substr, logOutput)
}
}
}
// TestInitObsidianBackend_DegradesToKeywordModeWhenModelMissing verifies that
// serve succeeds in keyword-only mode when Ollama is reachable but the
// requested embedding model has not been pulled (design decision D3).
func TestInitObsidianBackend_DegradesToKeywordModeWhenModelMissing(t *testing.T) {
srv := newMockOllamaServer("") // empty models list
defer srv.Close()
tmpDir := t.TempDir()
t.Setenv("DEWEY_EMBEDDING_ENDPOINT", srv.URL)
t.Setenv("DEWEY_EMBEDDING_MODEL", "granite-embedding:30m")
var logBuf bytes.Buffer
logger.SetOutput(&logBuf)
defer logger.SetOutput(os.Stderr)
be, _, cleanup, _, err := initObsidianBackend(tmpDir, "daily notes", false)
if err != nil {
t.Fatalf("initObsidianBackend should succeed with graceful degradation, got error: %v", err)
}
if cleanup != nil {
defer cleanup()
}
if be == nil {
t.Fatal("expected non-nil backend, got nil")
}
assertDegradationLog(t, logBuf.String(), srv.URL)
}
// TestCreateIndexEmbedder_DegradesToKeywordModeWhenModelMissing verifies that
// createIndexEmbedder returns (nil, nil) when Ollama is reachable but the
// embedding model has not been pulled (design decision D3, task 2.4).
func TestCreateIndexEmbedder_DegradesToKeywordModeWhenModelMissing(t *testing.T) {
srv := newMockOllamaServer("") // empty models list
defer srv.Close()
t.Setenv("DEWEY_EMBEDDING_ENDPOINT", srv.URL)
t.Setenv("DEWEY_EMBEDDING_MODEL", "granite-embedding:30m")
var logBuf bytes.Buffer
logger.SetOutput(&logBuf)
defer logger.SetOutput(os.Stderr)
embedder, err := createIndexEmbedder(false)
if err != nil {
t.Fatalf("createIndexEmbedder should succeed with graceful degradation, got error: %v", err)
}
if embedder != nil {
t.Fatal("expected nil embedder (keyword-only mode), got non-nil")
}
assertDegradationLog(t, logBuf.String(), srv.URL)
}
// TestRunDoctorChecks_ResolvesOllamaHostEndpoint verifies that dewey doctor
// uses the resolved OLLAMA_HOST endpoint in its Embedding Layer output
// when no config.yaml or DEWEY_EMBEDDING_ENDPOINT is set.
func TestRunDoctorChecks_ResolvesOllamaHostEndpoint(t *testing.T) {
srv := newMockOllamaServer(`{"name":"granite-embedding:30m"}`)
defer srv.Close()
tmpDir := t.TempDir()
deweyDir := filepath.Join(tmpDir, ".uf", "dewey")
if err := os.MkdirAll(deweyDir, 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("OLLAMA_HOST", srv.URL)
t.Setenv("DEWEY_EMBEDDING_ENDPOINT", "")
t.Setenv("DEWEY_EMBEDDING_MODEL", "")
var buf bytes.Buffer
runDoctorChecks(&buf, tmpDir)
output := buf.String()
if !strings.Contains(output, srv.URL) {
t.Errorf("doctor output should contain OLLAMA_HOST endpoint %q, got:\n%s", srv.URL, output)
}
}
// TestRunDoctorChecks_SynthesisOllamaProvider verifies the Synthesis Layer
// section reports connectivity and model availability for an Ollama synthesis
// provider, using an independent endpoint from the embedding layer.
func TestRunDoctorChecks_SynthesisOllamaProvider(t *testing.T) {
// Create separate mock servers for embedding and synthesis to verify
// dual-endpoint independence (triage guidance #6).
embedSrv := newMockOllamaServer(`{"name":"granite-embedding:30m"}`)
defer embedSrv.Close()
synthModel := "llama3.2:3b"
synthSrv := newMockOllamaServer(`{"name":"` + synthModel + `"}`)
defer synthSrv.Close()
tmpDir := t.TempDir()
deweyDir := filepath.Join(tmpDir, ".uf", "dewey")
if err := os.MkdirAll(deweyDir, 0o755); err != nil {
t.Fatal(err)
}
// Isolate from developer's global config (~/.config/dewey/config.yaml).
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
// Write config.yaml with ollama synthesis provider pointing to synthSrv.
configYAML := "synthesis:\n provider: ollama\n model: " + synthModel + "\n endpoint: " + synthSrv.URL + "\n"
if err := os.WriteFile(filepath.Join(deweyDir, "config.yaml"), []byte(configYAML), 0o644); err != nil {
t.Fatalf("write config.yaml: %v", err)
}
// Set embedding endpoint to a different server.
t.Setenv("DEWEY_EMBEDDING_ENDPOINT", embedSrv.URL)
t.Setenv("DEWEY_SYNTHESIS_ENDPOINT", "")
t.Setenv("OLLAMA_HOST", "")
var buf bytes.Buffer
runDoctorChecks(&buf, tmpDir)
output := buf.String()
// Verify Synthesis Layer section exists with the correct endpoint.
if !strings.Contains(output, "Synthesis Layer") {
t.Errorf("doctor should include Synthesis Layer section, got:\n%s", output)
}
if !strings.Contains(output, synthSrv.URL) {
t.Errorf("doctor synthesis section should show synthesis endpoint %q, got:\n%s", synthSrv.URL, output)
}
if !strings.Contains(output, synthModel) {
t.Errorf("doctor synthesis section should show model %q, got:\n%s", synthModel, output)
}
// Verify embedding endpoint is independent — embedding section shows embedSrv.URL.
if !strings.Contains(output, embedSrv.URL) {
t.Errorf("doctor embedding section should show embedding endpoint %q, got:\n%s", embedSrv.URL, output)
}
}
// TestRunDoctorChecks_SynthesisOllamaUnreachable verifies the Synthesis Layer
// section reports WARN when the Ollama synthesis endpoint is unreachable and
// skips the model availability check.
func TestRunDoctorChecks_SynthesisOllamaUnreachable(t *testing.T) {
// Create a server and immediately close it to get an unreachable endpoint.
unreachableSrv := newMockOllamaServer("")
unreachableURL := unreachableSrv.URL
unreachableSrv.Close()
tmpDir := t.TempDir()
deweyDir := filepath.Join(tmpDir, ".uf", "dewey")
if err := os.MkdirAll(deweyDir, 0o755); err != nil {
t.Fatal(err)
}
synthModel := "llama3.2:3b"
configYAML := "synthesis:\n provider: ollama\n model: " + synthModel + "\n endpoint: " + unreachableURL + "\n"
if err := os.WriteFile(filepath.Join(deweyDir, "config.yaml"), []byte(configYAML), 0o644); err != nil {
t.Fatalf("write config.yaml: %v", err)
}
t.Setenv("DEWEY_SYNTHESIS_ENDPOINT", "")
t.Setenv("DEWEY_EMBEDDING_ENDPOINT", "")
t.Setenv("OLLAMA_HOST", "")
// Isolate from developer's global config (~/.config/dewey/config.yaml).
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
var buf bytes.Buffer
runDoctorChecks(&buf, tmpDir)
output := buf.String()
if !strings.Contains(output, "Synthesis Layer") {
t.Errorf("doctor should include Synthesis Layer section, got:\n%s", output)
}
// Model check should be skipped when Ollama is not reachable.
if !strings.Contains(output, "skipped (ollama not reachable)") {
t.Errorf("doctor should report model check skipped when Ollama unreachable, got:\n%s", output)
}
}
// --- OllamaState tests (T011) ---
// TestOllamaState_String verifies the String() method returns the correct
// human-readable label for each OllamaState value, including unknown states.
func TestOllamaState_String(t *testing.T) {
tests := []struct {
state OllamaState
want string
}{
{OllamaExternal, "external"},
{OllamaManaged, "managed"},
{OllamaUnavailable, "unavailable"},
{OllamaState(99), "unknown"},
}
for _, tc := range tests {
t.Run(tc.want, func(t *testing.T) {
got := tc.state.String()
if got != tc.want {
t.Errorf("OllamaState(%d).String() = %q, want %q", int(tc.state), got, tc.want)
}
})
}
}
// --- isLocalEndpoint tests (T012) ---
// TestIsLocalEndpoint verifies that isLocalEndpoint correctly identifies
// local vs remote endpoints across various URL formats.
func TestIsLocalEndpoint(t *testing.T) {
tests := []struct {
endpoint string
want bool
}{
{"http://localhost:11434", true},
{"http://127.0.0.1:11434", true},
{"http://[::1]:11434", true},
{"http://gpu-server:11434", false},
{"http://192.168.1.100:11434", false},
{"", true}, // empty hostname defaults to localhost
{"://bad", false}, // malformed URL
}
for _, tc := range tests {
t.Run(tc.endpoint, func(t *testing.T) {
got := isLocalEndpoint(tc.endpoint)
if got != tc.want {
t.Errorf("isLocalEndpoint(%q) = %v, want %v", tc.endpoint, got, tc.want)
}
})
}
}
// --- ollamaHealthCheck tests (T013) ---
// TestOllamaHealthCheck_Healthy verifies that ollamaHealthCheck returns true
// when the endpoint responds with HTTP 200 on /api/tags.
func TestOllamaHealthCheck_Healthy(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
if !ollamaHealthCheck(server.URL) {
t.Errorf("ollamaHealthCheck(%q) = false, want true", server.URL)
}
}
// TestOllamaHealthCheck_Unreachable verifies that ollamaHealthCheck returns
// false when the endpoint is not reachable (port 0 = no listener).
func TestOllamaHealthCheck_Unreachable(t *testing.T) {
if ollamaHealthCheck("http://127.0.0.1:0") {
t.Error("ollamaHealthCheck(unreachable) = true, want false")
}
}
// --- ensureOllama tests (T014-T018) ---
// mockStarter records whether Start() was called, for testing ensureOllama
// without launching real subprocesses.
type mockStarter struct {
called bool
}
func (m *mockStarter) Start() error {
m.called = true
return nil
}
// TestEnsureOllama_AlreadyRunning verifies that when Ollama is already
// reachable, ensureOllama returns OllamaExternal without calling Start().
func TestEnsureOllama_AlreadyRunning(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
mock := &mockStarter{}
state, err := ensureOllama(server.URL, true, mock)
if err != nil {
t.Fatalf("ensureOllama() error = %v, want nil", err)
}
if state != OllamaExternal {
t.Errorf("ensureOllama() state = %v, want OllamaExternal", state)
}
if mock.called {
t.Error("Start() should not be called when Ollama is already running")
}
}
// TestEnsureOllama_BinaryNotFound verifies that ensureOllama returns
// OllamaUnavailable when the ollama binary is not in PATH.
// PARALLEL SAFETY: Manipulates PATH, must not run in parallel.
func TestEnsureOllama_BinaryNotFound(t *testing.T) {
// Save and restore PATH.
origPath := os.Getenv("PATH")
t.Setenv("PATH", "")
defer func() { _ = os.Setenv("PATH", origPath) }()
mock := &mockStarter{}
state, err := ensureOllama("http://localhost:99999", true, mock)
if err != nil {
t.Fatalf("ensureOllama() error = %v, want nil", err)
}
if state != OllamaUnavailable {
t.Errorf("ensureOllama() state = %v, want OllamaUnavailable", state)
}
if mock.called {
t.Error("Start() should not be called when binary is not in PATH")
}
}
// TestEnsureOllama_RemoteEndpoint verifies that ensureOllama does not attempt
// to start Ollama when the endpoint is a remote host (non-local).
func TestEnsureOllama_RemoteEndpoint(t *testing.T) {
mock := &mockStarter{}
state, err := ensureOllama("http://gpu-server:11434", true, mock)
if err != nil {
t.Fatalf("ensureOllama() error = %v, want nil", err)
}
if state != OllamaUnavailable {
t.Errorf("ensureOllama() state = %v, want OllamaUnavailable", state)
}
if mock.called {
t.Error("Start() should not be called for remote endpoints")
}
}
// TestEnsureOllama_StartSuccess verifies that ensureOllama starts Ollama
// and returns OllamaManaged when the binary is available and the server
// becomes ready after starting.
func TestEnsureOllama_StartSuccess(t *testing.T) {
// Skip if ollama binary is not in PATH — this test requires LookPath to succeed.
if _, err := exec.LookPath("ollama"); err != nil {
t.Skip("ollama not in PATH")
}
// Counter-based server: first health check fails (503), subsequent ones succeed (200).
// This simulates Ollama starting up after the subprocess is launched.
var calls int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if atomic.AddInt32(&calls, 1) <= 1 {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
mock := &mockStarter{}
state, err := ensureOllama(server.URL, true, mock)
if err != nil {
t.Fatalf("ensureOllama() error = %v, want nil", err)
}
if state != OllamaManaged {
t.Errorf("ensureOllama() state = %v, want OllamaManaged", state)
}
if !mock.called {
t.Error("Start() should be called when Ollama needs to be started")
}
}
// TestEnsureOllama_AutoStartDisabled verifies that ensureOllama returns
// OllamaUnavailable without panicking when autoStart is false and the
// starter is nil (doctor mode).
func TestEnsureOllama_AutoStartDisabled(t *testing.T) {
state, err := ensureOllama("http://localhost:99999", false, nil)
if err != nil {
t.Fatalf("ensureOllama() error = %v, want nil", err)
}
if state != OllamaUnavailable {
t.Errorf("ensureOllama() state = %v, want OllamaUnavailable", state)
}
}
// --- Background indexing integration tests (T008, spec 012) ---
// TestBackgroundIndex_ServerStartsBeforeIndexing verifies the core split
// introduced by spec 012: initObsidianBackend() returns quickly without
// indexing, and the returned deferredIndex function performs the slow
// operations (indexVault, LoadExternalPages, Watch) when called later.
//
// This proves the MCP server can start accepting connections before the
// vault is fully indexed — the key user story (US1).
//
// PARALLEL SAFETY: Mutates package-level logger output for log assertions.
func TestBackgroundIndex_ServerStartsBeforeIndexing(t *testing.T) {
tmpDir := t.TempDir()
// Create multiple markdown files to simulate a real vault.
files := map[string]string{
"page-one.md": "# Page One\n\nFirst page content.\n\n[[page-two]]",
"page-two.md": "# Page Two\n\nSecond page with a [[page-one]] backlink.",
"page-three.md": "# Page Three\n\nThird page, no links.",
}
for name, content := range files {
if err := os.WriteFile(filepath.Join(tmpDir, name), []byte(content), 0o644); err != nil {
t.Fatalf("WriteFile(%s): %v", name, err)
}
}
var logBuf bytes.Buffer
logger.SetOutput(&logBuf)
defer logger.SetOutput(os.Stderr)
// Step 1: Call initObsidianBackend — should return quickly.
initStart := time.Now()
b, _, cleanup, deferredIndex, err := initObsidianBackend(tmpDir, "daily notes", true)
initElapsed := time.Since(initStart)
if err != nil {
t.Fatalf("initObsidianBackend failed: %v", err)
}
defer cleanup()
if initElapsed >= 1*time.Second {
t.Errorf("initObsidianBackend took %v, want < 1s", initElapsed)
}
// Step 2: Verify backend is non-nil but has no pages yet.
if b == nil {
t.Fatal("initObsidianBackend returned nil backend")
}
pagesBeforeIndex, err := b.GetAllPages(context.Background())
if err != nil {
t.Fatalf("GetAllPages (before index): %v", err)
}
if len(pagesBeforeIndex) != 0 {
t.Errorf("expected 0 pages before background indexing, got %d", len(pagesBeforeIndex))
}
// Step 3: Simulate background indexing with shared mutex and readiness flag,
// matching the pattern in executeServe() (spec 012, T004).
indexReady := &atomic.Bool{}
indexMu := &sync.Mutex{}
if indexReady.Load() {
t.Error("indexReady should be false before background indexing")
}
// Step 4: Run deferred indexing in a goroutine (same as executeServe).
if deferredIndex == nil {
t.Fatal("deferredIndex should be non-nil")
}
done := make(chan struct{})
go func() {
defer close(done)
indexMu.Lock()
defer indexMu.Unlock()
defer indexReady.Store(true)
if err := deferredIndex(); err != nil {
// Can't use t.Fatalf in goroutine — log and let the main
// goroutine detect the failure via indexReady remaining false.
t.Errorf("deferredIndex failed: %v", err)
}
}()
// Step 5: Wait for background indexing to complete.
select {
case <-done:
// Success — goroutine completed.
case <-time.After(10 * time.Second):
t.Fatal("background indexing did not complete within 10 seconds")
}
// Step 6: Verify indexReady is true after completion.
if !indexReady.Load() {
t.Error("indexReady should be true after background indexing completes")
}