archsight 0.5.7 → 0.6.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 (46) hide show
  1. checksums.yaml +4 -4
  2. data/docs/pages.md +2 -2
  3. data/docs/search.md +91 -17
  4. data/lib/archsight/database.rb +14 -0
  5. data/lib/archsight/diagram/style/representers.rb +3 -1
  6. data/lib/archsight/linter.rb +8 -5
  7. data/lib/archsight/mcp/query_hints.rb +0 -23
  8. data/lib/archsight/mcp/query_tool.rb +15 -12
  9. data/lib/archsight/query/ast.rb +46 -2
  10. data/lib/archsight/query/evaluator.rb +7 -1
  11. data/lib/archsight/query/full_text.rb +69 -0
  12. data/lib/archsight/query/parser.rb +43 -4
  13. data/lib/archsight/query/text_search.rb +2 -12
  14. data/lib/archsight/query.rb +25 -4
  15. data/lib/archsight/resources/config.rb +21 -0
  16. data/lib/archsight/text_index/expression.rb +73 -0
  17. data/lib/archsight/text_index/matcher.rb +107 -0
  18. data/lib/archsight/text_index/snippets.rb +107 -0
  19. data/lib/archsight/text_index/weights.rb +76 -0
  20. data/lib/archsight/text_index.rb +89 -0
  21. data/lib/archsight/version.rb +1 -1
  22. data/lib/archsight/web/api/json_helpers.rb +23 -4
  23. data/lib/archsight/web/api/openapi/spec.yaml +70 -0
  24. data/lib/archsight/web/api/routes.rb +7 -3
  25. data/lib/archsight/web/application.rb +14 -1
  26. data/lib/archsight/web/public/vue/{DocPage-BHffBQ3u.js → DocPage-qVqx-gJ9.js} +1 -1
  27. data/lib/archsight/web/public/vue/{EditorPage-BHZtvtnN.js → EditorPage-Bz21Jreq.js} +1 -1
  28. data/lib/archsight/web/public/vue/{ErrorPage-BQARAwF8.js → ErrorPage-CKNxpjzn.js} +1 -1
  29. data/lib/archsight/web/public/vue/{GraphView-D84CH00D.js → GraphView-6EzYwP8T.js} +1 -1
  30. data/lib/archsight/web/public/vue/{HomePage-BJpTPWFz.js → HomePage-tCk9Pmh5.js} +2 -2
  31. data/lib/archsight/web/public/vue/{InstanceRouter-C1Da3nWo.js → InstanceRouter-BQx8UnCA.js} +1 -1
  32. data/lib/archsight/web/public/vue/{KindList-DNRUVuEJ.js → KindList-Ky5uk5xe.js} +1 -1
  33. data/lib/archsight/web/public/vue/{PageView-DzKj212I.js → PageView-AdolhVA0.js} +1 -1
  34. data/lib/archsight/web/public/vue/{QueryError-CTVAL1Tm.js → QueryError-Qt-3lwb7.js} +1 -1
  35. data/lib/archsight/web/public/vue/ResourceList-LYEUNwQn.css +1 -0
  36. data/lib/archsight/web/public/vue/ResourceList-zb7VO6Bk.js +2 -0
  37. data/lib/archsight/web/public/vue/SearchResults-8SgERqBf.js +1 -0
  38. data/lib/archsight/web/public/vue/SearchResults-C8Nqi4yk.css +1 -0
  39. data/lib/archsight/web/public/vue/{WikiPage-DSEL2gmd.js → WikiPage-D0x1B2aR.js} +1 -1
  40. data/lib/archsight/web/public/vue/{index-JZkWwfYg.js → index-DlL2S_4s.js} +2 -2
  41. data/lib/archsight/web/public/vue.html +1 -1
  42. metadata +36 -16
  43. data/lib/archsight/web/public/vue/ResourceList-CRt_FpfS.js +0 -2
  44. data/lib/archsight/web/public/vue/ResourceList-D75O87zG.css +0 -1
  45. data/lib/archsight/web/public/vue/SearchResults-BMwBz4BB.js +0 -1
  46. data/lib/archsight/web/public/vue/SearchResults-BV6UHriJ.css +0 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2538e617e5c3ea62514b655e2ee12325ec43c534e68ee86e3c92126e69e33e93
4
- data.tar.gz: 305cd2f0695a7f08119147853943adfabbacde94789614dc66aab447ca39a702
3
+ metadata.gz: 93f18d96d9048a6dc043f80bec20899295c126408334d7a3881a06052107bda9
4
+ data.tar.gz: c924aa94ead53a8a01b1a16a5e93b921ad3e16f80592f271a4d2d3827a916b73
5
5
  SHA512:
