intent-record 1.1.0 → 2.0.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.
@@ -0,0 +1,76 @@
1
+ require_relative "../blame/spans"
2
+ require_relative "../blame/porcelain"
3
+ require_relative "../asset_version_normalizer"
4
+ require_relative "../formatter"
5
+ require_relative "../input_validator"
6
+ require_relative "../models/asset_version"
7
+
8
+ module IntentRecord
9
+ module Commands
10
+ # Answers "why is this line here" for a range of lines.
11
+ #
12
+ # Blame output goes in on stdin rather than the tool shelling out to git, so
13
+ # the same command answers for Perforce or Mercurial and the store keeps
14
+ # knowing nothing about which repository a commit belongs to.
15
+ class Blame
16
+ DEFAULT_VCS = "git".freeze
17
+
18
+ # Git's all-zero object id, which blame gives a line that is in the working
19
+ # copy and not in the history. It is not a commit, so a reader is told the
20
+ # line is not committed rather than that nothing was recorded against it,
21
+ # and the store is not asked about it at all: the id is a valid shape, so
22
+ # a record can sit under it, and one did, but a line with no history cannot
23
+ # have had anything recorded against it.
24
+ # Forty zeros, or sixty-four in a repository using the sha256 object format.
25
+ UNCOMMITTED = /\A(?:0{40}|0{64})\z/
26
+
27
+ def call(input)
28
+ InputValidator.known_keys!(input, %w[vcs lines])
29
+ vcs = AssetVersionNormalizer.vcs_name(input["vcs"] || DEFAULT_VCS)
30
+ spans = IntentRecord::Blame::Spans.new(input["lines"]).call
31
+ { "spans" => answers(spans, vcs) }
32
+ end
33
+
34
+ private
35
+
36
+ def answers(spans, vcs)
37
+ known = versions(spans.reject { |span| uncommitted?(span, vcs) }, vcs)
38
+ spans.map { |span| answer(span, vcs, known[AssetVersionNormalizer.lookup_id(vcs, span.external_id)]) }
39
+ end
40
+
41
+ # Every span is answered, including one whose change the store has never
42
+ # heard of. Leaving it out would read as "this line has no history", which
43
+ # is the opposite of what an empty list of intents says.
44
+ def answer(span, vcs, version)
45
+ answered = {
46
+ "from" => span.from,
47
+ "to" => span.to,
48
+ "asset_version" => { "vcs" => vcs, "external_id" => span.external_id },
49
+ "intents" => intents(version)
50
+ }
51
+ uncommitted?(span, vcs) ? answered.merge("uncommitted" => true) : answered
52
+ end
53
+
54
+ def uncommitted?(span, vcs)
55
+ vcs == DEFAULT_VCS && UNCOMMITTED.match?(span.external_id)
56
+ end
57
+
58
+ def intents(version)
59
+ return [] if version.nil?
60
+
61
+ version.intent_records.map { |record| Formatter.full(record) }
62
+ end
63
+
64
+ # Read once for the whole payload rather than per span. A blamed range is a
65
+ # handful of changes however many lines it covers, and asking per span
66
+ # would make the query count grow with the size of the range.
67
+ def versions(spans, vcs)
68
+ ids = spans.map { |span| AssetVersionNormalizer.lookup_id(vcs, span.external_id) }.uniq
69
+ scope = Models::AssetVersion.joins(:vcs_system)
70
+ .where(vcs_systems: { name: vcs }, external_id: ids)
71
+ .preload(intent_records: Formatter::PRELOADS)
72
+ scope.index_by(&:external_id)
73
+ end
74
+ end
75
+ end
76
+ end
@@ -14,7 +14,7 @@ module IntentRecord
14
14
  version = AssetVersionResolver.new(external_id: @external_id, vcs: @vcs).call
15
15
  {
16
16
  "asset_version" => Formatter.asset_version(version),
17
- "intents" => Formatter.preloaded(version.intent_records.order(:created_at)).map { |r| Formatter.full(r) }
17
+ "intents" => Formatter.preloaded(version.intent_records).map { |r| Formatter.full(r) }
18
18
  }
19
19
  end
20
20
  end
@@ -5,11 +5,14 @@ require_relative "../models/intent_record"
5
5
  require_relative "../linkers/asset_version_linker"
6
6
  require_relative "../linkers/stakeholder_linker"
