archsight 0.5.2 → 0.5.3

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 (49) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +2 -0
  3. data/docs/archimate.md +1 -1
  4. data/docs/diagram.md +12 -2
  5. data/docs/modeling.md +16 -5
  6. data/docs/search.md +19 -0
  7. data/lib/archsight/annotations/capacity_annotations.rb +15 -0
  8. data/lib/archsight/database.rb +1 -1
  9. data/lib/archsight/diagram/graph/attributes.rb +11 -3
  10. data/lib/archsight/diagram/graph/builder.rb +1 -0
  11. data/lib/archsight/diagram/graph/node.rb +26 -2
  12. data/lib/archsight/diagram/layout/expander.rb +39 -0
  13. data/lib/archsight/diagram/layout.rb +11 -0
  14. data/lib/archsight/diagram/legend/inventory.rb +6 -2
  15. data/lib/archsight/diagram/parser.rb +1 -1
  16. data/lib/archsight/diagram/renderer/node_renderer.rb +6 -1
  17. data/lib/archsight/diagram/renderer/stylesheet.rb +2 -0
  18. data/lib/archsight/diagram/style/representers.rb +14 -0
  19. data/lib/archsight/diagram/support/text_metrics.rb +38 -0
  20. data/lib/archsight/import/handlers/repository.rb +25 -0
  21. data/lib/archsight/linter.rb +13 -2
  22. data/lib/archsight/mcp/analyze_resource_tool.rb +145 -43
  23. data/lib/archsight/mcp/base.rb +112 -5
  24. data/lib/archsight/mcp/execute_analysis_tool.rb +11 -1
  25. data/lib/archsight/mcp/query_hints.rb +119 -0
  26. data/lib/archsight/mcp/query_tool.rb +90 -5
  27. data/lib/archsight/mcp/relations_tool.rb +89 -0
  28. data/lib/archsight/mcp/resource_doc_tool.rb +39 -20
  29. data/lib/archsight/mcp/summary_tool.rb +106 -0
  30. data/lib/archsight/mcp.rb +2 -0
  31. data/lib/archsight/query/ast.rb +28 -0
  32. data/lib/archsight/query/evaluator.rb +2 -0
  33. data/lib/archsight/query/lexer.rb +2 -2
  34. data/lib/archsight/query/parser.rb +45 -0
  35. data/lib/archsight/query/text_search.rb +38 -0
  36. data/lib/archsight/query.rb +1 -0
  37. data/lib/archsight/resources/base.rb +12 -0
  38. data/lib/archsight/resources/business_contract.rb +8 -1
  39. data/lib/archsight/resources/config.rb +28 -0
  40. data/lib/archsight/resources/motivation_requirement.rb +10 -0
  41. data/lib/archsight/resources/technology_device.rb +14 -0
  42. data/lib/archsight/resources/technology_equipment.rb +3 -1
  43. data/lib/archsight/resources/technology_node.rb +8 -1
  44. data/lib/archsight/summary/builder.rb +204 -0
  45. data/lib/archsight/summary/lens.rb +224 -0
  46. data/lib/archsight/summary.rb +11 -0
  47. data/lib/archsight/version.rb +1 -1
  48. data/lib/archsight/web/application.rb +2 -0
  49. metadata +9 -1
@@ -23,6 +23,22 @@ class Archsight::MCP::AnalyzeResourceTool < FastMcp::Tool
23
23
  kind/verb/depth with summary statistics. Essential for change impact assessment.
24
24
  Example: kind="ApplicationInterface", name="Kubernetes:RestAPI", impact=true
25
25
 