6
- metadata.gz: bc8c2c474235d33628fdb819ffc3f66dc91171b3bdabd06df91a07bb87336b3136da817aab5499c3920c65977c739293f807bdf2b0c4511ff7f31268bee48b80
7
- data.tar.gz: 329910d151a0534977344dbec32f4d36532fbe56d001bdebd68c5552e187abc6b3e6f2a6afeeb9e9ad8316ce8b5e687da144dc2c78becb9426ed1176936bf6dd
6
+ metadata.gz: fbb7e753d657c2cb71dcc232ce529a1e05e1d69e81db5da0cda573401dc7595f01e4f313f5c8397e2c33e6fcf0027ddab3b70992b06a83814a64d1fdb66c017f
7
+ data.tar.gz: b573c148b33b354ea1c5f6e58a0d4dc6c6d984bc17f73a8127560bb3a0ee0dceb07b48d5b71f72eaa0a27f5553319b615bfb827eee1f11f0a2b73e665a9cfb6f
data/docs/pages.md CHANGED
@@ -388,8 +388,8 @@ tools reach them. It is read-only, pages cannot be created or edited through MCP
388
388
  1. Ask for totals or names first, this is cheap: `query` with `Page:` and `output: "count"` or `"brief"`.
389
389
  `brief` returns the page names (file names) only, not titles, tags or status.