7
7
  require_relative "../linkers/intent_linker"
8
+ require_relative "../linkers/link_keys"
8
9
 
9
10
  module IntentRecord
10
11
  module Commands
11
12
  # Creates an intent record and links it to commits, stakeholder sources and related intents.
12
13
  class Record
14
+ KEYS = (%w[summary body author] + Linkers::LINK_KEYS).freeze
15
+
13
16
  def call(input)
14
17
  attributes = validated(input)
15
18
 
@@ -25,6 +28,7 @@ module IntentRecord
25
28
  # Nothing here reaches the database, so bad input is refused before the
26
29
  # store is asked anything, and these rules can be exercised without one.
27
30
  def validated(input)
31
+ InputValidator.known_keys!(input, KEYS, renamed: Linkers::OUTPUT_NAMES)
28
32
  { summary: summary(input),
29
33
  body: InputValidator.required_string!(input, "body"),
30
34
  author: InputValidator.optional_string!(input, "author"),
@@ -1,49 +1,76 @@
1
1
  require_relative "../formatter"
2
- require_relative "../like_pattern"
2
+ require_relative "../match_expression"
3
+ require_relative "../search_membership"
4
+ require_relative "../search_ranking"
5
+ require_relative "../search_snippet"
6
+ require_relative "../search_term"
3
7
  require_relative "../models/intent_record"
4
8
 
5
9
  module IntentRecord
6
10
  module Commands
7
- # Case-insensitive substring search over summary, body, and linked stakeholder uris and titles,
8
- # so a ticket key such as ACME-42 finds the intents built for it.
11
+ # Search over summary, body, and linked stakeholder uris and titles, so a
12
+ # ticket key such as ACME-42 finds the intents built for it.
13
+ #
14
+ # Which records answer is SearchMembership's decision and what order they
15
+ # answer in is SearchRanking's. The two are kept apart because they read a
16
+ # term differently, and only one of them may be trusted with a term that
17
+ # carries punctuation.
9
18
  class Search
10
19
  LIMIT = 200
11
- FIELDS = %w[intent_records.summary intent_records.body stakeholder_sources.uri stakeholder_sources.title].freeze
20
+ MATCH_MODES = %w[any all].freeze
12
21
 
22
+ # Refuses bad input here, before the store is asked anything.
13
23
  def initialize(terms:, match: "any")
14
- @terms = terms.map(&:strip).reject(&:empty?)
24
+ raw = terms.map(&:strip).reject(&:empty?)
25
+ raise ValidationError, "At least one search term is required" if raw.empty?
26
+ raise ValidationError, "--match must be any or all" unless MATCH_MODES.include?(match)
27
+
28
+ @terms = raw.map { |term| SearchTerm.parse(term) }
15
29
  @match = match
16
30
  end
17
31
 
18
32
  def call
19
- raise ValidationError, "At least one search term is required" if @terms.empty?
20
- raise ValidationError, "--match must be any or all" unless %w[any all].include?(@match)
21
-
22
- { "intents" => matching_records.map { |r| Formatter.full(r) } }
33
+ { "intents" => matching_records.map { |r| formatted(r) } }
23
34
  end
24
35
 
25
36
  private
26
37
 
38
+ # The snippet belongs to the search rather than to the record, so it is
39
+ # merged here instead of in Formatter, which every other command shares.
40
+ def formatted(record)
41
+ snippet = SearchSnippet.text(indexed: record[SearchSnippet::COLUMN], body: record.body)
42
+ Formatter.full(record).merge(SearchSnippet::COLUMN => snippet)
43
+ end
44
+
27
45
  def matching_records
28
- Formatter.preloaded(
29
- Models::IntentRecord.left_joins(:stakeholder_sources)
30
- .group("intent_records.id")
31
- .having(having_sql, *having_binds)
32
- .order(created_at: :desc).limit(LIMIT)
33
- )
46
+ Formatter.preloaded(with_ranking(matching_scope))
34
47
  end
35
48
 
36
- def having_sql
37
- joiner = @match == "all" ? " AND " : " OR "
38
- @terms.map { "SUM(CASE WHEN #{term_clause} THEN 1 ELSE 0 END) > 0" }.join(joiner)
49
+ def matching_scope
50
+ Models::IntentRecord.left_joins(:stakeholder_sources)
51
+ .group("intent_records.id")
52
+ .having(*SearchMembership.new(terms: @terms, match: @match).condition)
53
+ .limit(LIMIT)
39
54
  end
40
55
 
41
- def term_clause
42
- FIELDS.map { |f| LikePattern.contains(f) }.join(" OR ")
56
+ # Only the terms the index may answer rank anything. A term it may not be
57
+ # trusted with would rank by text the person did not ask for, which is the
58
+ # same reason it does not decide membership either.
59
+ def indexable
60
+ @terms.select(&:indexable?)
43
61
  end
44
62
 
45
- def having_binds
46
- @terms.flat_map { |t| [LikePattern.contains_bind(t)] * FIELDS.size }
63
+ # Joins the relevance and fragment the index found, and orders by them.
64
+ # Terms that hold no searchable token leave nothing to rank, and an empty
65
+ # MATCH is a syntax error rather than an expression matching nothing, so
66
+ # that case orders by the tie-break alone and the body stands in for the
67
+ # fragment.
68
+ def with_ranking(scope)
69
+ expression = MatchExpression.for(indexable)
70
+ return scope.order(Arel.sql(SearchRanking::TIE_BREAK)) if expression.nil?
71
+
72
+ join = Models::IntentRecord.sanitize_sql_array([SearchRanking::JOIN, expression])
73
+ scope.select(SearchRanking::SELECTION).joins(join).order(Arel.sql(SearchRanking::ORDER))
47
74
  end
48
75
  end
49
76
  end
@@ -37,15 +37,38 @@ module IntentRecord
37
37
  end
38
38
  end
39
39
 
40
- def hashes_with!(values, label, *keys)
40
+ def hashes_with!(values, label, *keys, optional: [])
41
41
  values.each do |v|
42
42
  raise ValidationError, "#{label} entries must be objects" unless v.is_a?(Hash)
43
43
 
44
+ known_keys!(v, keys + optional, within: "#{label} entries")
44
45
  keys.each { |k| required_string!(v, k) }
45
46
  end
46
47
  values
47
48
  end
48
49
 
50
+ # A key nobody reads is a request the caller believes was carried out, so
51
+ # it is refused rather than ignored. `renamed` maps a name the output uses
52
+ # to the key input takes for it, because the output's name is the obvious
53
+ # wrong guess.
54
+ def known_keys!(input, accepted, renamed: {}, within: nil)
55
+ unknown = input.keys - accepted
56
+ return input if unknown.empty?
57
+
58
+ raise ValidationError, unknown_keys_message(unknown, accepted, renamed, within)
59
+ end
60
+
61
+ def unknown_keys_message(unknown, accepted, renamed, within)
62
+ where = within ? " in #{within}" : ""
63
+ noun = unknown.one? ? "key" : "keys"
64
+ hints = unknown.filter_map { |key| renamed_hint(key, renamed[key]) }
65
+ "Unknown #{noun}#{where}: #{unknown.join(", ")}. Accepted keys: #{accepted.join(", ")}.#{hints.join}"
66
+ end
67
+
68
+ def renamed_hint(key, input_key)
69
+ " #{key} is what the output calls it; input takes #{input_key}." if input_key
70
+ end
71
+
49
72
  def non_blank_string!(input, key)
50
73
  value = input[key]
51
74
  raise ValidationError, "#{key} is required" if value.nil?
@@ -64,6 +87,6 @@ module IntentRecord
64
87
  end
65
88
 
66
89
  # Steps of required_string!, not part of what this module offers callers.
67
- private_class_method :non_blank_string!, :within_length!
90
+ private_class_method :non_blank_string!, :within_length!, :unknown_keys_message, :renamed_hint
68
91
  end
69
92
  end
@@ -0,0 +1,11 @@
1
+ module IntentRecord
2
+ module Linkers
3
+ # The payload keys the linkers read, which `record` and `attach` both accept.
4
+ LINK_KEYS = %w[commits asset_versions stakeholder_references related_intent_ids].freeze
5
+
6
+ # Output fields whose input key is spelled differently. The output's
7
+ # `related_intents` is a list of records and the input's is a list of ids,
8
+ # so accepting the output name would give one name two shapes.
9
+ OUTPUT_NAMES = { "related_intents" => "related_intent_ids" }.freeze
10
+ end
11
+ end
@@ -24,7 +24,7 @@ module IntentRecord
24
24
 
25
25
  def call(input)
26
26
  refs = InputValidator.hashes_with!(InputValidator.array!(input, "stakeholder_references"),
27
- "stakeholder_references", "system", "uri")
27
+ "stakeholder_references", "system", "uri", optional: %w[title])
28
28
  refs.map { |ref| link!(ref) }
