@phuc1403/musketeer 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/INSTALLATION.md +1 -0
  2. package/README.md +1 -1
  3. package/manifest.json +19 -2
  4. package/package.json +1 -1
  5. package/template/.claude/hooks/validate-cml-hook.js +6 -5
  6. package/template/.claude/skills/logical-components/.gitattributes +2 -0
  7. package/template/.claude/skills/logical-components/SKILL.md +102 -0
  8. package/template/.claude/skills/logical-components/references/component-classifier-prompt.md +53 -0
  9. package/template/.claude/skills/logical-components/references/responsibility-agent-prompt.md +67 -0
  10. package/template/.claude/skills/logical-components/references/responsibility-verifier-prompt.md +39 -0
  11. package/template/.claude/skills/logical-components/scripts/Directory.Build.props +7 -0
  12. package/template/.claude/skills/logical-components/scripts/Directory.Packages.props +8 -0
  13. package/template/.claude/skills/logical-components/scripts/LogicalComponents/BatchPlanning.cs +69 -0
  14. package/template/.claude/skills/logical-components/scripts/LogicalComponents/BatchesCommand.cs +39 -0
  15. package/template/.claude/skills/logical-components/scripts/LogicalComponents/CandidatesCommand.cs +70 -0
  16. package/template/.claude/skills/logical-components/scripts/LogicalComponents/CitableSource.cs +39 -0
  17. package/template/.claude/skills/logical-components/scripts/LogicalComponents/Citation.cs +37 -0
  18. package/template/.claude/skills/logical-components/scripts/LogicalComponents/ClassifyBatchesCommand.cs +65 -0
  19. package/template/.claude/skills/logical-components/scripts/LogicalComponents/ClassifyMergeCommand.cs +187 -0
  20. package/template/.claude/skills/logical-components/scripts/LogicalComponents/ComponentDiscovery.cs +166 -0
  21. package/template/.claude/skills/logical-components/scripts/LogicalComponents/ComponentRule.cs +87 -0
  22. package/template/.claude/skills/logical-components/scripts/LogicalComponents/ComponentsFile.cs +83 -0
  23. package/template/.claude/skills/logical-components/scripts/LogicalComponents/CouplingResolver.cs +196 -0
  24. package/template/.claude/skills/logical-components/scripts/LogicalComponents/DisplayName.cs +14 -0
  25. package/template/.claude/skills/logical-components/scripts/LogicalComponents/EdgeExtraction.cs +111 -0
  26. package/template/.claude/skills/logical-components/scripts/LogicalComponents/ExtractCommand.cs +72 -0
  27. package/template/.claude/skills/logical-components/scripts/LogicalComponents/ExtractConfig.cs +79 -0
  28. package/template/.claude/skills/logical-components/scripts/LogicalComponents/LogicalComponents.csproj +15 -0
  29. package/template/.claude/skills/logical-components/scripts/LogicalComponents/MarkdownRenderer.cs +73 -0
  30. package/template/.claude/skills/logical-components/scripts/LogicalComponents/MemberUseResolution.cs +203 -0
  31. package/template/.claude/skills/logical-components/scripts/LogicalComponents/MemberUses.cs +155 -0
  32. package/template/.claude/skills/logical-components/scripts/LogicalComponents/PortResolution.cs +75 -0
  33. package/template/.claude/skills/logical-components/scripts/LogicalComponents/Program.cs +27 -0
  34. package/template/.claude/skills/logical-components/scripts/LogicalComponents/ProjectFilters.cs +76 -0
  35. package/template/.claude/skills/logical-components/scripts/LogicalComponents/PruneCommand.cs +132 -0
  36. package/template/.claude/skills/logical-components/scripts/LogicalComponents/RenderCommand.cs +173 -0
  37. package/template/.claude/skills/logical-components/scripts/LogicalComponents/ResponsibilityBatches.cs +84 -0
  38. package/template/.claude/skills/logical-components/scripts/LogicalComponents/ResponsibilityValidation.cs +178 -0
  39. package/template/.claude/skills/logical-components/scripts/LogicalComponents/SeamDispatch.cs +59 -0
  40. package/template/.claude/skills/logical-components/scripts/LogicalComponents/SymbolNames.cs +53 -0
  41. package/template/.claude/skills/logical-components/scripts/LogicalComponents/TypeMap.cs +75 -0
  42. package/template/.claude/skills/logical-components/scripts/LogicalComponents/WalkRoots.cs +63 -0
  43. package/template/.claude/skills/logical-components/scripts/LogicalComponents/WorkspaceLoader.cs +227 -0
  44. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/AssignIdsTests.cs +41 -0
  45. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/BatchPlanningTests.cs +82 -0
  46. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/CandidatesCommandTests.cs +34 -0
  47. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/CitationTests.cs +42 -0
  48. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/ClassifyCommandsTests.cs +176 -0
  49. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/ComponentDiscoveryTests.cs +190 -0
  50. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/CouplingExtractionTests.cs +174 -0
  51. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/DisplayNameTests.cs +17 -0
  52. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/ExtractConfigTests.cs +72 -0
  53. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/FixturePaths.cs +32 -0
  54. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/LogicalComponents.Tests.csproj +23 -0
  55. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/MarkdownRendererTests.cs +50 -0
  56. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/ProjectFiltersTests.cs +65 -0
  57. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/PruneCommandTests.cs +119 -0
  58. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/RenderCommandTests.cs +162 -0
  59. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/RenderGoldenTests.cs +34 -0
  60. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/RenderTestData.cs +49 -0
  61. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/ResponsibilityValidationTests.cs +227 -0
  62. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/SampleAppWorkspace.cs +27 -0
  63. package/template/.claude/skills/logical-components/scripts/LogicalComponents.Tests/WorkspaceLoaderTests.cs +87 -0
  64. package/template/.claude/skills/logical-components/scripts/fixtures/BrokenApp/src/Broken.Application/Broken.Application.csproj +7 -0
  65. package/template/.claude/skills/logical-components/scripts/fixtures/BrokenApp/src/Broken.Application/Broken.cs +7 -0
  66. package/template/.claude/skills/logical-components/scripts/fixtures/MultiTargetApp/MultiTargetApp.slnx +6 -0
  67. package/template/.claude/skills/logical-components/scripts/fixtures/MultiTargetApp/src/Legacy.FSharp/Legacy.FSharp.fsproj +8 -0
  68. package/template/.claude/skills/logical-components/scripts/fixtures/MultiTargetApp/src/Legacy.FSharp/Library.fs +5 -0
  69. package/template/.claude/skills/logical-components/scripts/fixtures/MultiTargetApp/src/Multi.Application/Multi.Application.csproj +7 -0
  70. package/template/.claude/skills/logical-components/scripts/fixtures/MultiTargetApp/src/Multi.Application/Scheduling.cs +14 -0
  71. package/template/.claude/skills/logical-components/scripts/fixtures/NoSolutionApp/src/Solo.Application/Solo.Application.csproj +7 -0
  72. package/template/.claude/skills/logical-components/scripts/fixtures/NoSolutionApp/src/Solo.Application/SoloGreeting.cs +7 -0
  73. package/template/.claude/skills/logical-components/scripts/fixtures/NoSolutionApp/src/Solo.Application.Tests/FakeGreeting.cs +6 -0
  74. package/template/.claude/skills/logical-components/scripts/fixtures/NoSolutionApp/src/Solo.Application.Tests/Solo.Application.Tests.csproj +11 -0
  75. package/template/.claude/skills/logical-components/scripts/fixtures/RenderGolden/components.json +63 -0
  76. package/template/.claude/skills/logical-components/scripts/fixtures/RenderGolden/expected.md +28 -0
  77. package/template/.claude/skills/logical-components/scripts/fixtures/RenderGolden/repo/src/App/OrderAcceptance.cs +16 -0
  78. package/template/.claude/skills/logical-components/scripts/fixtures/RenderGolden/repo/src/Infra/OrderQueue.cs +10 -0
  79. package/template/.claude/skills/logical-components/scripts/fixtures/RenderGolden/resp/batch-01.json +18 -0
  80. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/SampleApp.slnx +10 -0
  81. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/logical-components.json +78 -0
  82. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/CandidateCases.cs +37 -0
  83. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/CouplingCases.cs +33 -0
  84. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/DependencyInjection.cs +18 -0
  85. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/EdgeCases.cs +63 -0
  86. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/LoudNotifying.Base.cs +5 -0
  87. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/LoudNotifying.cs +7 -0
  88. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/OrderAcceptance.cs +17 -0
  89. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/OrderOptions.cs +9 -0
  90. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/OrderRejectedException.cs +7 -0
  91. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/OrderRequest.cs +4 -0
  92. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/OrderRunning.cs +18 -0
  93. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/OrderValidation.cs +6 -0
  94. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/Ports.cs +19 -0
  95. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/PriceRules.cs +7 -0
  96. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/ReceiptPrinting.Totals.cs +6 -0
  97. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/ReceiptPrinting.cs +7 -0
  98. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/ReviewCases.cs +107 -0
  99. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/ReviewFixCases.cs +143 -0
  100. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/RunClock.cs +12 -0
  101. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/Sample.Application.csproj +10 -0
  102. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Application/SeeThroughCases.cs +89 -0
  103. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Billing.Application/OrderRunning.cs +7 -0
  104. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Billing.Application/Sample.Billing.Application.csproj +11 -0
  105. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Infrastructure/ForwardedNotifier.cs +8 -0
  106. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Infrastructure/InfrastructureDependencyInjection.cs +16 -0
  107. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Infrastructure/Mailer.cs +6 -0
  108. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Infrastructure/OrderQueue.cs +11 -0
  109. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Infrastructure/QueueEntry.cs +4 -0
  110. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Infrastructure/QueueStore.cs +8 -0
  111. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Infrastructure/ReviewCases.cs +35 -0
  112. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Infrastructure/ReviewFixCases.cs +13 -0
  113. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Infrastructure/Sample.Infrastructure.csproj +13 -0
  114. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Infrastructure/SeeThroughCases.cs +18 -0
  115. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/src/Sample.Infrastructure/UnreachedPlumbing.cs +7 -0
  116. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/tests/Sample.Tests/FakeOrderQueue.cs +11 -0
  117. package/template/.claude/skills/logical-components/scripts/fixtures/SampleApp/tests/Sample.Tests/Sample.Tests.csproj +11 -0
  118. package/template/.claude/skills/logical-components/scripts/fixtures/SharedOutsideRepo/SharedClock.cs +7 -0
  119. package/template/.claude/skills/logical-components/scripts/global.json +5 -0
  120. package/template/.claude/skills/logical-components/scripts/smoke-sample.sh +26 -0