26
+ EXAMPLES:
27
+ kind="ApplicationComponent", name="X", depth=2 - what X depends on and what depends on X, two levels
28
+ kind="ApplicationComponent", name="X", impact=true, exclude_kinds=["Page","PageMenu"], depth=2, limit=50 -
29
+ a small, filtered impact list; direction="out" turns it around (what X relies on)
30
+
31
+ TYPICAL FLOW: find the exact name with query (output='brief'), call this tool in basic mode, and go to
32
+ depth or impact only for the question that needs it. For just the direct relations of one verb use the
33
+ relations tool instead.
34
+
35
+ PITFALLS:
36
+ • kind and name are exact and case-sensitive; a wrong name returns 'did you mean' suggestions across all kinds.
37
+ • impact=true on a hub resource can list hundreds of entries: set limit, depth and exclude_kinds first.
38
+ The summary (counts by kind) always covers everything, even when the list is cut.
39
+ • depth > 0 returns the whole tree both ways and grows fast; keep it at 1 to 3.
40
+ • The response is cut when it exceeds the size budget; a 'truncated' note says how to narrow it.
41
+
26
42
  RESOURCE KINDS: TechnologyArtifact, ApplicationComponent, ApplicationInterface,
27
43
  ApplicationService, MotivationRequirement, ComplianceEvidence, and more.
28
44
  DESC
@@ -46,6 +62,22 @@ class Archsight::MCP::AnalyzeResourceTool < FastMcp::Tool
46
62
  "if this resource is deprecated or removed. Returns grouped results with statistics. " \
47
63
  "Useful for change management and deprecation planning."
48
64
  )
65
+ optional(:kinds).array(:string).description(
66
+ "Impact mode: only follow and report these kinds (e.g. ['ApplicationComponent']). Default: all kinds."
67
+ )
68
+ optional(:exclude_kinds).array(:string).description(
69
+ "Impact mode: skip these kinds and do not follow through them (e.g. ['Page', 'PageMenu'])."
70
+ )
71
+ optional(:verbs).array(:string).description(
72
+ "Impact mode: only follow these relation verbs (e.g. ['realizedThrough', 'servedBy'])."
73
+ )
74
+ optional(:direction).filled(:string).description(
75
+ "Impact mode: 'in' = what depends on this resource (default), 'out' = what this resource depends on."
76
+ )
77
+ optional(:limit).filled(:integer).description(
78
+ "Impact mode: maximum entries listed (nearest first). The summary (counts by kind) always covers all of " \
79
+ "them and says how many were left out."
80
+ )
49
81
  optional(:group_by).filled(:string).description(
50
82
  "How to group impact analysis results: " \
51
83
  "'kind' = group by resource type (default, good for understanding scope), " \
@@ -54,19 +86,21 @@ class Archsight::MCP::AnalyzeResourceTool < FastMcp::Tool
54
86
  )
55
87
  end
56
88
 
57
- def call(kind:, name:, depth: 0, impact: false, group_by: "kind")
89
+ def call(kind:, name:, depth: 0, impact: false, group_by: "kind", kinds: nil, exclude_kinds: nil, verbs: nil,
90
+ direction: "in", limit: nil)
58
91
  db = Archsight::MCP.db
59
92
 
60
93
  klass = Archsight::Resources[kind]
61
94
  return error_response("Unknown resource kind: #{kind}") unless klass
62
95
 
63
96
  instance = db.instance_by_kind(kind, name)
64
- return error_response("Resource not found: #{kind}/#{name}") unless instance
97
+ return not_found_response(kind, name) unless instance
65
98
 
66
99
  depth = [[depth.to_i, 0].max, 10].min # Clamp to 0-10
67
100
 
68
101
  if impact
69
- build_impact_analysis(db, instance, kind, name, depth, group_by)
102
+ filter = { kinds: kinds, exclude_kinds: exclude_kinds, verbs: verbs&.map(&:to_s), direction: direction.to_s }
103
+ build_impact_analysis(db, instance, kind, name, depth, group_by, filter, limit)
70
104
  else
71
105
  build_resource_analysis(db, instance, kind, name, depth)
72
106
  end
@@ -76,6 +110,13 @@ class Archsight::MCP::AnalyzeResourceTool < FastMcp::Tool
76
110
 
