Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
6001 lines (5390 loc) · 254 KB
/
Copy pathProgram.cs
File metadata and controls
6001 lines (5390 loc) · 254 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
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using CodeMesh.Control.AgentAccess;
using CodeMesh.Control.Configuration;
using CodeMesh.Control.Diagnostics;
using CodeMesh.Domain.Contracts;
using CodeMesh.Domain.Graph;
using CodeMesh.Domain.Health;
using CodeMesh.Domain.Utilities;
using CodeMesh.Ingestion;
using CodeMesh.Ingestion.Embedding;
using CodeMesh.Ingestion.Summary;
using CodeMesh.Ingestion.Summary.Qualification;
using CodeMesh.Parser.CSharp;
using CodeMesh.Parser.Deployment;
using CodeMesh.Parser.Markdown;
using CodeMesh.Parser.Python;
using CodeMesh.Parser.Rust;
using CodeMesh.Storage;
using CodeMesh.Storage.Memory;
using CodeMesh.Storage.Mongo;
using CodeMesh.Storage.Neo4j;
using CodeMesh.Storage.Qdrant;
using MongoDB.Bson;
using MongoDB.Driver;
var tests = new (string Name, Func<Task> Run)[]
{
("sha256 helper is deterministic", TestHash),
("repository path policy ignores generated directories", TestRepositoryPathPolicyIgnoresGeneratedDirectories),
("repository path policy rejects linked paths", TestRepositoryPathPolicyRejectsLinkedPaths),
("repository path policy excludes known secrets and applies filters", TestRepositoryPathPolicyExcludesKnownSecretsAndAppliesFilters),
("repository path policy rejects unsafe patterns", TestRepositoryPathPolicyRejectsUnsafePatterns),
("environment file loader fills missing variables", TestEnvironmentFileLoaderFillsMissingVariables),
("ingest path resolver accepts repository and caller relative files", TestIngestPathResolverAcceptsRelativeFiles),
("ingest path resolver rejects missing explicit files", TestIngestPathResolverRejectsMissingFiles),
("refresh workflow resolves repository root", TestRefreshWorkflowResolvesRepositoryRoot),
("refresh workflow normalizes ingest arguments", TestRefreshWorkflowNormalizesIngestArguments),
("watch workflow normalizes refresh arguments", TestWatchWorkflowNormalizesRefreshArguments),
("watch workflow detects file changes", TestWatchWorkflowDetectsFileChanges),
("self workflow resolves repository root", TestSelfWorkflowResolvesRepositoryRoot),
("self workflow normalizes ingest arguments", TestSelfWorkflowNormalizesIngestArguments),
("self workflow rejects invalid roots", TestSelfWorkflowRejectsInvalidRoots),
("agent access contracts map REST JSON", TestAgentAccessContractsMapRestJson),
("agent access client calls REST endpoints", TestAgentAccessClientCallsRestEndpoints),
("ingestion writes parser output", TestIngestionWritesParserOutput),
("multi-language ingestion publishes one deterministic snapshot", TestMultiLanguageIngestionPublishesOneDeterministicSnapshot),
("ingestion redacts sensitive content before stores and embeddings", TestIngestionRedactsSensitiveContentBeforeStoresAndEmbeddings),
("dry-run ingestion skips stores", TestDryRunSkipsStores),
("repository refresh removes stale records", TestRepositoryRefreshRemovesStaleRecords),
("incremental ingestion skips unchanged records", TestIncrementalIngestionSkipsUnchangedRecords),
("incremental ingestion skips unchanged summaries", TestIncrementalIngestionSkipsUnchangedSummaries),
("summary budgets scale with node complexity", TestSummaryBudgetsScaleWithNodeComplexity),
("summary generator persists budget metadata", TestSummaryGeneratorPersistsBudgetMetadata),
("summary generator regenerates when configuration changes", TestSummaryGeneratorRegeneratesWhenConfigurationChanges),
("summary qualification runner redacts inputs and enforces evidence gates", TestSummaryQualificationRunnerAndCompiler),
("forced embedding ingestion rebuilds unchanged embeddings", TestForcedEmbeddingIngestionRebuildsUnchangedEmbeddings),
("embedding verifier reports missing and stale vectors", TestEmbeddingVerifierReportsMissingAndStaleVectors),
("repository cleanup removes indexed data", TestRepositoryCleanupRemovesIndexedData),
("repository aliases are generated and resolved", TestRepositoryAliasesAreGeneratedAndResolved),
("ingestion stamps git repository metadata", TestIngestionStampsGitRepositoryMetadata),
("ingestion writes repository registry records", TestIngestionWritesRepositoryRegistryRecords),
("snapshot slots retain clean heads and bound dirty history", TestSnapshotSlotsRetainCleanHeadsAndBoundDirtyHistory),
("checkout identity survives moves and rejects live copies", TestCheckoutIdentitySurvivesMovesAndRejectsLiveCopies),
("linked worktrees share projects but not checkouts", TestLinkedWorktreesShareProjectsButNotCheckouts),
("explicit pins protect snapshots until released", TestExplicitPinsProtectSnapshotsUntilReleased),
("failed snapshot generations preserve active slots", TestFailedSnapshotGenerationPreservesActiveSlots),
("status uses configured ollama endpoint", TestStatusUsesConfiguredOllamaEndpoint),
("status retries transient ollama failures", TestStatusRetriesTransientOllamaFailures),
("status degrades when configured model is missing", TestStatusDegradesWhenConfiguredModelIsMissing),
("ollama embedding provider maps responses", TestOllamaEmbeddingProviderMapsResponses),
("lm studio embedding provider maps responses", TestLmStudioEmbeddingProviderMapsResponses),
("lm studio summary provider accepts numeric confidence", TestLmStudioSummaryProviderAcceptsNumericConfidence),
("ollama summary provider uses request completion budget", TestOllamaSummaryProviderUsesRequestCompletionBudget),
("openai summary provider uses responses structured output", TestOpenAiSummaryProviderUsesResponsesStructuredOutput),
("openai summary provider records provider-default effort", TestOpenAiSummaryProviderRecordsProviderDefaultEffort),
("mongodb content store round-trips content", TestMongoContentStoreRoundTripsContent),
("mongodb summary store migrates generation identity", TestMongoSummaryStoreMigratesGenerationIdentity),
("mongodb registry store round-trips repositories and runs", TestMongoRegistryStoreRoundTripsRepositoriesAndRuns),
("neo4j graph store round-trips graph", TestNeo4jGraphStoreRoundTripsGraph),
("qdrant vector store round-trips embeddings", TestQdrantVectorStoreRoundTripsEmbeddings),
("csharp parser emits Roslyn symbols", TestCSharpParserEmitsRoslynSymbols),
("csharp parser emits test files and cases", TestCSharpParserEmitsTestFilesAndCases),
("csharp parser emits invocation and member access relationships", TestCSharpParserEmitsInvocationAndMemberAccessRelationships),
("csharp parser emits cross-project invocation relationships", TestCSharpParserEmitsCrossProjectInvocationRelationships),
("csharp parser separates partial declarations from symbols", TestCSharpParserSeparatesPartialDeclarations),
("csharp parser honors project compile items", TestCSharpParserHonorsProjectCompileItems),
("csharp parser preserves isolated design-time editor configuration", TestCSharpParserDesignTimeEditorConfiguration),
("csharp parser applies repository path filters", TestCSharpParserAppliesRepositoryPathFilters),
("deployment parser emits Dockerfile and Compose nodes", TestDeploymentParserEmitsDockerfileAndComposeNodes),
("deployment parser parses repository runtime artifacts", TestDeploymentParserParsesRepositoryRuntimeArtifacts),
("markdown parser emits documents sections and containment", TestMarkdownParserEmitsDocumentsSectionsAndContainment),
("markdown parser parses repository docs", TestMarkdownParserParsesRepositoryDocs),
("python parser emits classes functions and containment", TestPythonParserEmitsClassesFunctionsAndContainment),
("python parser emits imports calls and test cases", TestPythonParserEmitsImportsCallsAndTestCases),
("python parser parses Agent Access project", TestPythonParserParsesAgentAccessProject),
("rust parser emits declarations relationships tests and PyO3 exports", TestRustParserEmitsDeclarationsRelationshipsTestsAndPyO3Exports),
("composite parser links Python calls to Rust PyO3 exports", TestCompositeParserLinksPythonCallsToRustPyO3Exports),
("csharp parser parses YoutubeDownloader sample", TestYoutubeDownloaderSampleParser)
};
var failures = 0;
var skipped = 0;
foreach (var test in tests)
{
try
{
await test.Run().ConfigureAwait(false);
Console.WriteLine($"[pass] {test.Name}");
}
catch (SkipTestException exception)
{
skipped++;
Console.WriteLine($"[skip] {test.Name}: {exception.Message}");
}
catch (Exception exception)
{
failures++;
Console.Error.WriteLine($"[fail] {test.Name}: {exception.Message}");
}
}
if (failures > 0)
{
Console.Error.WriteLine($"{failures} test(s) failed.");
return 1;
}
Console.WriteLine($"{tests.Length - skipped} test(s) passed, {skipped} skipped.");
return 0;
static Task TestHash()
{
Equal(
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
CodeMeshHash.Sha256Hex("abc"),
"SHA-256 output changed.");
return Task.CompletedTask;
}
static Task TestRepositoryPathPolicyIgnoresGeneratedDirectories()
{
Equal(true, RepositoryPathPolicy.IsIgnoredRelativePath("agent-access/.venv/lib/package.md"), "Repository path policy did not ignore .venv content.");
Equal(true, RepositoryPathPolicy.IsIgnoredRelativePath(".tmp/fixture/package.md"), "Repository path policy did not ignore temporary content.");
Equal(true, RepositoryPathPolicy.IsIgnoredRelativePath(".codemesh-smoke/run/Fixture.cs"), "Repository path policy did not ignore smoke output.");
Equal(true, RepositoryPathPolicy.IsIgnoredRelativePath("package.egg-info/PKG-INFO"), "Repository path policy did not ignore Python package metadata.");
Equal(false, RepositoryPathPolicy.IsIgnoredRelativePath("docs/evaluation/testing.md"), "Repository path policy ignored repository documentation.");
return Task.CompletedTask;
}
static Task TestRepositoryPathPolicyRejectsLinkedPaths()
{
var root = Path.Combine(Path.GetTempPath(), $"codemesh-path-link-root-{Guid.NewGuid():N}");
var outside = Path.Combine(Path.GetTempPath(), $"codemesh-path-link-outside-{Guid.NewGuid():N}");
Directory.CreateDirectory(root);
Directory.CreateDirectory(outside);
try
{
var outsideFile = Path.Combine(outside, "External.cs");
var normalFile = Path.Combine(root, "Normal.cs");
File.WriteAllText(outsideFile, "public sealed class External;");
File.WriteAllText(normalFile, "public sealed class Normal;");
var linkedDirectory = Path.Combine(root, "linked-directory");
var linkedFile = Path.Combine(root, "Linked.cs");
try
{
Directory.CreateSymbolicLink(linkedDirectory, outside);
File.CreateSymbolicLink(linkedFile, outsideFile);
}
catch (Exception exception) when (
exception is PlatformNotSupportedException or
UnauthorizedAccessException or
IOException)
{
return Task.CompletedTask;
}
Equal(true, RepositoryPathPolicy.IsIgnoredPath(root, linkedDirectory), "Repository path policy did not reject a linked directory.");
Equal(true, RepositoryPathPolicy.IsIgnoredPath(root, Path.Combine(linkedDirectory, "External.cs")), "Repository path policy did not reject a file below a linked directory.");
Equal(true, RepositoryPathPolicy.IsIgnoredPath(root, linkedFile), "Repository path policy did not reject a linked file.");
Equal(false, RepositoryPathPolicy.IsIgnoredPath(root, normalFile), "Repository path policy rejected a normal repository file.");
var enumerated = RepositoryPathPolicy.EnumerateFiles(root, "*.cs")
.Select(Path.GetFileName)
.Order(StringComparer.Ordinal)
.ToArray();
Equal(1, enumerated.Length, "Repository traversal included a linked file or traversed a linked directory.");
Equal("Normal.cs", enumerated[0], "Repository traversal did not retain the normal repository file.");
}
finally
{
Directory.Delete(root, recursive: true);
Directory.Delete(outside, recursive: true);
}
return Task.CompletedTask;
}
static Task TestRepositoryPathPolicyExcludesKnownSecretsAndAppliesFilters()
{
Equal(true, RepositoryPathPolicy.IsIgnoredRelativePath(".env"), "Repository path policy did not exclude .env.");
Equal(true, RepositoryPathPolicy.IsIgnoredRelativePath("config/.env.local"), "Repository path policy did not exclude environment-specific secrets.");
Equal(true, RepositoryPathPolicy.IsIgnoredRelativePath("infra/secrets.yaml"), "Repository path policy did not exclude a known secret manifest.");
Equal(true, RepositoryPathPolicy.IsIgnoredRelativePath("cloud/service-account-prod.json"), "Repository path policy did not exclude service-account material.");
Equal(true, RepositoryPathPolicy.IsIgnoredRelativePath("keys/deploy.pem"), "Repository path policy did not exclude a private-key extension.");
Equal(true, RepositoryPathPolicy.IsIgnoredRelativePath("state/app.tfstate.backup"), "Repository path policy did not exclude Terraform state backup.");
Equal(false, RepositoryPathPolicy.IsIgnoredRelativePath(".env.example"), "Repository path policy excluded a safe environment template.");
Equal(false, RepositoryPathPolicy.IsIgnoredRelativePath("config/.env.production.template"), "Repository path policy excluded an environment-specific safe template.");
Equal(false, RepositoryPathPolicy.IsIgnoredRelativePath("src/Secrets.cs"), "Repository path policy excluded source code based only on its name.");
var filter = new RepositoryPathFilter(
AllowPatterns: ["src/**"],
DenyPatterns: ["src/generated/**"]);
Equal(false, RepositoryPathPolicy.IsIgnoredRelativePath("src/App.cs", filter), "Repository path allow pattern did not include matching source.");
Equal(true, RepositoryPathPolicy.IsIgnoredRelativePath("tests/AppTests.cs", filter), "Repository path allow pattern did not exclude a non-matching path.");
Equal(true, RepositoryPathPolicy.IsIgnoredRelativePath("src/generated/App.g.cs", filter), "Repository path deny pattern did not override the allow pattern.");
Equal(true, RepositoryPathPolicy.IsIgnoredRelativePath("src/.env", filter), "Allow pattern bypassed default known-secret exclusion.");
var rootOnly = new RepositoryPathFilter(AllowPatterns: ["README.md"]);
Equal(false, RepositoryPathPolicy.IsIgnoredRelativePath("README.md", rootOnly), "Root-relative allow pattern did not match the root file.");
Equal(true, RepositoryPathPolicy.IsIgnoredRelativePath("docs/README.md", rootOnly), "Root-relative allow pattern matched a nested basename.");
var recursiveBasename = new RepositoryPathFilter(AllowPatterns: ["**/README.md"]);
Equal(false, RepositoryPathPolicy.IsIgnoredRelativePath("docs/README.md", recursiveBasename), "Recursive basename allow pattern did not match a nested file.");
var explicitSecretOverride = filter with { ExcludeKnownSecretFiles = false };
Equal(false, RepositoryPathPolicy.IsIgnoredRelativePath("src/.env", explicitSecretOverride), "Explicit known-secret override did not change the default exclusion.");
Equal(true, RepositoryPathPolicy.IsIgnoredRelativePath("src/bin/Generated.cs", explicitSecretOverride), "Explicit secret override bypassed immutable generated-directory exclusions.");
Equal(
RepositoryPathPolicy.StableFingerprint(new RepositoryPathFilter(["SRC/**", "docs/**"])),
RepositoryPathPolicy.StableFingerprint(new RepositoryPathFilter(["docs/**", "src/**"])),
"Equivalent path filters produced different stable fingerprints.");
return Task.CompletedTask;
}
static Task TestRepositoryPathPolicyRejectsUnsafePatterns()
{
Throws<ArgumentException>(
() => RepositoryPathPolicy.StableFingerprint(new RepositoryPathFilter(["../outside/**"])),
"Repository path policy accepted parent traversal in an allow pattern.");
Throws<ArgumentException>(
() => RepositoryPathPolicy.StableFingerprint(new RepositoryPathFilter(DenyPatterns: [Path.GetFullPath("outside/**")])),
"Repository path policy accepted an absolute deny pattern.");
Throws<ArgumentException>(
() => RepositoryPathPolicy.StableFingerprint(new RepositoryPathFilter(DenyPatterns: ["C:\\outside\\**"])),
"Repository path policy accepted a Windows absolute deny pattern.");
Throws<ArgumentException>(
() => RepositoryPathPolicy.StableFingerprint(new RepositoryPathFilter([" "])),
"Repository path policy accepted an empty allow pattern.");
Throws<ArgumentException>(
() => RepositoryPathPolicy.StableFingerprint(new RepositoryPathFilter(["src//**"])),
"Repository path policy accepted an ambiguous repeated separator.");
return Task.CompletedTask;
}
static Task TestEnvironmentFileLoaderFillsMissingVariables()
{
var root = Path.Combine(Path.GetTempPath(), $"codemesh-env-loader-test-{Guid.NewGuid():N}");
var missingKey = $"CODEMESH_TEST_ENV_MISSING_{Guid.NewGuid():N}";
var quotedKey = $"CODEMESH_TEST_ENV_QUOTED_{Guid.NewGuid():N}";
var existingKey = $"CODEMESH_TEST_ENV_EXISTING_{Guid.NewGuid():N}";
try
{
Directory.CreateDirectory(root);
File.WriteAllLines(
Path.Combine(root, ".env"),
[
"# comment",
$"{missingKey}=from-env-file",
$"{quotedKey}=\"quoted value\"",
$"{existingKey}=from-env-file"
]);
Environment.SetEnvironmentVariable(missingKey, null);
Environment.SetEnvironmentVariable(quotedKey, null);
Environment.SetEnvironmentVariable(existingKey, "already-set");
var loaded = EnvironmentFileLoader.LoadIfExists(root);
Equal(2, loaded, "Environment loader loaded an unexpected number of variables.");
Equal("from-env-file", Environment.GetEnvironmentVariable(missingKey) ?? string.Empty, "Environment loader did not set a missing variable.");
Equal("quoted value", Environment.GetEnvironmentVariable(quotedKey) ?? string.Empty, "Environment loader did not unquote a value.");
Equal("already-set", Environment.GetEnvironmentVariable(existingKey) ?? string.Empty, "Environment loader overwrote an existing variable.");
}
finally
{
Environment.SetEnvironmentVariable(missingKey, null);
Environment.SetEnvironmentVariable(quotedKey, null);
Environment.SetEnvironmentVariable(existingKey, null);
if (Directory.Exists(root))
{
Directory.Delete(root, recursive: true);
}
}
return Task.CompletedTask;
}
static Task TestIngestPathResolverAcceptsRelativeFiles()
{
var root = Path.Combine(Path.GetTempPath(), $"codemesh-ingest-path-test-{Guid.NewGuid():N}");
var solution = Path.Combine(root, "src", "Sample.sln");
try
{
Directory.CreateDirectory(Path.GetDirectoryName(solution)!);
File.WriteAllText(solution, string.Empty);
Equal(
solution,
CodeMeshIngestPathResolver.ResolveFile(root, Path.Combine("src", "Sample.sln"), "Solution") ?? string.Empty,
"Ingest path resolver did not resolve a repository-relative solution.");
var callerRelativePath = Path.GetRelativePath(Directory.GetCurrentDirectory(), solution);
Equal(
solution,
CodeMeshIngestPathResolver.ResolveFile(root, callerRelativePath, "Solution") ?? string.Empty,
"Ingest path resolver did not resolve a caller-relative solution.");
Equal(
solution,
CodeMeshIngestPathResolver.ResolveFile(root, solution, "Solution") ?? string.Empty,
"Ingest path resolver changed an absolute solution path.");
}
finally
{
if (Directory.Exists(root))
{
Directory.Delete(root, recursive: true);
}
}
return Task.CompletedTask;
}
static Task TestIngestPathResolverRejectsMissingFiles()
{
var root = Path.Combine(Path.GetTempPath(), $"codemesh-ingest-path-missing-test-{Guid.NewGuid():N}");
try
{
Directory.CreateDirectory(root);
Throws<InvalidOperationException>(
() => CodeMeshIngestPathResolver.ResolveFile(root, "missing.sln", "Solution"),
"Ingest path resolver accepted a missing explicit solution.");
}
finally
{
if (Directory.Exists(root))
{
Directory.Delete(root, recursive: true);
}
}
return Task.CompletedTask;
}
static Task TestRefreshWorkflowResolvesRepositoryRoot()
{
var root = Path.Combine(Path.GetTempPath(), $"codemesh-refresh-root-test-{Guid.NewGuid():N}");
var nested = Path.Combine(root, "src", "Nested");
var solution = Path.Combine(root, "Sample.sln");
try
{
Directory.CreateDirectory(nested);
File.WriteAllText(solution, string.Empty);
var target = CodeMeshRefreshWorkflow.ResolveTarget(nested);
Equal(root, target.RootPath, "Refresh workflow did not walk up to the repository root.");
Equal(solution, target.SolutionPath ?? string.Empty, "Refresh workflow did not default to the repository solution.");
}
finally
{
if (Directory.Exists(root))
{
Directory.Delete(root, recursive: true);
}
}
return Task.CompletedTask;
}
static Task TestRefreshWorkflowNormalizesIngestArguments()
{
var root = Path.Combine(Path.GetTempPath(), $"codemesh-refresh-args-test-{Guid.NewGuid():N}");
var solution = Path.Combine(root, "Sample.sln");
try
{
Directory.CreateDirectory(root);
File.WriteAllText(solution, string.Empty);
var target = CodeMeshRefreshWorkflow.ResolveTarget(root);
var args = CodeMeshRefreshWorkflow.BuildRefreshIngestArgs(
[
"refresh",
"--root",
"ignored",
"--solution",
"ignored.sln",
"--skip-embeddings",
"--force-embeddings",
"--include-summaries",
"--summary-max-completion-tokens",
"1024",
"--json"
],
target);
Equal("ingest", args[0], "Refresh workflow did not normalize to the ingest command.");
Equal(false, args.Contains("refresh"), "Refresh workflow leaked the refresh command into ingest args.");
Equal(true, args.Contains("--skip-embeddings"), "Refresh workflow removed an ingestion flag.");
Equal(true, args.Contains("--force-embeddings"), "Refresh workflow removed an embedding flag.");
Equal(true, args.Contains("--include-summaries"), "Refresh workflow removed a summary flag.");
Equal(true, args.Contains("--summary-max-completion-tokens"), "Refresh workflow removed summary budget configuration.");
Equal("1024", args[Array.IndexOf(args, "--summary-max-completion-tokens") + 1], "Refresh workflow changed summary budget configuration.");
Equal(true, args.Contains("--json"), "Refresh workflow removed json output flag.");
Equal(1, args.Count(arg => string.Equals(arg, "--root", StringComparison.OrdinalIgnoreCase)), "Refresh workflow emitted duplicate root options.");
Equal(1, args.Count(arg => string.Equals(arg, "--solution", StringComparison.OrdinalIgnoreCase)), "Refresh workflow emitted duplicate solution options.");
Equal(root, args[Array.LastIndexOf(args, "--root") + 1], "Refresh workflow did not inject the resolved root.");
Equal(solution, args[Array.LastIndexOf(args, "--solution") + 1], "Refresh workflow did not inject the resolved solution.");
}
finally
{
if (Directory.Exists(root))
{
Directory.Delete(root, recursive: true);
}
}
return Task.CompletedTask;
}
static Task TestWatchWorkflowNormalizesRefreshArguments()
{
var root = Path.Combine(Path.GetTempPath(), $"codemesh-watch-args-test-{Guid.NewGuid():N}");
var solution = Path.Combine(root, "Sample.sln");
try
{
Directory.CreateDirectory(root);
File.WriteAllText(solution, string.Empty);
var target = CodeMeshRefreshWorkflow.ResolveTarget(root);
var args = CodeMeshWatchWorkflow.BuildWatchRefreshArgs(
[
"watch",
"--root",
"ignored",
"--solution",
"ignored.sln",
"--poll-seconds",
"1",
"--max-runs",
"2",
"--run-once",
"--skip-embeddings",
"--include-summaries",
"--summary-reasoning-token-reserve",
"768",
"--json"
],
target);
Equal("ingest", args[0], "Watch workflow did not normalize to the ingest command.");
Equal(false, args.Contains("watch"), "Watch workflow leaked the watch command into ingest args.");
Equal(false, args.Contains("--poll-seconds"), "Watch workflow leaked poll configuration into ingest args.");
Equal(false, args.Contains("--max-runs"), "Watch workflow leaked run limit configuration into ingest args.");
Equal(false, args.Contains("--run-once"), "Watch workflow leaked run-once configuration into ingest args.");
Equal(true, args.Contains("--skip-embeddings"), "Watch workflow removed an ingestion flag.");
Equal(true, args.Contains("--include-summaries"), "Watch workflow removed a summary flag.");
Equal(true, args.Contains("--summary-reasoning-token-reserve"), "Watch workflow removed summary reasoning configuration.");
Equal("768", args[Array.IndexOf(args, "--summary-reasoning-token-reserve") + 1], "Watch workflow changed summary reasoning configuration.");
Equal(true, args.Contains("--json"), "Watch workflow removed json output flag.");
Equal(root, args[Array.LastIndexOf(args, "--root") + 1], "Watch workflow did not inject the resolved root.");
Equal(solution, args[Array.LastIndexOf(args, "--solution") + 1], "Watch workflow did not inject the resolved solution.");
}
finally
{
if (Directory.Exists(root))
{
Directory.Delete(root, recursive: true);
}
}
return Task.CompletedTask;
}
static Task TestWatchWorkflowDetectsFileChanges()
{
var root = Path.Combine(Path.GetTempPath(), $"codemesh-watch-snapshot-test-{Guid.NewGuid():N}");
var file = Path.Combine(root, "src", "Sample.cs");
var ignoredDirectory = Path.Combine(root, "bin");
var ignoredTemporaryDirectory = Path.Combine(root, ".tmp");
var ignoredSmokeDirectory = Path.Combine(root, ".codemesh-smoke");
var filteredDirectory = Path.Combine(root, "tests");
var secretFile = Path.Combine(root, ".env");
try
{
Directory.CreateDirectory(Path.GetDirectoryName(file)!);
Directory.CreateDirectory(ignoredDirectory);
Directory.CreateDirectory(ignoredTemporaryDirectory);
Directory.CreateDirectory(ignoredSmokeDirectory);
Directory.CreateDirectory(filteredDirectory);
File.WriteAllText(file, "one");
var first = CodeMeshWatchWorkflow.CreateSnapshot(root);
var unchanged = CodeMeshWatchWorkflow.CreateSnapshot(root);
File.WriteAllText(file, "one two");
var changed = CodeMeshWatchWorkflow.CreateSnapshot(root);
File.WriteAllText(Path.Combine(ignoredDirectory, "Generated.cs"), "ignored");
File.WriteAllText(Path.Combine(ignoredTemporaryDirectory, "Temporary.cs"), "ignored");
File.WriteAllText(Path.Combine(ignoredSmokeDirectory, "Fixture.cs"), "ignored");
var ignoredChange = CodeMeshWatchWorkflow.CreateSnapshot(root);
Equal(false, CodeMeshWatchWorkflow.HasChanges(first, unchanged), "Watch workflow reported changes for identical snapshots.");
Equal(true, CodeMeshWatchWorkflow.HasChanges(first, changed), "Watch workflow did not detect a changed file.");
Equal(false, CodeMeshWatchWorkflow.HasChanges(changed, ignoredChange), "Watch workflow did not ignore generated directories.");
var filter = new RepositoryPathFilter(AllowPatterns: ["src/**"]);
File.WriteAllText(secretFile, "TOKEN=not-a-real-secret");
File.WriteAllText(Path.Combine(filteredDirectory, "SampleTests.cs"), "one");
var filtered = CodeMeshWatchWorkflow.CreateSnapshot(root, filter);
File.WriteAllText(secretFile, "TOKEN=still-not-a-real-secret");
File.WriteAllText(Path.Combine(filteredDirectory, "SampleTests.cs"), "one two");
var filteredIgnoredChange = CodeMeshWatchWorkflow.CreateSnapshot(root, filter);
Equal(false, CodeMeshWatchWorkflow.HasChanges(filtered, filteredIgnoredChange), "Watch workflow reacted to secret or allow-filtered files.");
File.WriteAllText(file, "one two three");
var filteredSourceChange = CodeMeshWatchWorkflow.CreateSnapshot(root, filter);
Equal(true, CodeMeshWatchWorkflow.HasChanges(filteredIgnoredChange, filteredSourceChange), "Watch workflow missed an allowed source change.");
}
finally
{
if (Directory.Exists(root))
{
Directory.Delete(root, recursive: true);
}
}
return Task.CompletedTask;
}
static Task TestSelfWorkflowResolvesRepositoryRoot()
{
var root = Path.Combine(Path.GetTempPath(), $"codemesh-self-root-test-{Guid.NewGuid():N}");
var nested = Path.Combine(root, "src", "Nested");
var solution = Path.Combine(root, CodeMeshSelfWorkflow.SolutionFileName);
try
{
Directory.CreateDirectory(nested);
File.WriteAllText(solution, string.Empty);
File.WriteAllText(Path.Combine(root, CodeMeshSelfWorkflow.MarkerFileName), "version: test");
var target = CodeMeshSelfWorkflow.ResolveTarget(nested);
Equal(root, target.RootPath, "Self workflow did not walk up to the CodeMesh repository root.");
Equal(solution, target.SolutionPath, "Self workflow did not default to CodeMesh.sln.");
}
finally
{
if (Directory.Exists(root))
{
Directory.Delete(root, recursive: true);
}
}
return Task.CompletedTask;
}
static Task TestSelfWorkflowNormalizesIngestArguments()
{
var root = Path.Combine(Path.GetTempPath(), $"codemesh-self-args-test-{Guid.NewGuid():N}");
var solution = Path.Combine(root, CodeMeshSelfWorkflow.SolutionFileName);
var alternateSolution = Path.Combine(root, "Alternate.sln");
try
{
Directory.CreateDirectory(root);
File.WriteAllText(solution, string.Empty);
File.WriteAllText(alternateSolution, string.Empty);
File.WriteAllText(Path.Combine(root, CodeMeshSelfWorkflow.AgentInstructionsFileName), "# test");
var target = CodeMeshSelfWorkflow.ResolveTarget(root, alternateSolution);
var args = CodeMeshSelfWorkflow.BuildSelfIngestArgs(
[
"self",
"smoke",
"--root",
"ignored",
"--solution",
"ignored.sln",
"--agent-access-url",
"http://127.0.0.1:8088",
"--query",
"ignored query",
"--skip-embeddings",
"--include-summaries",
"--summary-max-input-chars",
"4000",
"--json"
],
target);
Equal("ingest", args[0], "Self workflow did not normalize to the ingest command.");
Equal(false, args.Contains("smoke"), "Self workflow leaked the self smoke subcommand into ingest args.");
Equal(false, args.Contains("--agent-access-url"), "Self workflow leaked smoke-only Agent Access options into ingest args.");
Equal(true, args.Contains("--skip-embeddings"), "Self workflow removed an ingestion flag.");
Equal(true, args.Contains("--include-summaries"), "Self workflow removed a summary flag.");
Equal(true, args.Contains("--summary-max-input-chars"), "Self workflow removed summary input configuration.");
Equal("4000", args[Array.IndexOf(args, "--summary-max-input-chars") + 1], "Self workflow changed summary input configuration.");
Equal(true, args.Contains("--json"), "Self workflow removed json output flag.");
Equal(root, args[Array.LastIndexOf(args, "--root") + 1], "Self workflow did not inject the resolved root.");
Equal(alternateSolution, args[Array.LastIndexOf(args, "--solution") + 1], "Self workflow did not inject the resolved solution.");
}
finally
{
if (Directory.Exists(root))
{
Directory.Delete(root, recursive: true);
}
}
return Task.CompletedTask;
}
static Task TestSelfWorkflowRejectsInvalidRoots()
{
var root = Path.Combine(Path.GetTempPath(), $"codemesh-self-invalid-test-{Guid.NewGuid():N}");
try
{
Directory.CreateDirectory(root);
Throws<InvalidOperationException>(
() => CodeMeshSelfWorkflow.ResolveTarget(root),
"Self workflow accepted a directory without CodeMesh root markers.");
}
finally
{
if (Directory.Exists(root))
{
Directory.Delete(root, recursive: true);
}
}
return Task.CompletedTask;
}
static Task TestAgentAccessContractsMapRestJson()
{
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
var serializedQuery = JsonSerializer.Serialize(
new AgentContextQuery(
"DownloadAsync",
RepositoryId: "repo:test",
Kinds: ["Method"],
Filters: new Dictionary<string, string> { ["project"] = "Sample" },
Vector: [0.1f, 0.2f],
ExpandContext: false,
ContextRelationshipLimit: 4),
options);
if (!serializedQuery.Contains("\"repository_id\":\"repo:test\"", StringComparison.Ordinal) ||
!serializedQuery.Contains("\"context_relationship_limit\":4", StringComparison.Ordinal))
{
throw new InvalidOperationException("Agent context query did not serialize using Agent Access snake_case fields.");
}
var serializedPackageQuery = JsonSerializer.Serialize(
new AgentContextPackageQuery(
"DownloadAsync",
RepositoryId: "repo:test",
MaxCharacters: 4000,
CallerLimit: 2,
UsesTypeLimit: 0),
options);
if (!serializedPackageQuery.Contains("\"max_characters\":4000", StringComparison.Ordinal) ||
!serializedPackageQuery.Contains("\"uses_type_limit\":0", StringComparison.Ordinal))
{
throw new InvalidOperationException("Agent context package query did not serialize using Agent Access snake_case fields.");
}
var context = JsonSerializer.Deserialize<AgentContextResult>(
"""
{
"query": {
"query": "DownloadAsync",
"repository_id": "repo:test",
"limit": 5,
"kinds": ["Method"],
"filters": {"project": "Sample"},
"vector": [0.1, 0.2],
"expand_context": false,
"context_depth": 2,
"include_context_relationships": true,
"context_relationship_limit": 4
},
"hits": [
{
"node_id": "node:download",
"stable_key": "stable:download",
"kind": "Method",
"file_path": "Downloader.cs",
"start_line": 10,
"end_line": 20,
"score": 0.91,
"repository_id": "repo:test",
"content_hash": "content:download",
"score_components": {"vector_score": 0.6},
"expanded_context": {"reason": "defined_ancestor"},
"preview": "Task DownloadAsync"
}
],
"diagnostics": {
"mode": "hybrid",
"embedding_attempted": true,
"embedding_source": "model_provider",
"model_provider": "lmstudio",
"vector_available": true,
"vector_hit_count": 7,
"lexical_hit_count": 3,
"summary_hit_count": 2,
"vector_candidate_count": 9,
"lexical_candidate_count": 5,
"summary_candidate_count": 4,
"lexical_fallback": false,
"hit_count": 1
},
"generated_at": "2026-06-06T10:00:00Z"
}
""",
options);
NotNull(context, "Agent context result did not deserialize.");
Equal("repo:test", context!.Query.RepositoryId ?? string.Empty, "Agent context query repository id did not map from snake_case.");
Equal(false, context.Query.ExpandContext, "Agent context query expansion flag changed.");
Equal(4, context.Query.ContextRelationshipLimit, "Agent context relationship limit did not deserialize.");
Equal(CodeNodeKind.Method, context.Hits[0].Kind, "Agent context hit kind did not deserialize.");
Equal("content:download", context.Hits[0].ContentHash ?? string.Empty, "Agent context hit content hash did not deserialize.");
Equal(0.6, context.Hits[0].ScoreComponents!["vector_score"], "Agent context score components did not deserialize.");
Equal("defined_ancestor", context.Hits[0].ExpandedContext!["reason"].GetString() ?? string.Empty, "Agent context expanded context did not deserialize.");
Equal("hybrid", context.Diagnostics!.Mode, "Agent context diagnostics mode did not deserialize.");
Equal("lmstudio", context.Diagnostics.ModelProvider, "Agent context diagnostics provider did not deserialize.");
Equal(7, context.Diagnostics.VectorHitCount, "Agent context diagnostics vector hit count did not deserialize.");
Equal(3, context.Diagnostics.LexicalHitCount, "Agent context diagnostics lexical hit count did not deserialize.");
Equal(2, context.Diagnostics.SummaryHitCount, "Agent context diagnostics summary hit count did not deserialize.");
Equal(9, context.Diagnostics.VectorCandidateCount, "Agent context diagnostics vector candidate count did not deserialize.");
Equal(5, context.Diagnostics.LexicalCandidateCount, "Agent context diagnostics lexical candidate count did not deserialize.");
Equal(4, context.Diagnostics.SummaryCandidateCount, "Agent context diagnostics summary candidate count did not deserialize.");
var package = JsonSerializer.Deserialize<AgentContextPackageResult>(
"""
{
"query": {
"query": "DownloadAsync",
"repository_id": "repo:test",
"limit": 3,
"max_characters": 4000,
"kinds": ["Method"],
"filters": {"project": "Sample"},
"vector": [0.1, 0.2],
"context_depth": 3,
"include_content": true,
"include_relationships": true,
"relationship_limit": 8,
"caller_limit": 2,
"callee_limit": 2,
"read_limit": 1,
"write_limit": 1,
"contains_limit": 1,
"definition_limit": 1,
"uses_type_limit": 0,
"include_repository": true
},
"repository": {"repository_id": "repo:test", "alias": "sample_repo"},
"latest_run": {"run_id": "run:test", "embedding_provider": "lmstudio"},
"items": [
{
"hit": {
"node_id": "node:download",
"stable_key": "stable:download",
"kind": "Method",
"file_path": "Downloader.cs",
"start_line": 10,
"end_line": 20,
"score": 0.91
},
"node": {"id": "node:download", "kind": "Method"},
"content": {"hash": "content:download"},
"summary": {"summary": "Downloads subtitles for a video URL.", "provider": "test"},
"snippet": "return Task.CompletedTask;",
"relationships": [{"kind": "Invokes", "target_node_id": "node:callee"}],
"relationship_groups": {
"callees": [{"kind": "Invokes", "target_node_id": "node:callee"}],
"callers": []
},
"rationale": {"rank": 1, "expanded": true}
}
],
"validation_recommendations": [
{
"id": "dotnet-tests",
"command": "dotnet run --project tests/CodeMesh.Tests",
"reason": "Run after .NET changes.",
"applies_to": ["Downloader.cs"]
}
],
"total_snippet_characters": 26,
"generated_at": "2026-06-06T10:00:00Z"
}
""",
options);
NotNull(package, "Agent context package did not deserialize.");
Equal(4000, package!.Query.MaxCharacters, "Agent context package max characters did not deserialize.");
Equal(0, package.Query.UsesTypeLimit ?? -1, "Agent context package uses type limit did not deserialize.");
Equal("sample_repo", package.Repository!["alias"].GetString() ?? string.Empty, "Agent context package repository metadata did not deserialize.");
Equal("lmstudio", package.LatestRun!["embedding_provider"].GetString() ?? string.Empty, "Agent context package latest run did not deserialize.");
Equal("dotnet run --project tests/CodeMesh.Tests", package.ValidationRecommendations![0]["command"].GetString() ?? string.Empty, "Agent context package validation recommendations did not deserialize.");
Equal("Downloads subtitles for a video URL.", package.Items[0].Summary!["summary"].GetString() ?? string.Empty, "Agent context package summary did not deserialize.");
Equal("return Task.CompletedTask;", package.Items[0].Snippet ?? string.Empty, "Agent context package snippet did not deserialize.");
Equal("node:callee", package.Items[0].RelationshipGroups!["callees"][0]["target_node_id"].GetString() ?? string.Empty, "Agent context package relationship groups did not deserialize.");
Equal(1, package.Items[0].Rationale!["rank"].GetInt32(), "Agent context package rationale did not deserialize.");
return Task.CompletedTask;
}
static async Task TestAgentAccessClientCallsRestEndpoints()
{
var handler = new FakeAgentAccessHandler();
using var http = new HttpClient(handler)
{
BaseAddress = new Uri("http://agent.test/")
};
var client = new AgentAccessClient(http);
var health = await client.GetHealthAsync();
Equal("health", handler.Requests[0].Path, "Agent Access health path changed.");
Equal("healthy", health.Status, "Agent Access health status did not deserialize.");
Equal("healthy", health.Components["model_provider"].GetProperty("status").GetString() ?? string.Empty, "Agent Access health components did not deserialize.");
var status = await client.GetStatusAsync();
Equal("status", handler.Requests[1].Path, "Agent Access status path changed.");
Equal("codemesh-agent-access", status.Service, "Agent Access status service did not deserialize.");
var context = await client.SearchContextAsync(new AgentContextQuery(
"DownloadAsync",
RepositoryId: "repo:test",
Kinds: ["Method"],
Filters: new Dictionary<string, string> { ["project"] = "Sample" },
Vector: [0.1f, 0.2f],
IncludeContextRelationships: true));
Equal("context/search", handler.Requests[2].Path, "Agent Access context search path changed.");
if (!handler.Requests[2].Body.Contains("\"repository_id\":\"repo:test\"", StringComparison.Ordinal) ||
!handler.Requests[2].Body.Contains("\"include_context_relationships\":true", StringComparison.Ordinal))
{
throw new InvalidOperationException("Agent Access context request did not use REST JSON field names.");
}
Equal("hybrid", context.Diagnostics!.Mode, "Agent Access context response diagnostics changed.");
Equal("node:download", context.Hits[0].NodeId, "Agent Access context hit did not deserialize.");
var package = await client.GetContextPackageAsync(new AgentContextPackageQuery(
"DownloadAsync",
RepositoryId: "repo:test",
MaxCharacters: 4000,
CallerLimit: 2));
Equal("context/package", handler.Requests[3].Path, "Agent Access context package path changed.");
if (!handler.Requests[3].Body.Contains("\"max_characters\":4000", StringComparison.Ordinal) ||
!handler.Requests[3].Body.Contains("\"caller_limit\":2", StringComparison.Ordinal))
{
throw new InvalidOperationException("Agent Access package request did not use REST JSON field names.");
}
if (handler.Requests[3].Body.Contains("\"vector\":null", StringComparison.Ordinal))
{
throw new InvalidOperationException("Agent Access package request should omit null vectors.");
}
Equal("return Task.CompletedTask;", package.Items[0].Snippet ?? string.Empty, "Agent Access package response did not deserialize.");
var symbols = await client.SearchSymbolsAsync(new AgentSymbolQuery(
"DownloadAsync",
RepositoryId: "repo:test",
Kinds: ["Method"],
IncludeDeclarations: false));
Equal("symbols/search", handler.Requests[4].Path, "Agent Access symbol search path changed.");
Equal("DownloadAsync", symbols.Symbols[0].Node["name"].GetString() ?? string.Empty, "Agent Access symbol result did not deserialize.");
var node = await client.GetNodeAsync(new AgentNodeLookup(
"node:download",
RepositoryId: "repo:test",
IncludeContent: false));
Equal("nodes/get", handler.Requests[5].Path, "Agent Access node path changed.");
Equal("node:download", node.Node!["id"].GetString() ?? string.Empty, "Agent Access node result did not deserialize.");
var neighbors = await client.GetNeighborsAsync(new AgentNeighborQuery(
"node:download",
RepositoryId: "repo:test",
RelationshipKinds: ["Invokes"]));
Equal("graph/neighbors", handler.Requests[6].Path, "Agent Access neighbors path changed.");
Equal("node:download", neighbors.Node!["id"].GetString() ?? string.Empty, "Agent Access neighbor node did not deserialize.");
Equal("Invokes", neighbors.Relationships[0]["kind"].GetString() ?? string.Empty, "Agent Access neighbor result did not deserialize.");
var repositories = await client.ListRepositoriesAsync(limit: 3);
Equal("repositories?limit=3", handler.Requests[7].Path, "Agent Access repositories path changed.");
Equal("sample_repo", repositories.Repositories[0].Alias ?? string.Empty, "Agent Access repository list did not deserialize.");
Equal(17, repositories.Repositories[0].NodeCount, "Agent Access repository node count did not deserialize.");
var repository = await client.GetRepositoryAsync("sample repo/id");
Equal("repositories/sample%20repo%2Fid", handler.Requests[8].Path, "Agent Access repository lookup path did not escape id.");
Equal("repo:test", repository!.RepositoryId, "Agent Access repository lookup did not deserialize.");
var repositoryStatus = await client.GetRepositoryStatusAsync("sample repo/id");
Equal("repositories/sample%20repo%2Fid/status", handler.Requests[9].Path, "Agent Access repository status path did not escape id.");
Equal("repo:test", repositoryStatus.RepositoryId, "Agent Access repository status did not deserialize.");
Equal("fresh", repositoryStatus.Freshness["status"].GetString() ?? string.Empty, "Agent Access repository freshness did not deserialize.");
Equal("completed", repositoryStatus.Refresh["status"].GetString() ?? string.Empty, "Agent Access repository refresh status did not deserialize.");
Equal("run:test", repositoryStatus.Refresh["latest_run_id"].GetString() ?? string.Empty, "Agent Access repository refresh run id did not deserialize.");
Equal(17, repositoryStatus.Counts["graph_nodes"].GetInt32(), "Agent Access repository status counts did not deserialize.");
var coverage = await client.GetSummaryCoverageAsync("sample repo/id");
Equal("repositories/sample%20repo%2Fid/summaries", handler.Requests[10].Path, "Agent Access summary coverage path did not escape id.");
Equal(5, coverage.CompletedCount, "Agent Access summary coverage completed count did not deserialize.");
Equal(2, coverage.KindCounts["Method"], "Agent Access summary coverage kind counts did not deserialize.");
Equal("qwen/qwen2.5-coder-14b", coverage.ProviderModelCountDetails[0].Model, "Agent Access summary coverage provider/model details did not deserialize.");
Equal("model failed", coverage.RecentFailures[0]["error"].GetString() ?? string.Empty, "Agent Access summary coverage failures did not deserialize.");
var runs = await client.ListIngestionRunsAsync(repositoryId: "sample repo/id", limit: 2);
Equal("ingestion-runs?limit=2&repository_id=sample%20repo%2Fid", handler.Requests[11].Path, "Agent Access runs path changed.");
Equal("run:test", runs.Runs[0].RunId, "Agent Access ingestion run did not deserialize.");
Equal("lmstudio", runs.Runs[0].EmbeddingProvider, "Agent Access run embedding provider did not deserialize.");
var delete = await client.DeleteRepositoryAsync("sample repo/id");
Equal(HttpMethod.Delete.Method, handler.Requests[12].Method, "Agent Access repository delete method changed.");
Equal("repositories/sample%20repo%2Fid", handler.Requests[12].Path, "Agent Access repository delete path did not escape id.");
Equal("repo:test", delete.RepositoryId, "Agent Access repository delete response did not deserialize.");
Equal(true, delete.Deleted, "Agent Access repository delete did not report deletion.");
Equal(true, delete.SummariesCleaned, "Agent Access repository delete cleanup flags did not deserialize.");
handler.FailNextRequest = true;
try
{
await client.SearchContextAsync(new AgentContextQuery("DownloadAsync"));
}
catch (InvalidOperationException exception) when (
exception.Message.Contains("context/search", StringComparison.Ordinal) &&
exception.Message.Contains("HTTP 503", StringComparison.Ordinal))
{
return;
}
throw new InvalidOperationException("Agent Access client did not surface REST error details.");
}
static async Task TestIngestionWritesParserOutput()
{
var store = new InMemoryCodeMeshStore();
var parser = new FakeParserClient();
var orchestrator = new IngestionOrchestrator(
parser,
store,
store,
store,
new NoEmbeddingProvider());
var result = await orchestrator.IngestAsync(new IngestionRequest(
Directory.GetCurrentDirectory(),
DryRun: false));
Equal(1, result.NodeCount, "Expected one node from fake parser.");
Equal(1, result.ContentCount, "Expected one content item from fake parser.");
var node = await store.GetNodeAsync(FakeParserClient.NodeId);
NotNull(node, "Node was not written to graph store.");
var content = await store.GetContentAsync(FakeParserClient.ContentHash);
NotNull(content, "Content was not written to content store.");