29
29
  end
30
30
 
@@ -0,0 +1,50 @@
1
+ module IntentRecord
2
+ # Turns the terms a user typed into an FTS5 MATCH expression.
3
+ #
4
+ # FTS5 reads its right-hand side as an expression language, not as text: `100%`
5
+ # is a syntax error and a term such as `OR` or `NEAR` is an operator. Quoting
6
+ # each term makes it a phrase, which is the only form that carries whatever the
7
+ # user typed through the parser unread.
8
+ #
9
+ # Phrases are joined with OR. The expression is used twice, and OR is right
10
+ # for both: SearchMembership asks the index one term at a time, so an
11
+ # expression there holds a single phrase and the joiner never applies; and
12
+ # SearchRanking asks it about every term at once, where a record is scored on
13
+ # whichever terms it holds rather than dropped for lacking one, because which
14
+ # records answer has already been settled and AND would score some of them at
15
+ # nothing.
16
+ module MatchExpression
17
+ JOINER = " OR ".freeze
18
+ QUOTE = '"'.freeze
19
+
20
+ module_function
21
+
22
+ # Takes SearchTerms, which carry the text and the column the person named.
23
+ def for(terms)
24
+ phrases = terms.map { |term| phrase(term) }.compact
25
+ return nil if phrases.empty?
26
+
27
+ phrases.join(JOINER)
28
+ end
29
+
30
+ def phrase(term)
31
+ # A term of pure punctuation tokenises to nothing, and an empty phrase is
32
+ # a syntax error rather than a phrase that matches nothing.
33
+ return nil unless term.text.match?(/[[:alnum:]]/)
34
+
35
+ column(term.index_column) + quoted(term.text)
36
+ end
37
+
38
+ # FTS5 reads `summary:"retry"` as that phrase in that column only. A term
39
+ # naming no column is left unprefixed and is answered over all of them.
40
+ def column(name)
41
+ name.nil? ? "" : "#{name}:"
42
+ end
43
+
44
+ def quoted(text)
45
+ "#{QUOTE}#{text.gsub(QUOTE, QUOTE * 2)}#{QUOTE}"
46
+ end
47
+
48
+ private_class_method :phrase, :column, :quoted
49
+ end
50
+ end
@@ -4,7 +4,9 @@ module IntentRecord
4
4
  class AssetVersion < ApplicationRecord