77
111
  private
78
112
 
113
+ # Not found: the closest names across all kinds, so a typo or a wrong kind is one call away from the answer
114
+ def not_found_response(kind, name)
115
+ suggestions = Archsight::MCP.suggest(name, kind: kind)
116
+ message = ["Resource not found: #{kind}/#{name}", Archsight::MCP.did_you_mean(suggestions)].compact.join(". ")
117
+ JSON.pretty_generate({ error: "Error", message: message, suggestions: suggestions })
118
+ end
119
+
79
120
  def error_response(message, error_type = "Error", backtrace = nil)
80
121
  result = {
81
122
  error: error_type,
@@ -91,7 +132,7 @@ class Archsight::MCP::AnalyzeResourceTool < FastMcp::Tool
91
132
  name: name,
92
133
  spec: instance.spec,
93
134
  annotations: instance.annotations
94
- }
135
+ }.merge(Archsight::MCP.source_info(instance))
95
136
 
96
137
  if depth.positive?
97
138
  # Include dependency trees
@@ -101,33 +142,22 @@ class Archsight::MCP::AnalyzeResourceTool < FastMcp::Tool
101
142
  else
102
143
  # Just direct relations
103
144
  result[:relations] = Archsight::MCP.extract_relations(instance)
145
+ result[:related] = Archsight::MCP.related_sources(instance)
104
146
  result[:has_relations] = instance.has_relations?
105
147
  end
106
148
 
107
149
  JSON.pretty_generate(result)
108
150
  end
109
151
 
110
- def build_impact_analysis(db, instance, kind, name, max_depth, group_by)
152
+ def build_impact_analysis(db, instance, kind, name, max_depth, group_by, filter, limit)
111
153
  max_depth = 5 if max_depth.zero? # Default depth for impact analysis
154
+ limit = [limit.to_i, 1].max if limit
112
155
 
113
- # Collect all impacted resources
114
156
  impacted = []