@@ -0,0 +1,203 @@
1
+ using System.Collections.Immutable;
2
+ using Microsoft.CodeAnalysis;
3
+ using Microsoft.CodeAnalysis.CSharp.Syntax;
4
+
5
+ namespace LogicalComponents;
6
+
7
+ /// <summary>
8
+ /// Follows what a component's code uses until it lands on another component. A use of a member of:
9
+ /// <list type="bullet">
10
+ /// <item>a component is an edge to it;</item>
11
+ /// <item>an interface or abstract class (a seam) goes on to the member that runs in each implementation of the
12
+ /// construction used (see <see cref="SeamDispatch"/>);</item>
13
+ /// <item>any other type of the repo (a helper, a record, a non-candidate) is seen through: the code that runs for that
14
+ /// use is walked the same way, with the helper's type parameters bound to the use's type arguments (see
15
+ /// <see cref="TypeMap"/>). It is walked per member and per accessor, so reading one property never couples to what
16
+ /// another member or the setter calls, and compiler-written record members run nothing.</item>
17
+ /// </list>
18
+ /// Framework and library members end the walk. The kind of an edge is the kind of the last use; its citation is the
19
+ /// line in the component where the chain starts; <c>via</c> names the seams and seen-through types on the first path
20
+ /// found (members already walked for a component are not walked again). The helper code walked is the component's
21
+ /// <c>reaches</c>.
22
+ /// </summary>
23
+ public sealed class MemberUseResolution(LoadedWorkspace loaded, IReadOnlySet<string> components, PortResolution ports)
24
+ {
25
+ public sealed record RawEdge(string From, string To, string Kind, IReadOnlyList<string> Via, string File, int Line);
26
+
27
+ /// <summary>The edges a component's code leads to, and the helper code it runs on the way (sorted, distinct).</summary>
28
+ public sealed record Resolution(List<RawEdge> Edges, List<SourceSpan> Reaches);
29
+
30
+ // Shared by every component's walk: what a piece of syntax uses never changes within one loaded solution.
31
+ private readonly Dictionary<SyntaxNode, List<MemberUses.MemberUse>> _uses = [];
32
+ private readonly Dictionary<INamedTypeSymbol, bool> _repoSource = new(SymbolEqualityComparer.Default);
33
+
34
+ /// <summary>
35
+ /// The edges from <paramref name="from"/> reached by <paramref name="uses"/>. <paramref name="self"/> holds the
36
+ /// component and the base classes whose code counts as its own: uses of those are not coupling.
37
+ /// </summary>
38
+ public async Task<Resolution> ResolveAsync(
39
+ string from, IReadOnlySet<string> self, IEnumerable<MemberUses.MemberUse> uses, CancellationToken cancellationToken)
40
+ {
41
+ var walk = new Walk(from, self);
42
+ foreach (var use in uses)
43
+ {
44
+ await ResolveUseAsync(use.Member, use.Kind, [], use.File, use.Line, TypeMap.Empty, walk, cancellationToken);
45
+ }
46
+
47
+ return new Resolution(
48
+ walk.Edges,
49
+ walk.Reaches.OrderBy(s => s.File, StringComparer.Ordinal).ThenBy(s => s.Start).ThenBy(s => s.End).ToList());
50
+ }
51
+
52
+ // One component's walk: members already seen through (for the same type bindings) are not walked again, which also
53
+ // ends cycles.
54
+ private sealed class Walk(string from, IReadOnlySet<string> self)
55
+ {
56
+ public string From { get; } = from;
57
+ public IReadOnlySet<string> Self { get; } = self;
58
+ public HashSet<string> Visited { get; } = new(StringComparer.Ordinal);
59
+ public List<RawEdge> Edges { get; } = [];
60
+ public HashSet<SourceSpan> Reaches { get; } = [];
61
+ }
62
+
63
+ private async Task ResolveUseAsync(
64
+ ISymbol member,
65
+ string kind,
66
+ ImmutableList<string> via,
67
+ string file,
68
+ int line,
69
+ TypeMap map,
70
+ Walk walk,
71
+ CancellationToken cancellationToken)
72
+ {
73
+ // A C# 14 extension member belongs to the static class around its extension block.
74
+ var declaring = member.ContainingType is { IsExtension: true } block ? block.ContainingType : member.ContainingType;
75
+ if (declaring is null)
76
+ {
77
+ return;
78
+ }
79
+
80
+ if (map.Substitute(declaring) is INamedTypeSymbol bound)
81
+ {
82
+ declaring = bound;
83
+ }
84
+
85
+ var owner = EdgeExtraction.Normalize(declaring.OriginalDefinition);
86
+ if (!IsRepo(owner) || walk.Self.Contains(SymbolNames.FullName(owner)))
87
+ {
88
+ return;
89
+ }
90
+
91
+ if (components.Contains(SymbolNames.FullName(owner)))
92
+ {
93
+ walk.Edges.Add(new RawEdge(walk.From, SymbolNames.FullName(owner), kind, via, file, line));
94
+ return;
95
+ }
96
+
97
+ if (EdgeExtraction.IsSeam(declaring) && !member.IsStatic && kind != EdgeExtraction.New)
98
+ {
99
+ foreach (var implementation in await ports.ImplementationsAsync(declaring, cancellationToken))
100
+ {
101
+ if (SeamDispatch.ImplementationOf(implementation, declaring, member) is not { } runs)
102
+ {
103
+ continue;
104
+ }
105
+
106
+ // An inherited default body lives on the seam itself: walk it rather than resolve the seam again.
107
+ if (runs.ContainingType is { } runsIn && EdgeExtraction.IsSeam(runsIn))
108
+ {
109
+ await SeeThroughAsync(runs, kind, via.Add(declaring.Name), file, line, map, walk, cancellationToken);
110
+ }
111
+ else
112
+ {
113
+ await ResolveUseAsync(runs, kind, via.Add(declaring.Name), file, line, TypeMap.Empty, walk, cancellationToken);
114
+ }
115
+ }
116
+
117
+ return;
118
+ }
119
+
120
+ await SeeThroughAsync(member, kind, via.Add(owner.Name), file, line, map, walk, cancellationToken);
121
+ }
122
+
123
+ private async Task SeeThroughAsync(
124
+ ISymbol member,
125
+ string kind,
126
+ ImmutableList<string> via,
127
+ string file,
128
+ int line,
129
+ TypeMap map,
130
+ Walk walk,
131
+ CancellationToken cancellationToken)
132
+ {
133
+ // Compiler-written members (a record's ToString/Equals/Deconstruct, an auto-property accessor) run nothing of the
134
+ // type's own code; their declaring syntax is the whole type, which must not be walked. Constructors still run
135
+ // initializers. Using an instance field runs no code: its initializer ran when the object was constructed.
136
+ if ((member.IsImplicitlyDeclared && kind != EdgeExtraction.New) || member is IFieldSymbol { IsStatic: false })
137
+ {
138
+ return;
139
+ }
140
+
141
+ var inner = map.For(member);
142
+ var key = (kind == EdgeExtraction.New ? "new " : "") + SymbolNames.MemberId(member) + "|" + inner.Key;
143
+ if (!walk.Visited.Add(key))
144
+ {
145
+ return;
146
+ }
147
+
148
+ var (roots, runsImplicitBase) = kind == EdgeExtraction.New && member is IMethodSymbol constructor
149
+ ? WalkRoots.Construction(constructor)
150
+ : (WalkRoots.Body(member), false);
151
+ Record(roots, walk);
152
+
153
+ foreach (var root in roots)
154
+ {
155
+ foreach (var use in await UsesAsync(root, cancellationToken))
156
+ {
157
+ await ResolveUseAsync(use.Member, use.Kind, via, file, line, inner, walk, cancellationToken);
158
+ }
159
+ }
160
+
161
+ if (runsImplicitBase
162
+ && member.ContainingType.BaseType?.InstanceConstructors.FirstOrDefault(c => c.Parameters.Length == 0) is { } baseConstructor)
163
+ {
164
+ await ResolveUseAsync(baseConstructor, EdgeExtraction.New, via, file, line, inner, walk, cancellationToken);
165
+ }
166
+ }
167
+
168
+ // The walked helper code becomes citable for the component; a parameter declares a value and runs nothing.
169
+ private void Record(IEnumerable<SyntaxNode> roots, Walk walk)
170
+ {
171
+ foreach (var root in roots.Where(r => r is not (ParameterSyntax or ParameterListSyntax)))
172
+ {
173
+ var (sourceKind, relative) = CitableSource.Classify(loaded, root.SyntaxTree);
174
+ if (sourceKind == CitableSource.Kind.InRepo)
175
+ {
176
+ var lines = root.GetLocation().GetLineSpan();
177
+ walk.Reaches.Add(new SourceSpan(relative, lines.StartLinePosition.Line + 1, lines.EndLinePosition.Line + 1));
178
+ }
179
+ }
180
+ }
181
+
182
+ private async Task<List<MemberUses.MemberUse>> UsesAsync(SyntaxNode root, CancellationToken cancellationToken)
183
+ {
184
+ if (!_uses.TryGetValue(root, out var uses))
185
+ {
186
+ uses = await MemberUses.ReadAsync([root], loaded, cancellationToken);
187
+ _uses[root] = uses;
188
+ }
189
+
190
+ return uses;
191
+ }
192
+
193
+ private bool IsRepo(INamedTypeSymbol type)
194
+ {
195
+ if (!_repoSource.TryGetValue(type, out var isRepo))
196
+ {
197
+ isRepo = CitableSource.IsRepoSource(type, loaded);
198
+ _repoSource[type] = isRepo;
199
+ }
200
+
201
+ return isRepo;
202
+ }
203
+ }
@@ -0,0 +1,155 @@
1
+ using Microsoft.CodeAnalysis;
2
+ using Microsoft.CodeAnalysis.CSharp;
3
+ using Microsoft.CodeAnalysis.CSharp.Syntax;
4
+
5
+ namespace LogicalComponents;
6
+
7
+ /// <summary>
8
+ /// Reads what a piece of code uses, as members: <c>new</c> (the constructor an object creation, a <c>: this(...)</c> /
9
+ /// <c>: base(...)</c> initializer or a primary-constructor base call runs), <c>static</c> (a static member, an extension
10
+ /// method or C# 14 extension member, a user-defined operator or conversion) and <c>call</c> (an instance member used on
11
+ /// any receiver, an indexer, the enumerator a <c>foreach</c> runs). A property or indexer use is the accessor that
12
+ /// actually runs: a read is the getter, an assignment the setter, a compound assignment or increment both. Only
13
+ /// citable source is read, so generator output never contributes. What a use couples to is decided by
14
+ /// <see cref="MemberUseResolution"/>.
15
+ /// </summary>
16
+ public static class MemberUses
17
+ {
18
+ /// <summary>One use of <see cref="Member"/>, at a repo-relative file and 1-based line.</summary>
19
+ public sealed record MemberUse(ISymbol Member, string Kind, string File, int Line);
20
+
21
+ /// <summary>Every member use inside the given syntax nodes, in source order. Nodes outside the repo are skipped.</summary>
22
+ public static async Task<List<MemberUse>> ReadAsync(
23
+ IEnumerable<SyntaxNode> roots, LoadedWorkspace loaded, CancellationToken cancellationToken)
24
+ {
25
+ var uses = new List<MemberUse>();
26
+ foreach (var root in roots)
27
+ {
28
+ var (kind, file) = CitableSource.Classify(loaded, root.SyntaxTree);
29
+ if (kind != CitableSource.Kind.InRepo || loaded.Solution.GetDocument(root.SyntaxTree) is not { } document)
30
+ {
31
+ continue;
32
+ }
33
+
34
+ var model = await document.GetSemanticModelAsync(cancellationToken)
35
+ ?? throw new InvalidOperationException($"No semantic model for {file}");
36
+ foreach (var node in root.DescendantNodesAndSelf())
37
+ {
38
+ var line = node.GetLocation().GetLineSpan().StartLinePosition.Line + 1;
39
+ uses.AddRange(Uses(node, model, cancellationToken).Select(u => new MemberUse(u.Member, u.Kind, file, line)));
40
+ }
41
+ }
42
+
43
+ return uses;
44
+ }
45
+
46
+ private static IEnumerable<(ISymbol Member, string Kind)> Uses(SyntaxNode node, SemanticModel model, CancellationToken token)
47
+ {
48
+ ISymbol? Symbol() => model.GetSymbolInfo(node, token).Symbol;
49
+
50
+ switch (node)
51
+ {
52
+ case BaseObjectCreationExpressionSyntax or ConstructorInitializerSyntax or PrimaryConstructorBaseTypeSyntax:
53
+ if (Symbol() is IMethodSymbol constructor)
54
+ {
55
+ yield return (constructor, EdgeExtraction.New);
56
+ }
57
+
58
+ break;
59
+ case SimpleNameSyntax name when !IsInsideNameOf(name, model):
60
+ foreach (var use in Classify(Symbol(), name))
61
+ {
62
+ yield return use;
63
+ }
64
+
65
+ break;
66
+ case ElementAccessExpressionSyntax when Symbol() is IPropertySymbol indexer:
67
+ foreach (var accessor in AccessorsThatRun(indexer, node))
68
+ {
69
+ yield return (accessor, EdgeExtraction.Call);
70
+ }
71
+
72
+ break;
73
+ case BinaryExpressionSyntax or PrefixUnaryExpressionSyntax or PostfixUnaryExpressionSyntax
74
+ or CastExpressionSyntax or AssignmentExpressionSyntax
75
+ when Symbol() is IMethodSymbol { MethodKind: MethodKind.UserDefinedOperator or MethodKind.Conversion } op:
76
+ yield return (op, EdgeExtraction.Static);
77
+ break;
78
+ case CommonForEachStatementSyntax loop when model.GetForEachStatementInfo(loop).GetEnumeratorMethod is { } enumerator:
79
+ yield return (enumerator, enumerator.IsStatic ? EdgeExtraction.Static : EdgeExtraction.Call);
80
+ break;
81
+ }
82
+ }
83
+
84
+ /// <summary>
85
+ /// A symbol a name refers to, as uses: static or extension members are <c>static</c> (a classic extension method is
86
+ /// seen as its unreduced static form), other members are <c>call</c>, a property is the accessors that run. Locals,
87
+ /// parameters, types, namespaces and consts (copied into the caller at compile time) are not uses.
88
+ /// </summary>
89
+ private static IEnumerable<(ISymbol, string)> Classify(ISymbol? symbol, SyntaxNode usage)
90
+ {
91
+ var kind = symbol is not null && (symbol.IsStatic || symbol.ContainingType is { IsExtension: true })
92
+ ? EdgeExtraction.Static
93
+ : EdgeExtraction.Call;
94
+ switch (symbol)
95
+ {
96
+ case IFieldSymbol { IsConst: true }:
97
+ case IMethodSymbol { MethodKind: MethodKind.LocalFunction or MethodKind.AnonymousFunction }:
98
+ break;
99
+ case IMethodSymbol { ReducedFrom: { } extension }:
100
+ yield return (extension, EdgeExtraction.Static);
101
+ break;
102
+ case IPropertySymbol property:
103
+ foreach (var accessor in AccessorsThatRun(property, usage))
104
+ {
105
+ yield return (accessor, kind);
106
+ }
107
+
108
+ break;
109
+ case IMethodSymbol or IFieldSymbol or IEventSymbol:
110
+ yield return (symbol, kind);
111
+ break;
112
+ }
113
+ }
114
+
115
+ /// <summary>
116
+ /// The accessors a property or indexer use runs, from where it stands: the target of <c>=</c> (including an object
117
+ /// initializer) runs the setter; a compound assignment, <c>++</c>/<c>--</c>, or a <c>ref</c>/<c>out</c> argument runs
118
+ /// both; anything else is a read and runs the getter. An accessor the property does not have runs nothing.
119
+ /// </summary>
120
+ private static IEnumerable<IMethodSymbol> AccessorsThatRun(IPropertySymbol property, SyntaxNode usage)
121
+ {
122
+ // The whole access expression: `a.B` for the name B, `a?.B` for a conditional access, the name itself otherwise.
123
+ var access = usage.Parent switch
124
+ {
125
+ MemberAccessExpressionSyntax member when member.Name == usage => member,
126
+ MemberBindingExpressionSyntax binding => (SyntaxNode)binding,
127
+ _ => usage,
128
+ };
129
+
130
+ var (reads, writes) = access.Parent switch
131
+ {
132
+ AssignmentExpressionSyntax assignment when assignment.Left == access =>
133
+ (!assignment.IsKind(SyntaxKind.SimpleAssignmentExpression), true),
134
+ PrefixUnaryExpressionSyntax or PostfixUnaryExpressionSyntax => (true, true),
135
+ ArgumentSyntax { RefKindKeyword.RawKind: not 0 } => (true, true),
136
+ _ => (true, false),
137
+ };
138
+
139
+ if (reads && property.GetMethod is { } getter)
140
+ {
141
+ yield return getter;
142
+ }
143
+
144
+ if (writes && property.SetMethod is { } setter)
145
+ {
146
+ yield return setter;
147
+ }
148
+ }
149
+
150
+ // nameof(Foo.Bar) mentions a member without using it.
151
+ private static bool IsInsideNameOf(SyntaxNode node, SemanticModel model) =>
152
+ node.Ancestors().OfType<InvocationExpressionSyntax>().Any(invocation =>
153
+ invocation.Expression is IdentifierNameSyntax { Identifier.Text: "nameof" }
154
+ && model.GetSymbolInfo(invocation).Symbol is null);
155
+ }
@@ -0,0 +1,75 @@
1
+ using Microsoft.CodeAnalysis;
2
+ using Microsoft.CodeAnalysis.FindSymbols;
3
+
4
+ namespace LogicalComponents;
5
+
6
+ /// <summary>
7
+ /// Maps a seam (an interface or abstract class) to the concrete classes behind it in the loaded solution. Test
8
+ /// projects were removed at load time, so test doubles never appear. Asking the type system rather than parsing DI
9
+ /// registrations covers every registration style (instance, factory, forwarding) at once.
10
+ /// A constructed generic seam (<c>IHandler&lt;Order&gt;</c>) resolves only to classes implementing exactly that construction,
11
+ /// or an open generic one (<c>LoggingHandler&lt;T&gt; : IHandler&lt;T&gt;</c>). Results are cached per construction and sorted.
12
+ /// </summary>
13
+ public sealed class PortResolution(Solution solution)
14
+ {
15
+ private readonly Dictionary<string, IReadOnlyList<INamedTypeSymbol>> _cache = new(StringComparer.Ordinal);
16
+
17
+ public async Task<IReadOnlyList<INamedTypeSymbol>> ImplementationsAsync(
18
+ INamedTypeSymbol seam, CancellationToken cancellationToken)
19
+ {
20
+ var key = Display(seam);
21
+ if (_cache.TryGetValue(key, out var cached))
22
+ {
23
+ return cached;
24
+ }
25
+
26
+ var definition = seam.OriginalDefinition;
27
+ IEnumerable<INamedTypeSymbol> found = definition.TypeKind == TypeKind.Interface
28
+ ? (await SymbolFinder.FindImplementationsAsync(definition, solution, cancellationToken: cancellationToken))
29
+ .OfType<INamedTypeSymbol>()
30
+ : await SymbolFinder.FindDerivedClassesAsync(definition, solution, transitive: true, cancellationToken: cancellationToken);
31
+
32
+ var implementations = found
33
+ .Where(t => t.TypeKind == TypeKind.Class && !t.IsAbstract)
34
+ .Select(t => t.OriginalDefinition)
35
+ .Where(t => ImplementsConstruction(t, seam))
36
+ .DistinctBy(SymbolNames.FullName)
37
+ .OrderBy(SymbolNames.FullName, StringComparer.Ordinal)
38
+ .ToList();
39
+ _cache[key] = implementations;
40
+ return implementations;
41
+ }
42
+
43
+ private static bool ImplementsConstruction(INamedTypeSymbol implementation, INamedTypeSymbol seam)
44
+ {
45
+ if (!seam.IsGenericType || seam.TypeArguments.All(a => a is ITypeParameterSymbol))
46
+ {
47
+ return true;
48
+ }
49
+
50
+ var definition = SymbolNames.FullName(seam.OriginalDefinition);
51
+ var wanted = Display(seam);
52
+ return Supertypes(implementation, seam.TypeKind).Any(s =>
53
+ SymbolNames.FullName(s.OriginalDefinition) == definition
54
+ && (Display(s) == wanted || s.TypeArguments.Any(a => a is ITypeParameterSymbol)));
55
+ }
56
+
57
+ private static IEnumerable<INamedTypeSymbol> Supertypes(INamedTypeSymbol type, TypeKind seamKind)
58
+ {
59
+ if (seamKind == TypeKind.Interface)
60
+ {
61
+ return type.AllInterfaces;
62
+ }
63
+
64
+ var bases = new List<INamedTypeSymbol>();
65
+ for (var current = type.BaseType; current is not null; current = current.BaseType)
66
+ {
67
+ bases.Add(current);
68
+ }
69
+
70
+ return bases;
71
+ }
72
+
73
+ // Compared as text: symbols of the same type seen from two projects' compilations are not always the same instance.
74
+ private static string Display(ITypeSymbol type) => type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
75
+ }
@@ -0,0 +1,27 @@
1
+ using LogicalComponents;
2
+
3
+ // Entry point: dispatches to one command per pipeline step. Anything unknown prints usage and exits 1.
4
+ // candidates, extract and render report on stderr (their artifact is a file); the others report on stdout.
5
+ return args switch
6
+ {
7
+ ["candidates", .. var rest] => await CandidatesCommand.RunAsync(rest, Console.Error),
8
+ ["classify-batches", .. var rest] => await ClassifyBatchesCommand.RunAsync(rest, Console.Out),
9
+ ["classify-merge", .. var rest] => await ClassifyMergeCommand.RunAsync(rest, Console.Out),
10
+ ["extract", .. var rest] => await ExtractCommand.RunAsync(rest, Console.Error),
11
+ ["batches", .. var rest] => await BatchesCommand.RunAsync(rest, Console.Out),
12
+ ["prune", .. var rest] => await PruneCommand.RunAsync(rest, Console.Out),
13
+ ["render", .. var rest] => await RenderCommand.RunAsync(rest, Console.Error),
14
+ _ => PrintUsage(),
15
+ };
16
+
17
+ static int PrintUsage()
18
+ {
19
+ Console.Error.WriteLine(CandidatesCommand.Usage);
20
+ Console.Error.WriteLine(ClassifyBatchesCommand.Usage);
21
+ Console.Error.WriteLine(ClassifyMergeCommand.Usage);
22
+ Console.Error.WriteLine(ExtractCommand.Usage);
23
+ Console.Error.WriteLine(BatchesCommand.Usage);
24
+ Console.Error.WriteLine(PruneCommand.Usage);
25
+ Console.Error.WriteLine(RenderCommand.Usage);
26
+ return 1;
27
+ }
@@ -0,0 +1,76 @@
1
+ using System.Text.RegularExpressions;
2
+
3
+ namespace LogicalComponents;
4
+
5
+ /// <summary>
6
+ /// Pure rules for which loaded projects the extractor keeps: no test projects, and one project per
7
+ /// multi-targeted csproj. Kept free of Roslyn types so they are unit-testable from plain strings.
8
+ /// </summary>
9
+ public static partial class ProjectFilters
10
+ {
11
+ /// <summary>
12
+ /// A test project lives under a <c>tests</c>/<c>test</c> folder, is named like one
13
+ /// (<c>.Tests</c>, <c>.UnitTests</c>, <c>.IntegrationTests</c>, <c>.Test</c>, <c>.Specs</c>), or its project
14
+ /// file carries a test marker (test SDK, <c>IsTestProject</c>, or a test-framework package).
15
+ /// Test-support libraries such as <c>Foo.Testing</c> are deliberately kept: nothing here can tell them apart
16
+ /// from source, and their types can be excluded through config.
17
+ /// </summary>
18
+ public static bool IsTestProject(string relativePath, string projectFileText)
19
+ {
20
+ var segments = relativePath.Split('/', '\\');
21
+ if (segments.Any(s => s.Equals("tests", StringComparison.OrdinalIgnoreCase)
22
+ || s.Equals("test", StringComparison.OrdinalIgnoreCase)))
23
+ {
24
+ return true;
25
+ }
26
+
27
+ return TestProjectName().IsMatch(Path.GetFileNameWithoutExtension(relativePath))
28
+ || TestProjectMarker().IsMatch(projectFileText);
29
+ }
30
+
31
+ /// <summary>
32
+ /// Orders the target framework in a loaded multi-target project name such as <c>Foo(net10.0)</c>.
33
+ /// Families rank .NET Framework &lt; netstandard &lt; netcoreapp &lt; net5+; versions order within a family.
34
+ /// </summary>
35
+ public static (int Family, Version Version) TargetFrameworkRank(string loadedProjectName)
36
+ {
37
+ var match = TargetFrameworkSuffix().Match(loadedProjectName);
38
+ if (!match.Success)
39
+ {
40
+ return (0, new Version(0, 0));
41
+ }
42
+
43
+ // Drop an OS suffix: net9.0-windows ranks as net9.0.
44
+ var tfm = match.Groups["tfm"].Value.ToLowerInvariant().Split('-')[0];
45
+ return tfm switch
46
+ {
47
+ _ when tfm.StartsWith("netstandard") => (1, ParseVersion(tfm["netstandard".Length..])),
48
+ _ when tfm.StartsWith("netcoreapp") => (2, ParseVersion(tfm["netcoreapp".Length..])),
49
+ _ when tfm.Contains('.') => (3, ParseVersion(tfm["net".Length..])),
50
+ // .NET Framework monikers pack the version into digits: net472 is 4.7.2.
51
+ _ => (0, ParseVersion(string.Join('.', tfm["net".Length..].ToCharArray()))),
52
+ };
53
+ }
54
+
55
+ /// <summary><c>Foo(net10.0)</c> becomes <c>Foo</c>; a name without a framework suffix is returned as-is.</summary>
56
+ public static string StripTargetFramework(string loadedProjectName)
57
+ {
58
+ var match = TargetFrameworkSuffix().Match(loadedProjectName);
59
+ return match.Success ? match.Groups["name"].Value : loadedProjectName;
60
+ }
61
+
62
+ private static Version ParseVersion(string text) =>
63
+ Version.TryParse(text.Contains('.') ? text : text + ".0", out var version) ? version : new Version(0, 0);
64
+
65
+ // Case-sensitive on purpose: "Foo.Contest" and "Latest.Feeds" must not look like test projects.
66
+ [GeneratedRegex(@"\.\w*Tests?$|\.Specs?$")]
67
+ private static partial Regex TestProjectName();
68
+
69
+ [GeneratedRegex(
70
+ @"<IsTestProject>\s*true\s*</IsTestProject>|Sdk=""MSTest\.Sdk|Include=""(Microsoft\.NET\.Test\.Sdk|xunit|xunit\.v3|xunit\.core|xunit\.v3\.core|NUnit|MSTest|MSTest\.TestFramework|Microsoft\.Testing\.Platform)""",
71
+ RegexOptions.IgnoreCase)]
72
+ private static partial Regex TestProjectMarker();
73
+
74
+ [GeneratedRegex(@"^(?<name>.+)\((?<tfm>net[^)]*)\)$")]
75
+ private static partial Regex TargetFrameworkSuffix();
76
+ }
@@ -0,0 +1,132 @@
1
+ using System.Text.Json;
2
+
3
+ namespace LogicalComponents;
4
+
5
+ /// <summary>
6
+ /// <c>prune --resp &lt;dir&gt; --verify &lt;dir&gt; --out &lt;dir&gt;</c>: applies the verifier agents' verdicts. For every
7
+ /// <c>resp/batch-NN.json</c> it reads <c>verify/batch-NN.json</c> — <c>{ "&lt;id&gt;": [ { "item": 1, "supported": true,
8
+ /// "reason": "..." } ] }</c> — and writes the batch without its unsupported items to <c>--out</c>. The agents' files are
9
+ /// never edited, so pruning is repeatable. Every item needs exactly one verdict: an unjudged claim is not verified, so
10
+ /// any gap fails the step (exit 3) before anything is written. Exit codes: 0 written, 1 usage, 3 verdicts incomplete.
11
+ /// </summary>
12
+ public static class PruneCommand
13
+ {
14
+ public const string Usage = "usage: LogicalComponents prune --resp <dir> --verify <dir> --out <dir>";
15
+
16
+ public sealed record Verdict(int Item, bool Supported, string? Reason);
17
+
18
+ private static readonly JsonSerializerOptions ReadOptions = new()
19
+ {
20
+ PropertyNameCaseInsensitive = true,
21
+ ReadCommentHandling = JsonCommentHandling.Skip,
22
+ AllowTrailingCommas = true,
23
+ AllowDuplicateProperties = false,
24
+ };
25
+
26
+ public static async Task<int> RunAsync(string[] args, TextWriter output)
27
+ {
28
+ if (args is not ["--resp", var respDir, "--verify", var verifyDir, "--out", var outDir]
29
+ || !Directory.Exists(respDir) || !Directory.Exists(verifyDir))
30
+ {
31
+ await output.WriteLineAsync(Usage);
32
+ return 1;
33
+ }
34
+
35
+ var problems = new List<string>();
36
+ var pruned = new List<(string File, SortedDictionary<string, List<Responsibility>> Kept)>();
37
+ var removed = new List<string>();
38
+ var emptied = new List<string>();
39
+
40
+ foreach (var respFile in Directory.EnumerateFiles(respDir, "batch-*.json").Order(StringComparer.Ordinal))
41
+ {
42
+ var name = Path.GetFileName(respFile);
43
+ var batch = ResponsibilityBatches.Load([respFile], ReadOptions);
44
+ problems.AddRange(batch.Problems);
45
+ var verdicts = ReadVerdicts(Path.Combine(verifyDir, name), name, problems);
46
+ if (verdicts is null)
47
+ {
48
+ continue;
49
+ }
50
+
51
+ var kept = new SortedDictionary<string, List<Responsibility>>(StringComparer.Ordinal);
52
+ foreach (var (id, items) in batch.Responsibilities.OrderBy(r => r.Key, StringComparer.Ordinal))
53
+ {
54
+ var judged = verdicts.GetValueOrDefault(id) ?? [];
55
+ problems.AddRange(judged.Where(v => v.Item < 1 || v.Item > items.Count)
56
+ .Select(v => $"{id}[{v.Item}]: verdict for an item that does not exist ({name})"));
57
+
58
+ kept[id] = [];
59
+ for (var item = 1; item <= items.Count; item++)
60
+ {
61
+ var forItem = judged.Where(v => v.Item == item).ToList();
62
+ if (forItem.Count != 1)
63
+ {
64
+ problems.Add($"{id}[{item}]: {(forItem.Count == 0 ? "no verdict" : "more than one verdict")} ({name})");
65
+ }
66
+ else if (forItem[0].Supported)
67
+ {
68
+ kept[id].Add(items[item - 1]);
69
+ }
70
+ else
71
+ {
72
+ removed.Add($"removed {id}[{item}]: {forItem[0].Reason ?? "(no reason given)"}");
73
+ }
74
+ }
75
+
76
+ if (items.Count > 0 && kept[id].Count == 0)
77
+ {
78
+ emptied.Add($"empty {id}: every responsibility was unsupported");
79
+ }
80
+ }
81
+
82
+ problems.AddRange(verdicts.Keys.Where(id => !batch.Responsibilities.ContainsKey(id))
83
+ .Order(StringComparer.Ordinal)
84
+ .Select(id => $"{id}: verdicts for a component the batch does not answer ({name})"));
85
+ pruned.Add((name, kept));
86
+ }
87
+
88
+ if (problems.Count > 0)
89
+ {
90
+ foreach (var problem in problems)
91
+ {
92
+ await output.WriteLineAsync(problem);
93
+ }
94
+
95
+ return 3;
96
+ }
97
+
98
+ Directory.CreateDirectory(outDir);
99
+ foreach (var (file, kept) in pruned)
100
+ {
101
+ await File.WriteAllBytesAsync(Path.Combine(outDir, file), ComponentsFile.ToJson(kept));
102
+ }
103
+
104
+ foreach (var line in removed.Concat(emptied))
105
+ {
106
+ await output.WriteLineAsync(line);
107
+ }
108
+
109
+ await output.WriteLineAsync($"{removed.Count} removed, {emptied.Count} empty");
110
+ return 0;
111
+ }
112
+
113
+ private static Dictionary<string, List<Verdict>>? ReadVerdicts(string path, string name, List<string> problems)
114
+ {
115
+ if (!File.Exists(path))
116
+ {
117
+ problems.Add($"{name}: no verdict file");
118
+ return null;
119
+ }
120
+
121
+ try
122
+ {
123
+ var verdicts = JsonSerializer.Deserialize<Dictionary<string, List<Verdict>?>>(File.ReadAllText(path), ReadOptions) ?? [];
124
+ return verdicts.ToDictionary(v => v.Key, v => v.Value ?? [], StringComparer.Ordinal);
125
+ }
126
+ catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException)
127
+ {
128
+ problems.Add($"{name}: not a valid verdict file ({e.Message})");
129
+ return null;
130
+ }
131
+ }
132
+ }