390
390
  2. Narrow down with the [query language](/doc/search#searching-wiki-pages), for example
391
- `Page: page/tags == "howto"`, or search the text with `Page: page/content =~ "asd"`. A bare word matches the
392
- name only, so full-text search always goes through `page/content`.
391
+ `Page: page/tags == "howto"`, or search the text with `Page: text: "asd"` (words, ranked by relevance). A bare
392
+ word matches the name only, so full-text search goes through `text:`.
393
393
  3. Read one page with `analyze_resource` (`kind: "Page"`, `name: "<page name>"`): the result has the
394
394
  metadata (`page/title`, `page/tags`, `page/status`, ...) and the raw markdown in `page/content`.
395
395
 
data/docs/search.md CHANGED
@@ -6,18 +6,24 @@ The search box supports a powerful query language for filtering architecture res
6
6
 
7
7
  | Query | Description |
8
8
  |-------|-------------|
9
- | `kubernetes` | Name contains "kubernetes" (case-insensitive) |
9
+ | `kubernetes` | Name contains "kubernetes" (in the search box: also the text, ranked) |
10
10
  | `TechnologyArtifact:` | All resources of a specific kind |
11
11
  | `activity/status == "active"` | Annotation equals value |
12
12
  | `scc/loc == 15000` | Numeric equality |
13
13
  | `activity/status?` | Annotation exists (is set) |
14
14
  | `! activity/status?` | Annotation doesn't exist |
15
15
  | `-> ApplicationInterface` | Has relation to a kind |
16
- | `text =~ "failover"` | Any string annotation contains the text |
16
+ | `text: "failover standby"` | Full-text search: the text contains both words, best matches first |
17
17
 
18
18
  ## Name Search
19
19
 
20
- Type any word to search by name (case-insensitive regex match):
20
+ In the **search box**, words find resources by name and by text: `kubernetes failover` lists everything whose name
21
+ contains both words or whose text (descriptions, titles, page content, ...) contains both, also as the beginning of
22
+ a longer word (`kube` finds kubernetes). The best matches come first, see [Ranking](#ranking). Mixed with a
23
+ condition the words are one part of the query: `kubernetes failover & activity/status == "active"`.
24
+
25
+ In saved views, embedded `view` blocks, sub-queries and the MCP `query` tool a bare word is a name search only
26
+ (case-insensitive regex match), so their results do not change:
21
27
 
22
28
  kubernetes # name =~ "kubernetes"
23
29
  name == "MyService" # exact match
@@ -34,21 +40,67 @@ without spaces they are one word, found by name or alias like any other bare wor
34
40
 
35
41
  ## Text Search
36
42
 
37
- `text` searches the content of resources: every string annotation (descriptions, titles, `link/*`, page content, ...)
38
- is checked for the pattern, case-insensitively, like `name =~`:
43
+ `text` searches the content of resources: every string annotation (descriptions, titles, `link/*`, page content, ...).
44
+ A quoted string is a **full-text search** in an index of all texts:
45
+
46
+ text: "failover" # the word failover (also failovers: word forms are found)
47
+ text =~ "failover" # the same
48
+ text: "failover standby" # both words, anywhere in the resource
49
+ text: "failover OR standby" # one of them
50
+ text: "failover NOT region" # failover, but not region
51
+ text: "\"active standby\"" # the exact phrase (quotes inside the string)
52
+ text: "kube*" # words that start with kube
53
+ text: "PROJ-1234" # words with - : / . are searched as written, next to each other
54
+ ApplicationService: text: "failover" & -> ApplicationComponent # combined with anything else
55
+
56
+ Words are case-insensitive and accents are ignored. `AND`, `OR` and `NOT` are operators only in capitals; parentheses
57
+ group. The hits of a full-text search come ranked by relevance, see [Ranking](#ranking).
39
58
 
40
- text =~ "failover" # any annotation mentions failover
41
- text: "failover" # the same, short
42
- text =~ /fail(over|back)/i # regex literal with flags
59
+ A **regex literal** or a **list of keys** scans the annotations with a case-insensitive regular expression instead,
60
+ for parts of words and patterns:
61
+
62
+ text =~ /fail(over|back)/i # regex literal with flags
63
+ text =~ /ailove/ # part of a word (a full-text search finds whole words)
43
64
  text(architecture/description) =~ "standby" # only this annotation
44
65
  text(link/*, page/content) =~ "PROJ-1234" # several keys, `*` is any run of characters
45
- ApplicationService: text =~ "failover" & -> ApplicationComponent # combined with anything else
46
66
 
47
67
  In a quoted string a backslash only escapes the next character (`"\d"` is `d`); write patterns with escapes as `/regex/`.
48
68
 
49
- A resource matches when one of the checked annotations matches. The MCP `query` tool shows the annotation and a short
50
- snippet around the match for each hit (`matched_text`). The bare word `text` is still a name search; text in YAML
51
- comments is not searched.
69
+ A resource matches the scan when one of the checked annotations matches. The MCP `query` tool shows the annotation
70
+ and a short snippet around the match for each hit (`matched_text`), for full-text searches too. The bare word `text`
71
+ is still a name search; text in YAML comments is not searched.
72
+
73
+ ### Ranking
74
+
75
+ A query that searches text (the words of the search box, `text: "..."`) lists its hits by relevance: how often and
76
+ where the words occur (a word in the name or title counts ten times a word in the body, rare words more than common
77
+ ones), times the weight of the kind. Pages count most, then application services and components, interfaces, the
78
+ other layers and technology; settings such as Config and PageMenu least:
79
+
80
+ | Weight | Kinds |
81
+ |--------|-------|
82
+ | 3 | `Page` |
83
+ | 2 | `ApplicationService`, `ApplicationComponent` |
84
+ | 1.5 | `ApplicationInterface` and the rest of the application layer |
85
+ | 1.2 | business, strategy and motivation layer |
86
+ | 1 | technology and implementation layer |
87
+ | 0.5 | other kinds (Config, PageMenu, Grouping, ...) |
88
+
89
+ A [Config](/kinds/Config) of type `search` named `default` changes them, per layer or per kind (numbers from 0 to
90
+ 100, the kind before the layer):
91
+
92
+ ```yaml
93
+ apiVersion: architecture/v1alpha1
94
+ kind: Config
95
+ metadata:
96
+ name: default
97
+ annotations:
98
+ config/type: search
99
+ search/weight-technology: "0.8"
100
+ search/weight-TechnologyService: "1.5"
101
+ ```
102
+
103
+ Queries without a text search list their hits by name.
52
104
 
53
105
  ## Kind Filter
54
106
 
@@ -242,12 +294,12 @@ to search pages only.
242
294
  | `page/author`, `page/owner` | `Name <email>` |
243
295
  | `page/content` | The markdown body, without the frontmatter |
244
296
 
245
- A bare word (`kubernetes`) only matches the **name**. To search the text of pages, match `page/content`:
297
+ Words typed in the Pages tab search the name, title and text of pages (`Page: handbook`), ranked. In a query, search
298
+ the text of pages with `text:` or match `page/content`:
246
299
 
247
- Page: page/content =~ "asd" # pages that mention "asd"
248
- Page: name =~ "query" | page/title =~ "query" | page/content =~ "query"
249
- # name, title or text (what the Pages tab does)
250
- Page: page/content =~ "asd" & page/status == "approved" # text search plus a filter
300
+ Page: text: "asd" # pages that mention "asd", best first
301
+ Page: text: "asd" & page/status == "approved" # text search plus a filter
302
+ Page: page/content =~ "asd" # a regex on the markdown
251
303
  Page: page/tags == "howto" # by tag
252
304
  Page: page/content =~ "```asd" # pages that contain a diagram
253
305
 
@@ -326,3 +378,25 @@ hits of the query) and, for each hit, `highlights`:
326
378
 
327
379
  Add `kind=TechnologyArtifact` to narrow the hits to one kind (`total` and paging follow, `by_kind` still counts
328
380
  all hits).
381
+
382
+ ### Hits of a text search
383
+
384
+ When the query searches text (words in the search box, `text: "..."`, `text =~ /.../`), every hit shows where the
385
+ words occur: its title with the words marked, and up to two **excerpts** from the fields with the most of the
386
+ searched words (a description before a tag list), cut to the part that holds most of them, markdown taken off.
387
+ Word forms are marked too (a search for `failovers` marks *Failover*). The hits come best match first; **Name**
388
+ next to the result count lists them alphabetically instead.
389
+
390
+ In the API (`fulltext=true` for the search box words, `sort=name` for the name order) such hits carry:
391
+
392
+ "title": "Diagrams in Pages",
393
+ "title_marks": [[0, 8]],
394
+ "relevance": 0.674,
395
+ "matches": [
396
+ { "key": "page/content", "title": "Content",
397
+ "text": "…They render to inline SVG, need no external tool…", "marks": [[5, 11]] }
398
+ ]
399
+
400
+ `marks` are `[from, to)` ranges of characters (code points) in `text`; `relevance` is relative to the best hit
401
+ (1.0), only when the hits are ranked. The response says `"sort": "relevance"` or `"name"`, and `"ranked": true`
402
+ when the query searches text. The MCP `query` tool shows the same excerpts as `matched_text`.
@@ -6,6 +6,7 @@ require_relative "resources"
6
6
  require_relative "page_loader"
7
7
  require_relative "query"
8
8
  require_relative "references"
9
+ require_relative "text_index"
9
10
 
10
11
  module Archsight
11
12
  # LineReference combines a path and line reference
@@ -63,11 +64,14 @@ module Archsight
63
64
  @only_kinds = only_kinds
64
65
  @instances = {}
65
66
  @deprecations = []
67
+ @text_index_mutex = Mutex.new
66
68
  end
67
69
 
68
70
  def reload!
69
71
  @instances = {}
70
72
  @deprecations = []
73
+ @text_index = nil
74
+ @search_weights = nil
71
75
 
72
76
  # load all resources
73
77
  Dir.glob(File.join(@path, "**/*.{yaml,md}")).each do |path|
@@ -127,6 +131,16 @@ module Archsight
127
131
  .reject { |_, values| values.empty? }
128
132
  end
129
133
 
134
+ # The full-text index of the resources (see TextIndex), built on first use and dropped by reload!
135
+ def text_index
136
+ @text_index_mutex.synchronize { @text_index ||= Archsight::TextIndex.new(self) }
137
+ end
138
+
139
+ # How much a hit of each kind counts in the ranking of a text search (see TextIndex::Weights)
140
+ def search_weights
141
+ @search_weights ||= Archsight::TextIndex::Weights.for(self)
142
+ end
143
+
130
144
  # Execute a query string and return matching instances
131
145
  def query(query_string)
132
146
  q = Archsight::Query.parse(query_string)
@@ -172,7 +172,9 @@ module Archsight
172
172
  # nowhere to put text "inside" it the way a rect or ellipse does.
173
173
  class Actor < Base
174
174
  def figure_geometry(box, theme)
175
- [box.x, box.top + (theme.actor_figure_height / 2.0), box.width, theme.actor_figure_height]
175
+ # Only the label grows with the text; the figure keeps its natural proportions, centred in the box.
176
+ figure_width = [box.width, theme.actor_figure_height * 0.9].min
177
+ [box.x, box.top + (theme.actor_figure_height / 2.0), figure_width, theme.actor_figure_height]
176
178
  end
177
179
 
178
180
  def label_y(box, theme) = box.top + theme.actor_figure_height + (theme.actor_label_height / 2.0)
@@ -332,7 +332,7 @@ module Archsight
332
332
  next
333
333
  end
334
334
 
335
- validate_summary_lens_key(instance, key)
335
+ validate_layer_or_kind_key(instance, key)
336
336
 
337
337
  # Content checks don't depend on enum/type constraints
338
338
  validate_markdown(instance, key, value) if annotation.markdown?
@@ -348,10 +348,13 @@ module Archsight
348
348
  end
349
349
  end
350
350
 
351
- # `summary/lens-<layer or Kind>`: a suffix that names neither would be ignored silently
352
- def validate_summary_lens_key(instance, key)
353
- suffix = key[%r{\Asummary/lens-(.+)\z}, 1]
354
- return unless suffix && instance.klass == "Config"
351
+ # `summary/lens-<layer or Kind>` / `search/weight-<layer or Kind>`: a suffix that names neither would be ignored
352
+ # silently
353
+ def validate_layer_or_kind_key(instance, key)
354
+ return unless instance.klass == "Config"
355
+
356
+ suffix = key[%r{\A(?:summary/lens|search/weight)-(.+)\z}, 1]
357
+ return unless suffix
355
358
 
356
359
  problem = Archsight::Summary::Lens.key_error(suffix)
357
360
  @errors << "#{instance.path_ref}: Annotation '#{key}' #{problem}" if problem
@@ -54,29 +54,6 @@ module Archsight::MCP::QueryHints
54
54
  end.uniq
55
55
  end
56
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
57
  # The direct relation conditions of a query (`-> Kind`, `<- "Name"`, with verb filters) that are not negated,
81
58
  # as AST nodes. Transitive, `none` and sub-query targets are left out: they have no single relation to show.
82
59
  def relation_conditions(node, found = [])
@@ -18,9 +18,11 @@ class Archsight::MCP::QueryTool < FastMcp::Tool
18
18
  • Annotation filters: 'activity/status == "active"', 'scc/language/Go/loc > 5000'
19
19
  Operators: == (equals), != (not equals), =~ (regex match), >, <, >=, <=
20
20
 
21
- • Free-text search over the string annotations (descriptions, links, titles, ...):
22
- text =~ "failover" (also text: "failover"; case-insensitive regex, like name =~)
23
- text(architecture/description) =~ "x", text(link/*, page/content) =~ "x" restrict the keys (* = any run)
21
+ • Full-text search over the string annotations (descriptions, links, titles, page content, ...):
22
+ text: "failover standby" (also text =~ "..."): words (all must occur, word forms match: failovers = failover),
23
+ OR, NOT, "exact phrase", prefix* ; hits come ranked by relevance (pages and application kinds first).
24
+ text =~ /fail(over|back)/i (regex literal) and text(architecture/description) =~ "x",
25
+ text(link/*, page/content) =~ "x" (restricted keys, * = any run) are case-insensitive regex scans instead.
24
26
  Each hit shows matched_text: the annotation key and a snippet around the match.
25
27
 
26
28
  • Relation queries:
@@ -93,7 +95,7 @@ class Archsight::MCP::QueryTool < FastMcp::Tool
93
95
 
94
96
  begin
95
97
  parsed_query = Archsight::Query.parse(query)
96
- results = parsed_query.filter(db)
98
+ results = parsed_query.ranked(db)
97
99
  total = results.length
98
100
 
99
101
  # Complete output omits the kind when filtering by a specific kind (it's redundant); brief always names
@@ -101,7 +103,7 @@ class Archsight::MCP::QueryTool < FastMcp::Tool
101
103
  omit_kind = !parsed_query.kind_filter.nil?
102
104
 
103
105
  conditions = Archsight::MCP::QueryHints.relation_conditions(parsed_query.ast)
104
- text_conditions = Archsight::MCP::QueryHints.text_conditions(parsed_query.ast)
106
+ matcher = Archsight::TextIndex::Matcher.for(parsed_query, db)
105
107
 
106
108
  # Count-only mode: return totals grouped by kind
107
109
  if output == "count"
@@ -115,7 +117,8 @@ class Archsight::MCP::QueryTool < FastMcp::Tool
115
117
  }
116
118
  else
117
119
  # Complete or brief mode: return paginated resources
118
- paginated = results.sort_by(&:name).drop(offset).take(limit)
120
+ ordered = parsed_query.ranked? ? results : results.sort_by(&:name)
121
+ paginated = ordered.drop(offset).take(limit)
119
122
  resources = case output
120
123
  when "brief"
121
124
  paginated.map { |r| Archsight::MCP.brief_summary(r, with_source: true) }
@@ -127,7 +130,7 @@ class Archsight::MCP::QueryTool < FastMcp::Tool
127
130
  end
128
131
 
129
132
  add_matched_via(resources, paginated, conditions)
130
- add_matched_text(resources, paginated, text_conditions)
133
+ add_matched_text(resources, paginated, matcher)
131
134
 
132
135
  result = {
133
136
  query: query,
@@ -154,13 +157,13 @@ class Archsight::MCP::QueryTool < FastMcp::Tool
154
157
 
155
158
  private
156
159
 
157
- # For text queries (`text =~ "x"`): the annotation and the snippet around the match, per hit
158
- def add_matched_text(summaries, resources, conditions)
159
- return if conditions.empty?
160
+ # For text queries (`text: "x"`, `text =~ /x/`): the annotations where the text occurs and an excerpt around it
161
+ def add_matched_text(summaries, resources, matcher)
162
+ return if matcher.empty?
160
163
 
161
164
  summaries.zip(resources).each do |summary, resource|
162
- found = Archsight::MCP::QueryHints.matched_text(resource, conditions)
163
- summary[:matched_text] = found unless found.empty?
165
+ found = Archsight::TextIndex::Snippets.for(resource, matcher, limit: 3, width: 140)
166
+ summary[:matched_text] = found.map { |hit| { key: hit[:key], snippet: hit[:text] } } unless found.empty?
164
167
  end
165
168
  end
166
169
 
@@ -93,8 +93,10 @@ module Archsight::Query::AST
93
93
  end
94
94
  end
95
95
 
96
- # Free-text condition: text =~ "pattern", text: "pattern", text(key, key/*) =~ "pattern". Matches when a string
97
- # annotation (all of them, or the ones named by `keys`, which may end in a `*` wildcard) contains the pattern.
96
+ # Free-text condition: text =~ "words", text: "words", text =~ /regex/, text(key, key/*) =~ "pattern". With a
97
+ # string and no keys it is a full-text search (Archsight::TextIndex: words, phrases, prefix*, ranked); a /regex/
98
+ # literal or a key list scans the string annotations (all, or the ones named by `keys`, which may end in a `*`
99
+ # wildcard) for the pattern.
98
100
  class TextCondition < Node
99
101
  attr_reader :keys, :operator, :value
100
102
 
@@ -104,6 +106,21 @@ module Archsight::Query::AST
104
106
  @value = value # StringValue or RegexValue
105
107
  end
106
108
 
109
+ # Searched in the full-text index (a string over every annotation), not by regular expression
110
+ def fulltext?
111
+ keys.nil? && value.is_a?(StringValue)
112
+ end
113
+
114
+ # The FTS5 match expression of a full-text condition
115
+ def fulltext_expression
116
+ @fulltext_expression ||= Archsight::TextIndex::Expression.translate(value.value)
117
+ end
118
+
119
+ # The words the full-text condition looks for (to show where they occur)
120
+ def terms
121
+ Archsight::TextIndex::Expression.terms(value.value)
122
+ end
123
+
107
124
  # The compiled pattern, built once per query (every resource is checked against it)
108
125
  def regexp
109
126
  @regexp ||= Archsight::Query::AST.regexp_for(value)
@@ -121,6 +138,33 @@ module Archsight::Query::AST
121
138
  end
122
139
  end
123
140
 
141
+ # Search box words (`kubernetes failover`, parsed with bare_words: :search): a resource matches when its name or an
142
+ # alias contains every word (as the bare word name search) or its text contains every word, also as prefix
143
+ class SearchTerms < Node
144
+ attr_reader :words
145
+
146
+ def initialize(words)
147
+ @words = words # Array of String
148
+ end
149
+
150
+ # The words as case-insensitive patterns for the name
151
+ def name_patterns
152
+ @name_patterns ||= words.map { |word| Regexp.new(Regexp.escape(word), Regexp::IGNORECASE) }
153
+ end
154
+
155
+ def fulltext_expression
156
+ @fulltext_expression ||= Archsight::TextIndex::Expression.translate(words.join(" "), prefix: true)
157
+ end
158
+
159
+ def terms
160
+ words
161
+ end
162
+
163
+ def accept(visitor)
164
+ visitor.visit_search_terms(self)
165
+ end
166
+ end
167
+
124
168
  # Kind condition: kind == "SomeKind" or kind =~ "pattern"
125
169
  class KindCondition < Node
126
170
  attr_reader :operator, :value
@@ -2,11 +2,15 @@
2
2
 
3
3
  require_relative "errors"
4
4
  require_relative "ast"
5
+ require_relative "full_text"
5
6
 
6
7
  class Archsight::Query::Evaluator
8
+ include Archsight::Query::FullText
9
+
7
10
  def initialize(database)
8
11
  @database = database
9
12
  @subquery_cache = {} # Cache for pre-computed subquery results
13
+ @fulltext_cache = {}.compare_by_identity # Full-text hits per condition node: {instance => score}
10
14
  end
11
15
 
12
16
  # Main entry point: evaluate query against instance, returns boolean
@@ -144,7 +148,9 @@ class Archsight::Query::Evaluator
144
148
  when Archsight::Query::AST::AnnotationInCondition
145
149
  evaluate_annotation_in_condition(node, instance)
146
150
  when Archsight::Query::AST::TextCondition
147
- Archsight::Query::TextSearch.matches?(instance, node)
151
+ evaluate_text_condition(node, instance)
152
+ when Archsight::Query::AST::SearchTerms
153
+ evaluate_search_terms(node, instance)
148
154
  when Archsight::Query::AST::KindCondition
149
155
  evaluate_kind_condition(node, instance)
150
156
  when Archsight::Query::AST::KindInCondition
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Full-text conditions (`text: "words"`, search box words) of the Evaluator: answered by the TextIndex once per
4
+ # condition, and the relevance order of results (full-text score times the weight of the kind).
5
+ module Archsight::Query::FullText
6
+ # What a name hit of search box words adds to the relevance of a resource (a word in the name already scores high
7
+ # in the full-text index; this ranks names that contain a word only as part of a longer word)
8
+ NAME_BONUS = 5.0
9
+
10
+ # The full-text nodes that decide the order of results: not negated, not inside a sub-query
11
+ def self.ranking_nodes(node, found = [])
12
+ case node
13
+ when Archsight::Query::AST::QueryNode then ranking_nodes(node.expression, found)
14
+ when Archsight::Query::AST::BinaryOp
15
+ ranking_nodes(node.left, found)
16
+ ranking_nodes(node.right, found)
17
+ when Archsight::Query::AST::SearchTerms then found << node
18
+ when Archsight::Query::AST::TextCondition then found << node if node.fulltext?
19
+ end
20
+ found
21
+ end
22
+
23
+ # The results ordered by relevance when the query searches text (full-text conditions and search box words that are
24
+ # not negated): weight of the kind (TextIndex::Weights) times the full-text score, best first, then by name.
25
+ # Without such conditions the results are returned as they are.
26
+ def rank(query_node, results)
27
+ scored(query_node, results)&.map(&:first) || results
28
+ end
29
+
30
+ # [[instance, score]] best first, as #rank orders them; nil without text search conditions
31
+ def scored(query_node, results)
32
+ nodes = Archsight::Query::FullText.ranking_nodes(query_node.expression)
33
+ return nil if nodes.empty?
34
+
35
+ weights = @database.respond_to?(:search_weights) ? @database.search_weights : Archsight::TextIndex::Weights.for(@database)
36
+ results.map { |instance| [instance, weights[instance.class] * relevance(nodes, instance)] }
37
+ .sort_by { |instance, score| [-score, instance.name.to_s] }
38
+ end
39
+
40
+ private
41
+
42
+ def relevance(nodes, instance)
43
+ nodes.sum do |node|
44
+ bonus = node.is_a?(Archsight::Query::AST::SearchTerms) && name_matches_words?(node, instance) ? NAME_BONUS : 0.0
45
+ fulltext_hits(node)[instance].to_f + bonus
46
+ end
47
+ end
48
+
49
+ # {instance => score} of a full-text node, searched once per evaluator
50
+ def fulltext_hits(node)
51
+ @fulltext_cache[node] ||= Archsight::TextIndex.for(@database).search(node.fulltext_expression)
52
+ end
53
+
54
+ def evaluate_text_condition(node, instance)
55
+ return Archsight::Query::TextSearch.matches?(instance, node) unless node.fulltext?
56
+
57
+ fulltext_hits(node).key?(instance)
58
+ end
59
+
60
+ # Search box words: the name or an alias contains every word, or the text does
61
+ def evaluate_search_terms(node, instance)
62
+ name_matches_words?(node, instance) || fulltext_hits(node).key?(instance)
63
+ end
64
+
65
+ def name_matches_words?(node, instance)
66
+ names = names_of(instance)
67
+ node.name_patterns.all? { |pattern| names.any? { |name| pattern.match?(name) } }
68
+ end
69
+ end
@@ -8,11 +8,17 @@ class Archsight::Query::Parser
8
8
  # Characters a resource name is made of, as the lexer reads an identifier
9
9
  NAME_CHAR = %r{[a-zA-Z0-9_\-/.]}
10
10
 
11
+ # Tokens after which an identifier is an annotation path, not a bare word
12
+ CONDITION_TOKENS = %i[EQ NEQ MATCH GT LT GTE LTE IN QUESTION].freeze
13
+
11
14
  # @param source [String, nil] the query text; with it, names that contain colons (`Archsight:CLI`, `ITGS:A001`)
12
15
  # are read as one name instead of a kind prefix and a condition
13
- def initialize(tokens, source: nil)
16
+ # @param bare_words [Symbol] :name (a bare word is a name search) or :search (a run of bare words is a
17
+ # SearchTerms node: name or full text, what the search box does)
18
+ def initialize(tokens, source: nil, bare_words: :name)
14
19
  @tokens = tokens
15
20
  @source = source
21
+ @bare_words = bare_words
16
22
  @position = 0
17
23
  end
18
24
 
@@ -399,12 +405,37 @@ class Archsight::Query::Parser
399
405
  # Existence check: path?
400
406
  advance # consume ?
401
407
  Archsight::Query::AST::AnnotationExistsCondition.new(path)
408
+ elsif @bare_words == :search
409
+ parse_search_terms(glue_name(path))
402
410
  else
403
411
  # Bare identifier - treat as name =~ "identifier"
404
412
  Archsight::Query::AST::NameCondition.new("=~", Archsight::Query::AST::StringValue.new(glue_name(path)))
405
413
  end
406
414
  end
407
415
 
416
+ # `kubernetes failover`: the bare words that follow each other, up to the first that starts a condition
417
+ def parse_search_terms(first)
418
+ words = [first]
419
+ while bare_word_ahead?
420
+ word = current_token.value
421
+ advance
422
+ words << glue_name(word)
423
+ end
424
+ Archsight::Query::AST::SearchTerms.new(words)
425
+ end
426
+
427
+ def bare_word_ahead?
428
+ return false unless current_token.type == :IDENTIFIER
429
+
430
+ following = peek_token&.type
431
+ return false if CONDITION_TOKENS.include?(following)
432
+ return false if current_token.value == "text" && %i[MATCH LPAREN COLON].include?(following)
433
+ # `Kind: ...` in the middle is no word; `ITGS:A001` (colon touching both words) is one
434
+ return false if following == :COLON && !@source.to_s[peek_token.position + 1].to_s.match?(NAME_CHAR)
435
+
436
+ true
437
+ end
438
+
408
439
  # `text` starts a free-text condition when `=~`, `:` plus a value, or a key list in parentheses follows;
409
440
  # otherwise it is the bare word "text" (a name search)
410
441
  def text_condition_ahead?
@@ -430,8 +461,10 @@ class Archsight::Query::Parser
430
461
 
431
462
  value_token = current_token
432
463
  value = parse_value
433
- check_value("=~", value, value_token)
434
- Archsight::Query::AST::TextCondition.new(keys, "=~", value)
464
+ condition = Archsight::Query::AST::TextCondition.new(keys, "=~", value)
465
+ # a full-text search is checked as such (`text: "C++"` is no regex); the others compile their pattern now
466
+ condition.fulltext? ? check_fulltext(condition, value_token) : check_value("=~", value, value_token)
467
+ condition
435
468
  end
436
469
 
437
470
  def parse_text_keys
@@ -495,7 +528,7 @@ class Archsight::Query::Parser
495
528
  return false unless stop
496
529
 
497
530
  following = @tokens.find { |token| token.position >= stop }
498
- !(following && %i[EQ NEQ MATCH GT LT GTE LTE IN QUESTION].include?(following.type))
531
+ !(following && CONDITION_TOKENS.include?(following.type))
499
532
  end
500
533
 
501
534
  # Where `a:b:c` ends, starting at its first colon; nil when that colon does not touch a name character on both sides
@@ -612,6 +645,12 @@ class Archsight::Query::Parser
612
645
  raise Archsight::Query::InvalidRegexError.new(e.message, position: token.position, source: nil)
613
646
  end
614
647
 
648
+ def check_fulltext(condition, token)
649
+ condition.fulltext_expression
650
+ rescue Archsight::Query::QueryError => e
651
+ raise Archsight::Query::ParseError.new(e.message, position: token.position, source: nil)
652
+ end
653
+
615
654
  # One value of an `in (...)` list
616
655
  def parse_in_value
617
656
  token = current_token
@@ -2,11 +2,9 @@
2
2
 
3
3
  require_relative "ast"
4
4
 
5
- # Free-text search over the string annotations of a resource (`text =~ "x"`), shared by the evaluator and by the
6
- # MCP query tool, which shows where the text was found.
5
+ # Regex search over the string annotations of a resource (`text =~ /x/`, `text(keys) =~ "x"`); where a text
6
+ # condition matched is shown by Archsight::TextIndex::Snippets.
7
7
  module Archsight::Query::TextSearch
8
- SNIPPET_WIDTH = 60
9
-
10
8
  class << self
11
9
  # Yields [key, value, MatchData] for every string annotation of `instance` the condition matches
12
10
  def each_match(instance, condition, &block)
@@ -26,13 +24,5 @@ module Archsight::Query::TextSearch
26
24
  def matches?(instance, condition)
27
25
  !each_match(instance, condition).first.nil?
28
26
  end
29
-
30
- # A short single-line excerpt of `value` around the match
31
- def snippet(value, match, width: SNIPPET_WIDTH)
32
- from = [match.begin(0) - width, 0].max
33
- to = [match.end(0) + width, value.length].min
34
- text = value[from...to].gsub(/\s+/, " ").strip
35
- "#{"…" if from.positive?}#{text}#{"…" if to < value.length}"
36
- end
37
27
  end
38
28
  end