5
5
  belongs_to :vcs_system
6
6
  has_many :intent_record_asset_versions, dependent: :destroy
7
- has_many :intent_records, through: :intent_record_asset_versions
7
+ # Oldest first, then id, so a commit carrying several intents reads as a
8
+ # story and the order is the query's rather than the plan's or Ruby's.
9
+ has_many :intent_records, -> { order(:created_at, :id) }, through: :intent_record_asset_versions
8
10
 
9
11
  validates :external_id, presence: true, uniqueness: { scope: :vcs_system_id }
10
12
  end
@@ -0,0 +1,7 @@
1
+ module IntentRecord
2
+ # The FTS5 table over intent records, created by the migration of the same
3
+ # name. Named here once, for the two modules that read it.
4
+ module SearchIndex
5
+ TABLE = "intent_search".freeze
6
+ end
7
+ end
@@ -0,0 +1,62 @@
1
+ require_relative "like_pattern"
2
+ require_relative "match_expression"
3
+ require_relative "search_ranking"
4
+ require_relative "search_term"
5
+
6
+ module IntentRecord
7
+ # Which records a search answers with.
8
+ #
9
+ # Two ways of matching sit behind one condition. Substring matching reads a
10
+ # term as the literal it is, which is what a person typing `100%` or `ACME-4`
11
+ # is asking for. The index reads it as a word, which is what finds `retried`
12
+ # for someone who typed `retry`.
13
+ #
14
+ # They are not interchangeable, and the index is the narrower of the two in
15
+ # one direction and the wider in the other. It cannot see inside a word, so it
16
+ # would lose `ACME-4` in `ACME-42`; and it drops punctuation, so, measured, it
17
+ # matches `100 percent` for `100%` and `done now` for `done_now`. A term the
18
+ # index may not be trusted with therefore gets the substring arm alone, which
19
+ # SearchTerm#indexable? decides.
20
+ class SearchMembership
21
+ JOINERS = { "all" => " AND ", "any" => " OR " }.freeze
22
+
23
+ def initialize(terms:, match:)
24
+ @terms = terms
25
+ @match = match
26
+ end
27
+
28
+ # Ready for `having`: the condition followed by its binds, in order.
29
+ def condition
30
+ clauses = @terms.map { |term| clause(term) }
31
+ [clauses.map(&:first).join(JOINERS.fetch(@match)), *clauses.flat_map { |c| c.drop(1) }]
32
+ end
33
+
34
+ private
35
+
36
+ def clause(term)
37
+ arms = [substring_arm(term), *index_arm(term)]
38
+ ["(#{arms.join(" OR ")})", *substring_binds(term), *index_binds(term)]
39
+ end
40
+
41
+ # Counted rather than tested for, because the join to stakeholder_sources
42
+ # gives a record one row per source and the condition is read after grouping.
43
+ def substring_arm(term)
44
+ "SUM(CASE WHEN #{term.fields.map { |f| LikePattern.contains(f) }.join(" OR ")} THEN 1 ELSE 0 END) > 0"
45
+ end
46
+
47
+ def substring_binds(term)
48
+ [LikePattern.contains_bind(term.text)] * term.fields.size
49
+ end
50
+
51
+ def index_arm(term)
52
+ return [] unless term.indexable?
53
+
54
+ ["EXISTS (SELECT 1 FROM #{SearchRanking::TABLE} " \
55
+ "WHERE #{SearchRanking::TABLE} MATCH ? AND #{SearchRanking::TABLE}.rowid = intent_records.id)"]
56
+ end
57
+
58
+ def index_binds(term)
59
+ term.indexable? ? [MatchExpression.for([term])] : []
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,57 @@
1
+ require_relative "search_index"
2
+ require_relative "search_snippet"
3
+
4
+ module IntentRecord
5
+ # The order a search answers in.
6
+ #
7
+ # Which records match is settled by the substring search, because that is what
8
+ # a person typing `100%` or `ACME-4` is asking for and FTS5 cannot answer it:
9
+ # it tokenises, so it neither sees a substring inside a word nor tells `100%`
10
+ # from `100 percent`. What it can do is say which of the matches the terms are
11
+ # actually about, and that is all it is asked here.
12
+ #
13
+ # bm25 returns a negative score, better the lower, so ascending is best first.
14
+ # A record the index cannot see scores nothing and sorts after every record it
15
+ # can, which is the right place for a hit the terms only touch as a substring.
16
+ module SearchRanking
17
+ TABLE = SearchIndex::TABLE
18
+ ALIAS = "ranking".freeze
19
+
20
+ # Weights per indexed column, in the order the index declares them. A term in
21
+ # a one-line summary is a stronger signal than the same term somewhere in a
22
+ # body that may run for pages, and bm25's own length normalisation does not
23
+ # say so on its own.
24
+ SUMMARY_WEIGHT = 10.0
25
+ BODY_WEIGHT = 1.0
26
+
27
+ # Every ranked list needs a total order, or the rows that tie come back in
28
+ # whatever order the plan produces. Newest first among equals, then id, which
29
+ # is the order `recent` already answers in.
30
+ TIE_BREAK = "intent_records.created_at DESC, intent_records.id DESC".freeze
31
+
32
+ NO_MATCH_SCORE = 0.0
33
+
34
+ # The relevance and the fragment for every record the terms match, computed
35
+ # once for the search and joined to the candidates. Once, not once per
36
+ # record: a correlated subquery measured eight seconds for a common word on
37
+ # twenty-five thousand records, this a quarter of a second. `LIMIT -1` is
38
+ # what keeps SQLite from flattening the subquery into the outer query, where
39
+ # bm25 and snippet lose their context; the plan reports it as MATERIALIZE,
40
+ # and SearchRankingPlanTest holds it there. The `?` is filled by the caller
41
+ # through sanitize_sql_array.
42
+ JOIN = <<~SQL.squish.freeze
43
+ LEFT JOIN (
44
+ SELECT rowid AS indexed_id,
45
+ bm25(#{TABLE}, #{SUMMARY_WEIGHT}, #{BODY_WEIGHT}) AS relevance,
46
+ #{SearchSnippet::EXPRESSION} AS #{SearchSnippet::COLUMN}
47
+ FROM #{TABLE} WHERE #{TABLE} MATCH ? LIMIT -1
48
+ ) AS #{ALIAS} ON #{ALIAS}.indexed_id = intent_records.id
49
+ SQL
50
+
51
+ ORDER = "COALESCE(#{ALIAS}.relevance, #{NO_MATCH_SCORE}) ASC, #{TIE_BREAK}".freeze
52
+
53
+ # What a search selects when it ranks: the record, and the fragment the
54
+ # subquery found for it.
55
+ SELECTION = "intent_records.*, #{ALIAS}.#{SearchSnippet::COLUMN} AS #{SearchSnippet::COLUMN}".freeze
56
+ end
57
+ end
@@ -0,0 +1,52 @@
1
+ require_relative "search_index"
2
+
3
+ module IntentRecord
4
+ # What a search result shows instead of the whole body.
5
+ #
6
+ # A result carries the whole body, which is right for an agent reading one
7
+ # record and wrong for a person scanning two hundred. The index can say which
8
+ # part of a body the terms landed in, and that is the part worth reading first.
9
+ #
10
+ # It can only say it for a record it matched, though, and a term matched as a
11
+ # substring inside a longer word is one it never saw. Those fall back to the
12
+ # opening of the body, so every result carries something rather than leaving a
13
+ # blank in a list where every other row has text.
14
+ module SearchSnippet
15
+ # Roughly a sentence or two either side of the match, which is enough to see
16
+ # why a record answered without turning the list back into a wall of prose.
17
+ INDEX_TOKENS = 20
18
+ FALLBACK_LENGTH = 200
19
+ ELLIPSIS = "…".freeze
20
+
21
+ # Marks are left empty deliberately. A fragment with `[` and `]` around the
22
+ # match reads as punctuation the writer typed, and a fragment with HTML in it
23
+ # is either escaped into visible markup or trusted, and neither is wanted.
24
+ # Column 1 is the body. Evaluated inside SearchRanking's subquery, which is
25
+ # the one place a search still holds the index's context.
26
+ EXPRESSION = "snippet(#{SearchIndex::TABLE}, 1, '', '', '#{ELLIPSIS}', #{INDEX_TOKENS})".freeze
27
+
28
+ COLUMN = "snippet".freeze
29
+
30
+ module_function
31
+
32
+ def text(indexed:, body:)
33
+ return indexed unless indexed.nil? || indexed.empty?
34
+
35
+ shortened(body.to_s)
36
+ end
37
+
38
+ # Cut at the last space where there is one, so the reader is not shown a
39
+ # fragment of a word. Japanese and Chinese prose has no spaces, and neither
40
+ # does a long url or a hash, and a cut that found no space and kept nothing
41
+ # showed an ellipsis on its own.
42
+ def shortened(body)
43
+ return body if body.length <= FALLBACK_LENGTH
44
+
45
+ cut = body[0, FALLBACK_LENGTH]
46
+ at_word = cut.rpartition(/\s/).first.rstrip
47
+ "#{at_word.empty? ? cut : at_word}#{ELLIPSIS}"
48
+ end
49
+
50
+ private_class_method :shortened
51
+ end
52
+ end
@@ -0,0 +1,59 @@
1
+ module IntentRecord
2
+ # One term a person typed, read into the fields it asks about and the text to
3
+ # look for in them.
4
+ #
5
+ # A term may name a field, as in `summary:retry`, for the case where a common
6
+ # word appears everywhere and ranking it first is not enough. The hazard that
7
+ # comes with it is that a ticket uri carries a colon too, so only the known
8
+ # names count as a name and anything else before a colon stays part of the term.
9
+ class SearchTerm
10
+ RECORD_FIELDS = { "summary" => "intent_records.summary", "body" => "intent_records.body" }.freeze
11
+ STAKEHOLDER_FIELDS = { "uri" => "stakeholder_sources.uri", "title" => "stakeholder_sources.title" }.freeze
12
+ FIELDS = RECORD_FIELDS.merge(STAKEHOLDER_FIELDS).freeze
13
+ ALL_FIELDS = FIELDS.values.freeze
14
+
15
+ # Case-insensitive, as every other name the tool takes is.
16
+ NAMED = /\A(#{FIELDS.keys.join("|")}):(.*)\z/mi
17
+
18
+ # Text the index may be trusted with: letters, digits and the spaces between
19
+ # them, with at least one letter or digit to tokenise. Anything else the
20
+ # index would drop, and dropping punctuation is how `100%` comes to match a
21
+ # record that only ever said `100 percent`.
22
+ WORD = /\A(?=.*[[:alnum:]])[[:alnum:][:space:]]+\z/
23
+
24
+ attr_reader :text, :fields, :index_column
25
+
26
+ def self.parse(raw)
27
+ match = NAMED.match(raw)
28
+ return new(text: raw, fields: ALL_FIELDS, index_column: nil) if match.nil?
29
+
30
+ named(match[1].downcase, match[2])
31
+ end
32
+
33
+ # The shell hands `uri: acme-42` over as one word with the space inside,
34
+ # and the space is not part of what is being looked for.
35
+ def self.named(name, text)
36
+ text = text.strip
37
+ raise ValidationError, "#{name}: needs something to look for" if text.empty?
38
+
39
+ new(text: text, fields: [FIELDS.fetch(name)], index_column: RECORD_FIELDS.key?(name) ? name : nil)
40
+ end
41
+
42
+ def initialize(text:, fields:, index_column:)
43
+ @text = text
44
+ @fields = fields
45
+ @index_column = index_column
46
+ # Named a stakeholder field, which the index does not hold. Distinguished
47
+ # from a plain term, where a nil column means every column of the index.
48
+ @off_index = index_column.nil? && fields != ALL_FIELDS
49
+ end
50
+
51
+ # Whether the index may answer this term at all: not for a field it does
52
+ # not hold, and not for text it would read differently from the person.
53
+ def indexable?
54
+ !@off_index && WORD.match?(text)
55
+ end
56
+
57
+ private_class_method :named
58
+ end
59
+ end
@@ -1,3 +1,3 @@
1
1
  module IntentRecord
2
- VERSION = "1.1.0".freeze
2
+ VERSION = "2.0.0".freeze
3
3
  end
@@ -11,7 +11,9 @@
11
11
  · <code class="id"><%= h r["intent_id"] %></code>
12
12
  </div>
13
13
  </header>
14
- <div class="body"><%= h r["body"] %></div>
14
+ <%# A search result carries the fragment its terms landed in; every other
15
+ page shows one record, where the body is what the reader came for. %>
16
+ <div class="body"><%= h(r["snippet"] || r["body"]) %></div>
15
17
  <% if r["asset_versions"].any? %>
16
18
  <div class="links">
17
19
  <span class="label">Commits</span>
@@ -1,5 +1,5 @@
1
1
  <header>
2
2
  <h1>Search: <%= h query %></h1>
3
- <p class="subtitle">Intents whose summary, body, or linked ticket URL or title contain every word</p>
3
+ <p class="subtitle">Intents matching every word, most relevant first</p>
4
4
  </header>
5
5
  <%= intent_cards(intents) %>
data/lib/intent_record.rb CHANGED
@@ -16,6 +16,12 @@ end
16
16
  require "intent_record/config"
17
17
  require "intent_record/database"
18
18
  require "intent_record/global_id"
19
+ require "intent_record/match_expression"
20
+ require "intent_record/search_index"
21
+ require "intent_record/search_ranking"
22
+ require "intent_record/search_term"
23
+ require "intent_record/search_membership"
24
+ require "intent_record/search_snippet"
19
25
  require "intent_record/application_record"
20
26
  require "intent_record/models/vcs_system"
21
27
  require "intent_record/models/asset_version"
@@ -25,5 +31,7 @@ require "intent_record/models/stakeholder_system"
25
31
  require "intent_record/models/stakeholder_source"
26
32
  require "intent_record/models/stakeholder_reference"
27
33
  require "intent_record/models/intent_record_link"
34
+ require "intent_record/blame/spans"
35
+ require "intent_record/blame/porcelain"
28
36
  require "intent_record/backfill"
29
37
  require "intent_record/cli"