115
- visited = Set.new
116
- collect_impact(db, instance, 0, max_depth, visited, impacted)
117
-
118
- # Group results
119
- grouped = case group_by
120
- when "verb"
121
- impacted.group_by { |i| i[:verb].to_s }
122
- when "kind"
123
- impacted.group_by { |i| i[:kind] }
124
- when "depth"
125
- impacted.group_by { |i| i[:depth] }
126
- else
127
- { "all" => impacted }
128
- end
129
-
130
- # Calculate summary statistics
157
+ edges = ImpactEdges.new(db, filter)
158
+ collect_impact(edges, instance, 0, max_depth, Set.new, impacted)
159
+
160
+ # Summary statistics always cover everything found, whatever is listed
131
161
  summary = {
132
162
  total_impacted: impacted.length,
133
163
  unique_resources: impacted.map { |i| "#{i[:kind]}/#{i[:name]}" }.uniq.length,
@@ -138,44 +168,116 @@ class Archsight::MCP::AnalyzeResourceTool < FastMcp::Tool
138
168
  result = {
139
169
  target: { kind: kind, name: name },
140
170
  analysis: "impact",
171
+ direction: filter[:direction],
141
172
  max_depth: max_depth,
142
173
  group_by: group_by,
143
- summary: summary,
144
- impacted_resources: grouped
174
+ summary: summary
145
175
  }
176
+ result[:filters] = filter.slice(:kinds, :exclude_kinds, :verbs).compact unless filter.slice(:kinds, :exclude_kinds, :verbs).compact.empty?
146
177
 
147
- JSON.pretty_generate(result)
178
+ ordered = impacted.each_with_index.sort_by { |entry, index| [entry[:depth], index] }.map(&:first)
179
+ shown = limit ? ordered.take(limit) : ordered
180
+ result[:impacted_resources] = group_impacted(shown, group_by)
181
+
182
+ Archsight::MCP.fit(truncation_note(result, impacted.length, shown.length)) do |attempt|
183
+ keep = [shown.length / (2**attempt), 1].max
184
+ result[:impacted_resources] = group_impacted(ordered.take(keep), group_by)
185
+ truncation_note(result, impacted.length, keep, budget: true)
186
+ end
148
187
  end
149
188
 
150
- def collect_impact(db, resource, current_depth, max_depth, visited, collector)
151
- return if current_depth >= max_depth
189
+ def group_impacted(entries, group_by)
190
+ case group_by
191
+ when "verb" then entries.group_by { |i| i[:verb].to_s }
192
+ when "kind" then entries.group_by { |i| i[:kind] }
193
+ when "depth" then entries.group_by { |i| i[:depth] }
194
+ else { "all" => entries }
195
+ end
196
+ end
152
197
 
153
- key = "#{resource.class.to_s.split("::").last}/#{resource.name}"
154
- return if visited.include?(key)
198
+ # Says how many entries are left out and how to narrow the request
199
+ def truncation_note(result, total, shown, budget: false)
200
+ return result if shown >= total
155
201
 
156
- visited.add(key)
202
+ reason = budget ? "size budget" : "limit"
203
+ result.merge(
204
+ truncated: "#{total - shown} more entries not listed (#{reason}); #{shown} of #{total} shown, nearest first. " \
205
+ "Narrow with exclude_kinds, kinds, verbs, a smaller depth or direction."
206
+ )
207
+ end
157
208
 
158
- db.instances.each_value do |instances_hash|
159
- instances_hash.each_value do |other|
160
- next if other == resource
209
+ # The relations to follow from a resource, filtered by kind and verb. `in` finds the resources that point at it
210
+ # (via an index over all relations, built once), `out` the ones it points at.
211
+ class ImpactEdges
212
+ def initialize(db, filter)
213
+ @db = db
214
+ @filter = filter
215
+ @incoming = nil
216
+ end
161
217
 
162
- other.class.relations.each do |verb, kind_name, _|
163
- rels = other.relations(verb, kind_name)
164
- next unless rels.include?(resource)
218
+ # [[resource, verb], ...]
219
+ def next_from(resource)
220
+ pairs = @filter[:direction] == "out" ? outgoing(resource) : incoming(resource)
221
+ pairs.select { |other, verb| allowed?(other, verb) }
222
+ end
165
223
 
166
- collector << {
167
- kind: other.class.to_s.split("::").last,
168
- name: other.name,
169
- verb: verb,
170
- depth: current_depth + 1
171
- }
224
+ private
172
225
 
173
- collect_impact(db, other, current_depth + 1, max_depth, visited.dup, collector)
226
+ def allowed?(other, verb)
227
+ kind = other.class.to_s.split("::").last
228
+ return false if @filter[:kinds] && !@filter[:kinds].empty? && !@filter[:kinds].include?(kind)
229
+ return false if @filter[:exclude_kinds]&.include?(kind)
230
+
231
+ @filter[:verbs].nil? || @filter[:verbs].empty? || @filter[:verbs].include?(verb.to_s)
232
+ end
233
+
234
+ def outgoing(resource)
235
+ resource.class.relations.flat_map do |verb, kind_name, _|
236
+ resource.relations(verb, kind_name).map { |target| [target, verb] }
237
+ end
238
+ end
239
+
240
+ def incoming(resource)
241
+ build_index unless @incoming
242
+ @incoming[resource] || []
243
+ end
244
+
245
+ def build_index
246
+ @incoming = {}
247
+ @db.instances.each_value do |instances_hash|
248
+ instances_hash.each_value do |other|
249
+ other.class.relations.each do |verb, kind_name, _|
250
+ other.relations(verb, kind_name).each do |target|
251
+ next if target == other
252
+
253
+ (@incoming[target] ||= []) << [other, verb]
254
+ end
255
+ end
174
256
  end
175
257
  end
176
258
  end
177
259
  end
178
260
 
261
+ def collect_impact(edges, resource, current_depth, max_depth, visited, collector)
262
+ return if current_depth >= max_depth
263
+
264
+ key = "#{resource.class.to_s.split("::").last}/#{resource.name}"
265
+ return if visited.include?(key)
266
+
267
+ visited.add(key)
268
+
269
+ edges.next_from(resource).each do |other, verb|
270
+ collector << {
271
+ kind: other.class.to_s.split("::").last,
272
+ name: other.name,
273
+ verb: verb,
274
+ depth: current_depth + 1
275
+ }
276
+
277
+ collect_impact(edges, other, current_depth + 1, max_depth, visited.dup, collector)
278
+ end
279
+ end
280
+
179
281
  def build_dependency_tree(db, resource, direction, current_depth, max_depth, visited)
180
282
  return [] if current_depth >= max_depth
181
283
 
@@ -6,10 +6,45 @@ require_relative "../resources"
6
6
 
7
7
  # Shared database and helper methods for MCP tools
8
8
  module Archsight::MCP
9
+ # Size budget of a tool response (characters of JSON). Larger results are cut down, with a pointer on how to
10
+ # narrow the request, because an agent cannot read a payload this size anyway.
11
+ MAX_RESPONSE_CHARS = 100_000
12
+
9
13
  class << self
10
14
  attr_accessor :db
11
15
 
12
- def complete_summary(resource, omit_kind: false)
16
+ # Pretty JSON of `result`; when it exceeds the budget, `shrink` (called with the attempt number, 1, 2, ...) must
17
+ # return a smaller result. Gives up after a few attempts with the last, smallest one.
18
+ def fit(result, max_chars: MAX_RESPONSE_CHARS, attempts: 8)
19
+ json = JSON.pretty_generate(result)
20
+ attempt = 0
21
+ while json.length > max_chars && attempt < attempts
22
+ attempt += 1
23
+ result = yield(attempt)
24
+ json = JSON.pretty_generate(result)
25
+ end
26
+ json
27
+ end
28
+
29
+ # The first sentence or line of a (markdown) description, at most `max` characters
30
+ def one_liner(text, max: 140)
31
+ line = text.to_s.strip.split(/\n\s*\n|\n/).first.to_s.strip
32
+ line = line[/\A.+?[.!?](?=\s|\z)/m] || line
33
+ line.length > max ? "#{line[0, max - 1].rstrip}…" : line
34
+ end
35
+
36
+ # `complete_summary` reduced to the given annotation keys and relation verbs (nil = everything)
37
+ def project(summary, fields)
38
+ return summary if fields.nil? || fields.empty?
39
+
40
+ wanted = fields.map(&:to_s)
41
+ summary = summary.dup
42
+ summary[:metadata] = { annotations: summary[:metadata][:annotations].slice(*wanted) } if summary[:metadata]
43
+ summary[:spec] = summary[:spec].select { |verb, _| wanted.include?(verb.to_s) } if summary[:spec]
44
+ summary
45
+ end
46
+
47
+ def complete_summary(resource, omit_kind: false, with_source: false)
13
48
  result = {
14
49
  name: resource.name,
15
50
  metadata: {
@@ -18,13 +53,85 @@ module Archsight::MCP
18
53
  spec: resource.spec
19
54
  }
20
55
  result[:kind] = resource.class.to_s.split("::").last unless omit_kind
21
- result
56
+ with_source ? result.merge(source_info(resource)) : result
22
57
  end
23
58
 
24
- def brief_summary(resource, omit_kind: false)
59
+ def brief_summary(resource, omit_kind: false, with_source: false)
25
60
  result = { name: resource.name }
26
- result[:kind] = resource.class.to_s.split("::").last unless omit_kind
27
- result
61
+ result[:kind] = kind_of(resource) unless omit_kind
62
+ with_source ? result.merge(source_info(resource)) : result
63
+ end
64
+
65
+ # Where the resource is defined: `source` ("path:line", relative to the resources root), `generated`
66
+ # (true = written by an importer, do not edit by hand) and, when several documents were merged into the
67
+ # resource, `sources` (every contributing file, hand-written ones included).
68
+ def source_info(resource)
69
+ refs = resource.source_refs
70
+ info = { source: format_ref(refs.first), generated: resource.generated? }
71
+ info[:sources] = refs.map { |ref| format_ref(ref) } if refs.length > 1
72
+ info
73
+ end
74
+
75
+ # The direct relations of a resource, both ways, as [{verb:, direction: "out"|"in", kind:, name:}]
76
+ # ("out": the resource points at the target, "in": the other resource points at it)
77
+ def direct_relations(instance)
78
+ outgoing = instance.relations_grouped.flat_map do |verb, kinds|
79
+ kinds.flat_map do |kind, targets|
80
+ targets.map { |target| { verb: verb.to_s, direction: "out", kind: kind, name: target.name } }
81
+ end
82
+ end
83
+ incoming = instance.references.map do |ref|
84
+ { verb: ref[:verb].to_s, direction: "in", kind: kind_of(ref[:instance]), name: ref[:instance].name }
85
+ end
86
+ (outgoing + incoming).uniq
87
+ end
88
+
89
+ # Up to `limit` resources whose name is close to `name`, as [{kind:, name:}]: same name in other letter case
90
+ # first, then names containing it (or contained in it), then small edit distances. Resources of `kind` win ties.
91
+ def suggest(name, kind: nil, limit: 5)
92
+ wanted = name.to_s.downcase
93
+ return [] if wanted.empty?
94
+
95
+ threshold = [[wanted.length / 3, 2].max, 5].min
96
+ scored = db.instances.flat_map do |klass, by_name|
97
+ by_name.each_key.filter_map do |candidate|
98
+ rank = suggestion_rank(wanted, candidate.to_s.downcase, threshold)
99
+ [rank, klass.to_s.split("::").last == kind ? 0 : 1, candidate, klass.to_s.split("::").last] if rank
100
+ end
101
+ end
102
+ scored.sort.first(limit).map { |(_, _, candidate, candidate_kind)| { kind: candidate_kind, name: candidate } }
103
+ end
104
+
105
+ def suggestion_rank(wanted, candidate, threshold)
106
+ return [0, 0] if candidate == wanted
107
+ return [1, (candidate.length - wanted.length).abs] if candidate.include?(wanted) || wanted.include?(candidate)
108
+
109
+ distance = DidYouMean::Levenshtein.distance(wanted, candidate)
110
+ [2, distance] if distance <= threshold
111
+ end
112
+
113
+ # "Did you mean ..." text for suggestions, or nil
114
+ def did_you_mean(suggestions)
115
+ return nil if suggestions.empty?
116
+
117
+ "Did you mean: #{suggestions.map { |s| "#{s[:kind]}/#{s[:name]}" }.join(", ")}?"
118
+ end
119
+
120
+ # `kind`, `name`, `source` and `generated` of each direct relation target, as [{kind:, name:, source:, generated:}]
121
+ def related_sources(instance)
122
+ targets = instance.class.relations.flat_map do |verb, kind_name, _|
123
+ instance.relations(verb, kind_name)
124
+ end
125
+ targets.uniq.map { |t| { kind: kind_of(t), name: t.name }.merge(source_info(t)) }
126
+ end
127
+
128
+ def format_ref(ref)
129
+ return nil unless ref
130
+
131
+ root = db.respond_to?(:path) ? db.path.to_s : ""
132
+ path = ref.path.to_s
133
+ path = path.delete_prefix(File.join(File.expand_path(root), "")) unless root.empty?
134
+ "#{path}:#{ref.line_no}"
28
135
  end
29
136
 
30
137
  def annotations_summary(resource, omit_kind: false)
@@ -16,6 +16,10 @@ class Archsight::MCP::ExecuteAnalysisTool < FastMcp::Tool
16
16
  2. EXECUTE MODE (name provided): Runs the specified Analysis script in a sandboxed environment
17
17
  and returns the results as markdown. The output includes structured findings like tables,
18
18
  lists, warnings, and errors generated by the script.
19
+
20
+ TYPICAL FLOW: always list first (no name) to get the exact analysis names, then run one by name.
21
+ PITFALLS: analyses take no parameters (they always run over the whole model); tables and lists in the output
22
+ are truncated unless verbose=true; names are exact and case-sensitive (a wrong one returns suggestions).
19
23
  DESC
20
24
 
21
25
  arguments do
@@ -64,7 +68,7 @@ class Archsight::MCP::ExecuteAnalysisTool < FastMcp::Tool
64
68
 
65
69
  db = Archsight::MCP.db
66
70
  analysis = db.instance_by_kind("Analysis", name)
67
- return error_response("Analysis not found: #{name}") unless analysis
71
+ return not_found(name) unless analysis
68
72
 
69
73
  executor = Archsight::Analysis::Executor.new(db)
70
74
  result = executor.execute(analysis)
@@ -91,6 +95,12 @@ class Archsight::MCP::ExecuteAnalysisTool < FastMcp::Tool
91
95
  end
92
96
  end
93
97
 
98
+ def not_found(name)
99
+ suggestions = Archsight::MCP.suggest(name, kind: "Analysis").select { |s| s[:kind] == "Analysis" }
100
+ message = ["Analysis not found: #{name}", Archsight::MCP.did_you_mean(suggestions)].compact.join(". ")
101
+ JSON.pretty_generate(error: "Error", message: message, suggestions: suggestions)
102
+ end
103
+
94
104
  def error_response(message)
95
105
  JSON.pretty_generate(
96
106
  error: "Error",
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "base"
4
+
5
+ # What a query result can tell about the query itself: unknown annotation keys in its filters and the direct
6
+ # relations that made a resource match a relation condition.
7
+ module Archsight::MCP::QueryHints
8
+ class << self
9
+ # Warnings for annotation keys in the filters of a query that no resource of the queried kind (any kind without
10
+ # a kind prefix) has and no kind declares: such a filter silently matches nothing (or, negated, everything).
11
+ def unknown_key_warnings(parsed_query)
12
+ keys = annotation_keys(parsed_query.ast).uniq
13
+ return [] if keys.empty?
14
+
15
+ kind = parsed_query.kind_filter
16
+ klass = kind && Archsight::Resources[kind]
17
+ classes = klass ? [klass] : Archsight::MCP.db.instances.keys
18
+ keys.reject { |key| known_annotation_key?(key, classes) }.map do |key|
19
+ known = known_annotation_keys(classes)
20
+ close = known.sort_by { |candidate| [Archsight::MCP.suggestion_rank(key.downcase, candidate.downcase, 99)&.first || 9, candidate] }.first(8)
21
+ scope = klass ? "known keys for #{kind}" : "closest known keys over all kinds (prefix the query with a Kind: to narrow)"
22
+ "unknown annotation key \"#{key}\"; #{scope}: #{close.join(", ")}"
23
+ end
24
+ end
25
+
26
+ def annotation_keys(node, found = [])
27
+ case node
28
+ when Archsight::Query::AST::QueryNode then annotation_keys(node.expression, found)
29
+ when Archsight::Query::AST::BinaryOp
30
+ annotation_keys(node.left, found)
31
+ annotation_keys(node.right, found)
32
+ when Archsight::Query::AST::NotOp then annotation_keys(node.operand, found)
33
+ when Archsight::Query::AST::TextCondition
34
+ found.concat(node.keys.to_a.reject { |key| key.include?("*") })
35
+ when Archsight::Query::AST::AnnotationCondition, Archsight::Query::AST::AnnotationExistsCondition,
36
+ Archsight::Query::AST::AnnotationInCondition
37
+ found << node.path
38
+ end
39
+ found
40
+ end
41
+
42
+ def known_annotation_key?(key, classes)
43
+ classes.any? do |klass|
44
+ klass.annotation_matching(key) || Archsight::MCP.db.instances[klass]&.each_value&.any? { |inst| inst.annotations.key?(key) }
45
+ end
46
+ end
47
+
48
+ # Declared keys (patterns like scc/language/*/loc included) and the keys resources actually carry
49
+ def known_annotation_keys(classes)
50
+ classes.flat_map do |klass|
51
+ declared = klass.annotations.map(&:key)
52
+ used = (Archsight::MCP.db.instances[klass] || {}).each_value.flat_map { |inst| inst.annotations.keys }
53
+ declared + used
54
+ end.uniq
55
+ end
56
+
57
+ # The free-text conditions (`text =~ "x"`) of a query that are not negated, as AST nodes
58
+ def text_conditions(node, found = [])
59
+ case node
60
+ when Archsight::Query::AST::QueryNode then text_conditions(node.expression, found)
61
+ when Archsight::Query::AST::BinaryOp
62
+ text_conditions(node.left, found)
63
+ text_conditions(node.right, found)
64
+ when Archsight::Query::AST::TextCondition then found << node
65
+ end
66
+ found
67
+ end
68
+
69
+ # Where the text of the conditions was found in `instance`: [{key:, snippet:}], at most `limit` entries
70
+ def matched_text(instance, conditions, limit: 3)
71
+ hits = []
72
+ conditions.each do |condition|
73
+ Archsight::Query::TextSearch.each_match(instance, condition) do |key, value, match|
74
+ hits << { key: key, snippet: Archsight::Query::TextSearch.snippet(value, match) }
75
+ end
76
+ end
77
+ hits.uniq.first(limit)
78
+ end
79
+
80
+ # The direct relation conditions of a query (`-> Kind`, `<- "Name"`, with verb filters) that are not negated,
81
+ # as AST nodes. Transitive, `none` and sub-query targets are left out: they have no single relation to show.
82
+ def relation_conditions(node, found = [])
83
+ case node
84
+ when Archsight::Query::AST::QueryNode then relation_conditions(node.expression, found)
85
+ when Archsight::Query::AST::BinaryOp
86
+ relation_conditions(node.left, found)
87
+ relation_conditions(node.right, found)
88
+ when Archsight::Query::AST::OutgoingDirectRelation, Archsight::Query::AST::IncomingDirectRelation
89
+ found << node if [Archsight::Query::AST::KindTarget, Archsight::Query::AST::InstanceTarget].any? { |t| node.target.is_a?(t) }
90
+ end
91
+ found
92
+ end
93
+
94
+ # The direct relations of `instance` that satisfy the given relation conditions: why a relation query matched it
95
+ def matched_via(instance, conditions)
96
+ relations = Archsight::MCP.direct_relations(instance)
97
+ conditions.flat_map do |cond|
98
+ direction = cond.is_a?(Archsight::Query::AST::OutgoingDirectRelation) ? "out" : "in"
99
+ relations.select do |rel|
100
+ rel[:direction] == direction && relation_target_match?(cond.target, rel) && relation_verb_match?(cond, rel)
101
+ end
102
+ end.uniq
103
+ end
104
+
105
+ def relation_target_match?(target, rel)
106
+ if target.is_a?(Archsight::Query::AST::KindTarget)
107
+ rel[:kind] == target.kind_name
108
+ else
109
+ rel[:name] == target.instance_name
110
+ end
111
+ end
112
+
113
+ def relation_verb_match?(cond, rel)
114
+ return true if cond.verbs.nil?
115
+
116
+ cond.verbs.include?(rel[:verb]) != cond.exclude_verbs
117
+ end
118
+ end
119
+ end