intent-record 1.0.0 → 1.2.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 871b5d799ddc9505ac23dbbd3bf468d243ae3c48a4c04574e9fd0fc596a579ae
4
- data.tar.gz: f6370c0f8003d35971d1b717c1ca7d24632b38b9568496c22e7605838397f9d6
3
+ metadata.gz: '09016b9ff684f0f9137aa00a6848f68b6018cd870495a73d9ebfe11dd4706d8f'
4
+ data.tar.gz: 93d53144d6ea2bfe0c997d6242ed4e0e34843392998562824196d44494a0c569
5
5
  SHA512:
6
- metadata.gz: 7d0ef27f3db2d4bf6616ea46f225462e778dad93c6433738d90f03e7c68fac5c2ee196681f1445a15673915d5ac449f0737d12974d01af97cdb618a4530f2759
7
- data.tar.gz: 5dc2d7077843e89318b6d8d5ef7238663eb531e8ab01633a63f7a40c96f025577751e2a757f27fa64e8e1c31a81eef4ca9c8829d818fdd0f4bffbb1faa61867a
6
+ metadata.gz: 34aa8df17cbecd1c6eda808dde6dbb54d8c13d6acd5741c62b89cfdfb54843a942f951cd06e7f84935d45486609a90ec3d3696bcd30dfbf9230694d0c2bc9f41
7
+ data.tar.gz: bfccfc5091b3fde1060e638d6e9f3f451daad4d8a984ca144d705bae19133a948f10f555213061510eea2dda252312bc0dd07db87c14dcce5eba39087cdababf
data/CHANGELOG.md CHANGED
@@ -6,6 +6,30 @@ Notable changes, one section per released version. The format follows
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 1.2.0 - 2026-09-20
10
+
11
+ ### Added
12
+
13
+ - `blame`, which answers "why is this line here" for a range of lines. Blame output goes in on stdin, so the tool still never shells out to git and the same command works for Perforce or Mercurial. `--format git-porcelain` reads what `git blame --porcelain` prints, so the common case is one command.
14
+ - Neighbouring lines from one change are answered once, as a span. A change the store has never heard of still gets a span, with no intents, and a line you have edited but not committed is marked `uncommitted`.
15
+ - A search term can name one field: `summary:retry`, `body:retry`, `uri:ACME-42`, `title:flaky`. The name is read in any case. Only those four names count, so a ticket url is still searched as itself.
16
+
17
+ ### Changed
18
+
19
+ - Search answers most relevant first rather than newest first, with a term in a summary counting for more than the same term in a long body. Each result carries the fragment of the body its terms landed in, and the GUI's search page shows that instead of every body in full.
20
+ - A plain search word now also matches the other forms of itself, so `retry` finds a record that said `retried`. A term carrying punctuation is still matched as the literal you typed, so `100%` does not match "100 percent" and `ACME-4` still finds `ACME-42`.
21
+ - Upgrading indexes the records a store already holds, so ranking works on existing history from the first run rather than only on what is recorded afterwards.
22
+
23
+ ## 1.1.0 - 2026-09-19
24
+
25
+ ### Added
26
+
27
+ - `backfill`, which recovers intent records from a repository's commit history. Commits go in on stdin as JSON, `--pattern` says what a ticket reference looks like and `--uri-prefix` turns each match into a stakeholder source. Afterwards `lookup` and `by-source` answer for commits made before the tool was adopted.
28
+ - A backfilled record says in its body that the reasoning was never recorded, so an agent can tell where the real reasoning still needs attaching.
29
+ - Commits for one ticket are chained oldest to newest. `--order` says which end of the input is the old end and defaults to newest-first, the order `git log` prints.
30
+ - A later pass with a different pattern adds its references to the records an earlier pass created and reports them as `linked`. A pass that finds nothing new writes nothing.
31
+ - `--dry-run` writes nothing and reports the sources it would create and the commit subjects nothing matched.
32
+
9
33
  ## 1.0.0 - 2026-09-18
10
34
 
11
35
  First release.
data/README.md CHANGED
@@ -1,11 +1,13 @@
1
1
  # intent-record
2
2
 
3
+ [![Gem Version](https://badge.fury.io/rb/intent-record.svg)](https://badge.fury.io/rb/intent-record)
3
4
  [![CI](https://github.com/beatmadsen/intent-record/actions/workflows/ci.yml/badge.svg)](https://github.com/beatmadsen/intent-record/actions/workflows/ci.yml)
4
5
 
5
6
  Local records storage for the intent behind individual code changes.
6
7
 
7
8
  A commit message says what changed. The intent record says why: what the agent (or person) was trying to achieve, which ticket or design page asked for it, and which earlier change it builds on. intent-record stores that in a local SQLite database, links it to the commit hash, and answers the questions people and agents ask later.
8
9
 
10
+ - "Why is this line here?" (`git blame --porcelain f.rb | intent-record blame --format git-porcelain`)
9
11
  - "What was this commit for?" (`lookup <hash>`)
10
12
  - "What did we build for this Jira ticket, and why that way?" (`by-source <url-or-key>`)
11
13
  - "Have we touched retry logic before, and what were we thinking?" (`search retry`)
@@ -45,6 +47,9 @@ intent-record lookup 8f3a1c2
45
47
  # Or comes at it from the ticket
46
48
  intent-record by-source ACME-42 --contains
47
49
 
50
+ # Or is staring at one line of a file and wants to know why it is there
51
+ git blame --porcelain lib/fetch.rb | intent-record blame --format git-porcelain
52
+
48
53
  # Or wants to read it in a browser
49
54
  intent-record serve
50
55
  ```
@@ -59,10 +64,12 @@ JSON in on stdin where input is needed, JSON out on stdout, exit code 0 on succe
59
64
  | `attach <intent_id>` | Link more commits, stakeholder references or related intents to an existing record (JSON via stdin) |
60
65
  | `show <intent_id>` | Full intent record with commits, stakeholder links and related intents |
61
66
  | `lookup <commit> [--vcs name]` | All intents recorded against a commit. Accepts a full hash or a unique prefix of at least 4 characters. Ids are unique per system, not across them, so an id recorded in two systems is reported as ambiguous; name one with `--vcs` |
62
- | `search <terms...> [--match all]` | Case-insensitive substring search over summary, body, and linked stakeholder URIs and titles, so a ticket key finds its intents |
67
+ | `search <terms...> [--match all]` | Search over summary, body, and linked stakeholder URIs and titles, most relevant first, so a ticket key finds its intents |
63
68
  | `by-source <uri> [--contains]` | Intents linked to a stakeholder source, plus the distinct commits across them. `--contains` matches a substring such as a ticket key |
64
69
  | `recent [--limit N]` | Newest intents first |
65
70
  | `systems` | Known VCS and stakeholder system names |
71
+ | `blame [--format git-porcelain]` | Intents for the commits a blame output names, answered as spans of lines (JSON via stdin, or `git blame --porcelain` output with `--format git-porcelain`) |
72
+ | `backfill` | Recover intent records from a history of commit messages (JSON via stdin) |
66
73
  | `serve [--port N]` | Start the web GUI on 127.0.0.1 (default port 4791) |
67
74
 
68
75
  ### Input shape for `record` and `attach`
@@ -87,6 +94,159 @@ Options take either `--name value` or `--name=value`. Unknown options and stray
87
94
 
88
95
  An intent can be recorded before the commit exists and linked with `attach` afterwards. This also covers rebases and squashes, where the same intent ends up on a new hash. One commit can carry several intents and one intent can span several commits.
89
96
 
97
+ ## Searching
98
+
99
+ Results come back most relevant first, not newest first, with a term in a summary
100
+ counting for more than the same term somewhere in a long body. Each result carries a
101
+ `snippet`: the part of the body the terms landed in, or the opening of the body when
102
+ the match was a literal one, so a page of hits is readable without opening any of them.
103
+
104
+ ```bash
105
+ intent-record search retry backoff # either word
106
+ intent-record search retry backoff --match all # both
107
+ intent-record search "retry the fetch" # the words in that order
108
+ ```
109
+
110
+ A plain word also matches the other forms of itself, so `retry` finds a record that
111
+ said `retried`. A term carrying punctuation is matched as the literal you typed:
112
+ `100%` does not match "100 percent", and `ACME-4` still finds `ACME-42` the way a
113
+ substring search does.
114
+
115
+ A term can name one field, for when a common word turns up everywhere:
116
+
117
+ ```bash
118
+ intent-record search summary:retry # summary, body, uri or title
119
+ ```
120
+
121
+ Only those four names count, so a ticket URL is searched as itself rather than read
122
+ as a field called `https`.
123
+
124
+ ## Why is this line here
125
+
126
+ `lookup` answers for a commit, which means finding the commit first. That is three
127
+ steps: run blame, copy the hash, look it up. `blame` does the whole thing.
128
+
129
+ ```bash
130
+ git blame --porcelain lib/fetch.rb | intent-record blame --format git-porcelain
131
+ git blame --porcelain -L 40,60 lib/fetch.rb | intent-record blame --format git-porcelain
132
+ ```
133
+
134
+ The answer is one entry per change rather than one per line, because neighbouring
135
+ lines from the same change collapse into a span:
136
+
137
+ ```json
138
+ {"spans": [
139
+ {"from": 40, "to": 44,
140
+ "asset_version": {"vcs": "git", "external_id": "8f3a1c2d..."},
141
+ "intents": [{"intent_id": "EUt4WMY", "summary": "Retry flaky fetches with backoff", "...": "..."}]},
142
+ {"from": 45, "to": 45,
143
+ "asset_version": {"vcs": "git", "external_id": "b2c4e6f8..."},
144
+ "intents": []},
145
+ {"from": 46, "to": 46,
146
+ "asset_version": {"vcs": "git", "external_id": "0000000000..."},
147
+ "intents": [], "uncommitted": true}
148
+ ]}
149
+ ```
150
+
151
+ A change nothing was recorded against still gets a span, with no intents. A line you
152
+ have edited but not committed is marked `uncommitted`, because there was never
153
+ anything to record against it.
154
+
155
+ The same change appearing twice in a file with someone else's edit between is
156
+ answered as two spans.
157
+
158
+ ### Other version control systems
159
+
160
+ `--format git-porcelain` is a convenience. The contract is JSON, and any tool that
161
+ can say which change a line came from can feed it:
162
+
163
+ ```bash
164
+ echo '{"vcs": "perforce", "lines": [{"line": 40, "external_id": "12345"}]}' | intent-record blame
165
+ ```
166
+
167
+ `vcs` defaults to `git`. Line numbers start at 1, and the same line given twice is
168
+ rejected rather than answered from one of the two changes.
169
+
170
+ ## Backfilling an existing repo
171
+
172
+ A repo that adopts intent-record already has years of history, and `lookup` and `by-source` answer nothing for any of it. That history is usually exactly what someone needs when they open unfamiliar code. The ticket keys are already in the commit messages, so `backfill` reads them and writes the rows `record` would have written at the time.
173
+
174
+ It recovers the graph, not the reasoning. A commit message says what changed, and only the person who made the change knew why. Every backfilled record says so in its body, so an agent that later touches that code knows the real reasoning is still to be attached.
175
+
176
+ Commits go in on stdin as JSON, so the tool never shells out to git and the same command works for Perforce or Mercurial:
177
+
178
+ ```bash
179
+ git log --format='%H%x00%an%x00%B%x01' | ruby -rjson -e '
180
+ commits = $stdin.read.split("\x01").map(&:strip).reject(&:empty?).map do |entry|
181
+ hash, author, message = entry.split("\x00", 3)
182
+ { "commit" => hash, "author" => author, "message" => message.to_s.strip }
183
+ end
184
+ puts JSON.generate({ "commits" => commits })
185
+ ' > history.json
186
+
187
+ intent-record backfill --system jira \
188
+ --pattern 'ACME-\d+' \
189
+ --uri-prefix https://acme.atlassian.net/browse/ \
190
+ --dry-run < history.json
191
+ ```
192
+
193
+ Start with `--dry-run`. It writes nothing, and it reports the sources it would create and the first twenty commit subjects nothing matched, which is how you find the second convention your team used before anything is written:
194
+
195
+ ```json
196
+ {"created": 128, "linked": 0, "skipped": 41, "failed": 0, "dry_run": true,
197
+ "sources": ["https://acme.atlassian.net/browse/ACME-42"],
198
+ "unmatched": ["Fix a typo in the README", "Bump version to 0.4.1"]}
199
+ ```
200
+
201
+ Drop `--dry-run` to write. Each commit that names a ticket gets one record, linked to that commit and to every ticket its message names. A commit naming no ticket is not stored at all.
202
+
203
+ A history may use more than one convention. Run it once per convention, each with its own system:
204
+
205
+ ```bash
206
+ intent-record backfill --system github-issues \
207
+ --pattern '(?<![A-Za-z])#(\d+)' \
208
+ --uri-prefix https://github.com/acme/api/issues/ < history.json
209
+ ```
210
+
211
+ A commit the first pass already recorded keeps that record and gains the references this pass finds, so a commit naming both a Jira key and a GitHub issue ends up linked to both. The report counts those as `linked` rather than `created`.
212
+
213
+ Reruns stay cheap. A pass that finds nothing new to link reports the commit as skipped and writes nothing.
214
+
215
+ ### Options
216
+
217
+ - `--system <name>` names the stakeholder system the references belong to. Required.
218
+ - `--pattern <regex>` says what a reference looks like in a message. Required.
219
+ - `--uri-prefix <url>` is prepended to the key to give the source uri. Without it, the whole match is the uri.
220
+ - `--dry-run` reports what it would write and writes nothing.
221
+ - `--order <newest-first|oldest-first>` says which end of the history the list starts at. Defaults to `newest-first`, which is what `git log` gives you.
222
+
223
+ A capture group narrows what gets appended to the prefix. `ACME-\d+` with prefix `https://acme.atlassian.net/browse/` appends `ACME-42`; `ENG-(\d+)` with prefix `https://linear.app/acme/issue/ENG-` appends `7`. The source is titled with the matched text either way, so `search ENG-7` finds it.
224
+
225
+ A pattern matches anywhere in the message, including inside another key. `#(\d+)` finds the `77` in an Azure `AB#77` and links it to GitHub issue 77, which is a different thing entirely. Where a history mixes conventions, anchor the loose one: `(?<![A-Za-z])#(\d+)` matches `closes #123` and `fix (#42)` while leaving `AB#77` alone.
226
+
227
+ Patterns are case-sensitive, and so are the uris they build. A history that writes `ACME-42` in some commits and `acme-42` in others gives you two sources. `(?i)acme-\d+` matches both, but each uri is still built from what the commit wrote, so the two are not merged.
228
+
229
+ There is no default pattern per system, because Jira and Linear keys look alike and only you know which one `ABC-123` means.
230
+
231
+ ### What it does with the history
232
+
233
+ Each entry takes a `commit` and an optional `message`, `author` and `ref`. A commit with no message matches nothing and is skipped rather than failing the run. The ref is the branch name, scanned alongside the message for teams that put the key in the branch and never in the commit.
234
+
235
+ Commits for the same ticket are chained. Each record links to the most recent earlier record for that ticket, so `show` on any one of them walks back through the others, and the chain continues across separate runs.
236
+
237
+ The chain is always written oldest to newest, so the later commit builds on the earlier one. That needs to know which end of your list is the old end, which is what `--order` says. `git log` prints newest first and that is the default, so a reversed list (`git log --reverse`) needs `--order oldest-first` or every link points backwards.
238
+
239
+ Each commit is written in its own transaction. One malformed hash in a history of thousands costs that commit and not the run, and the report names it:
240
+
241
+ ```json
242
+ {"created": 3, "linked": 0, "skipped": 1, "failed": 1,
243
+ "failures": [{"commit": "bad-hash", "error": "git commit must be 40 or 64 hex characters, got \"bad-hash\""}]}
244
+ ```
245
+
246
+ Those failures come back on every rerun, since a hash that is not a hash can never be written.
247
+
248
+ Rewriting history changes hashes, and a rerun after a rebase links the new hashes to new records. The old ones stay, pointing at commits that no longer exist.
249
+
90
250
  ## Data model
91
251
 
92
252
  Commit hashes are treated as globally unique, so the store does not track which repository a commit belongs to. VCS and stakeholder system names are lowercased on the way in, and the common ones are seeded on first connect; `intent-record systems` lists them. Unknown names are added on first use.
@@ -112,7 +272,7 @@ Related-intent links may form cycles; the store records what it is told and leav
112
272
 
113
273
  ## Agent integration
114
274
 
115
- Any agent that can run a process and read stdout can use it. Record after each commit, `lookup` before touching unfamiliar code, `by-source` when picking up a ticket that has history.
275
+ Any agent that can run a process and read stdout can use it. Record after each commit, `lookup` before touching unfamiliar code, `by-source` when picking up a ticket that has history, and `backfill` once when adopting the tool on a repository that already has history.
116
276
 
117
277
  For Claude Code there is a skill that says when to do each of those and what a usable `body` contains: [intent-record](https://github.com/beatmadsen/claude-skills/tree/main/skills/intent-record), in the [beatmadsen/claude-skills](https://github.com/beatmadsen/claude-skills) collection. Install it for every project you work on:
118
278
 
@@ -0,0 +1,64 @@
1
+ # A relevance index over the text of an intent record. It decides the order the
2
+ # search answers in, never which records the search answers with: FTS5 tokenises,
3
+ # so it cannot see a substring inside a word and it cannot tell `100%` from `100
4
+ # percent`, both of which the substring search is asked for and tested on.
5
+ #
6
+ # Kept in step by triggers rather than from Ruby, so a writer that never heard of
7
+ # the index cannot leave it stale. `backfill` writes through `record` today, but
8
+ # the guarantee should not depend on that staying true.
9
+ class CreateSearchIndex < ActiveRecord::Migration[8.0]
10
+ TABLE = "intent_search".freeze
11
+ SOURCE = "intent_records".freeze
12
+
13
+ def up
14
+ # An external-content table: the text lives in intent_records and the index
15
+ # stores only the terms, so the store does not carry a second copy of every
16
+ # body.
17
+ execute(<<~SQL)
18
+ CREATE VIRTUAL TABLE #{TABLE} USING fts5(
19
+ summary, body,
20
+ content='#{SOURCE}', content_rowid='id',
21
+ tokenize='porter unicode61'
22
+ )
23
+ SQL
24
+
25
+ create_triggers
26
+ backfill_existing
27
+ end
28
+
29
+ def down
30
+ %w[insert update delete].each { |event| execute("DROP TRIGGER IF EXISTS #{TABLE}_after_#{event}") }
31
+ execute("DROP TABLE IF EXISTS #{TABLE}")
32
+ end
33
+
34
+ private
35
+
36
+ # An external-content table is told about a change rather than reading it: the
37
+ # 'delete' command hands back the old text so FTS5 can retract the terms it
38
+ # indexed, which is why an update deletes before it inserts.
39
+ def create_triggers
40
+ execute(<<~SQL)
41
+ CREATE TRIGGER #{TABLE}_after_insert AFTER INSERT ON #{SOURCE} BEGIN
42
+ INSERT INTO #{TABLE}(rowid, summary, body) VALUES (new.id, new.summary, new.body);
43
+ END
44
+ SQL
45
+ execute(<<~SQL)
46
+ CREATE TRIGGER #{TABLE}_after_delete AFTER DELETE ON #{SOURCE} BEGIN
47
+ INSERT INTO #{TABLE}(#{TABLE}, rowid, summary, body) VALUES('delete', old.id, old.summary, old.body);
48
+ END
49
+ SQL
50
+ execute(<<~SQL)
51
+ CREATE TRIGGER #{TABLE}_after_update AFTER UPDATE ON #{SOURCE} BEGIN
52
+ INSERT INTO #{TABLE}(#{TABLE}, rowid, summary, body) VALUES('delete', old.id, old.summary, old.body);
53
+ INSERT INTO #{TABLE}(rowid, summary, body) VALUES (new.id, new.summary, new.body);
54
+ END
55
+ SQL
56
+ end
57
+
58
+ # A store that already holds records gets them indexed here, so ranking works
59
+ # on the history from the first run after the upgrade rather than only on what
60
+ # is written afterwards.
61
+ def backfill_existing
62
+ execute("INSERT INTO #{TABLE}(rowid, summary, body) SELECT id, summary, body FROM #{SOURCE}")
63
+ end
64
+ end
@@ -0,0 +1,54 @@
1
+ require_relative "../models/intent_record"
2
+
3
+ module IntentRecord
4
+ module Backfill
5
+ # The text a backfilled record carries.
6
+ #
7
+ # A commit message says what changed, not why, and backfill cannot invent
8
+ # the why. So the body says plainly that the reasoning was never recorded,
9
+ # and the commit message follows it. The marker is a fixed string, which is
10
+ # what lets an agent find these records later and attach the real reasoning,
11
+ # and what a migration would search for if this ever becomes a column.
12
+ #
13
+ # The message is copied rather than pointed at: the store keeps no
14
+ # repository identity, so "see the commit" names no git anyone could open,
15
+ # and search, by-source and the GUI all read the store alone.
16
+ class BackfilledIntent
17
+ MARKER = "Backfilled from the commit message; the reasoning behind this change was not recorded.".freeze
18
+ SUMMARY_LIMIT = Models::IntentRecord::SUMMARY_MAX_LENGTH
19
+ BLANK_SUMMARY = "Backfilled commit with no message".freeze
20
+ ELLIPSIS = "...".freeze
21
+
22
+ def initialize(message:, author:)
23
+ @message = message.to_s
24
+ @author = author
25
+ end
26
+
27
+ def to_h
28
+ { "summary" => summary, "body" => body, "author" => @author }
29
+ end
30
+
31
+ private
32
+
33
+ # A truncated summary loses nothing: the body below keeps the subject
34
+ # whole.
35
+ def summary
36
+ subject.empty? ? BLANK_SUMMARY : truncated(subject)
37
+ end
38
+
39
+ def body
40
+ [MARKER, @message.strip].reject(&:empty?).join("\n\n")
41
+ end
42
+
43
+ def subject
44
+ @message.strip.lines.first.to_s.strip.gsub(/\s+/, " ")
45
+ end
46
+
47
+ def truncated(text)
48
+ return text if text.length <= SUMMARY_LIMIT
49
+
50
+ "#{text[0, SUMMARY_LIMIT - ELLIPSIS.length]}#{ELLIPSIS}"
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,39 @@
1
+ require_relative "../input_validator"
2
+
3
+ module IntentRecord
4
+ module Backfill
5
+ # Reads what a backfill payload says about each commit. Every entry is
6
+ # checked before any is returned, so a payload with a bad entry late in the
7
+ # list never reaches the database. Nothing here needs one.
8
+ module CommitSpecs
9
+ module_function
10
+
11
+ def from(input)
12
+ entries(input).map { |entry| spec(entry) }
13
+ end
14
+
15
+ def entries(input)
16
+ InputValidator.array!(input, "commits")
17
+ end
18
+
19
+ def spec(entry)
20
+ raise ValidationError, "commits entries must be objects" unless entry.is_a?(Hash)
21
+
22
+ { commit: InputValidator.required_string!(entry, "commit"),
23
+ message: message(entry),
24
+ author: InputValidator.optional_string!(entry, "author"),
25
+ ref: InputValidator.optional_string!(entry, "ref") }
26
+ end
27
+
28
+ # An empty commit message is rare and real, and it names no ticket, so it
29
+ # is the same as any commit matching nothing. Refusing it would abort a
30
+ # whole history over one commit nobody wrote a message for. A message that
31
+ # is not a string is still a malformed payload rather than an absent one.
32
+ def message(entry)
33
+ InputValidator.optional_string!(entry, "message").to_s
34
+ end
35
+
36
+ private_class_method :entries, :spec, :message
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,46 @@
1
+ module IntentRecord
2
+ module Backfill
3
+ # What one dry run saw: the sources it would create and the commit subjects
4
+ # that matched nothing. A write run collects neither, because it is not an
5
+ # inspection, and reports neither.
6
+ class Inspection
7
+ # A real history has thousands of unmatched commits and nobody reads
8
+ # thousands of lines. Enough to recognise a convention, not enough to bury
9
+ # the counts.
10
+ UNMATCHED_SHOWN = 20
11
+
12
+ def initialize(collecting)
13
+ @collecting = collecting
14
+ @sources = []
15
+ @unmatched = []
16
+ end
17
+
18
+ def missed(subject)
19
+ @unmatched << subject if listable?(subject)
20
+ :skipped
21
+ end
22
+
23
+ def noted(references)
24
+ @sources.concat(references.map { |r| r["uri"] }) if @collecting
25
+ end
26
+
27
+ def to_h
28
+ return {} unless @collecting
29
+
30
+ { "dry_run" => true, "sources" => @sources.uniq, "unmatched" => @unmatched }
31
+ end
32
+
33
+ private
34
+
35
+ # A commit with no message has no subject to show, and a column of blank
36
+ # lines says nothing about what the pattern missed.
37
+ def listable?(subject)
38
+ @collecting && room_left? && !subject.empty?
39
+ end
40
+
41
+ def room_left?
42
+ @unmatched.size < UNMATCHED_SHOWN
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,49 @@
1
+ require_relative "../models/intent_record"
2
+ require_relative "../models/stakeholder_source"
3
+ require_relative "../stakeholder_normalizer"
4
+
5
+ module IntentRecord
6
+ module Backfill
7
+ # The intent a new record for these references builds on: the most recent
8
+ # earlier record against the same stakeholder source.
9
+ #
10
+ # The most recent one only, because linking to every earlier commit for a
11
+ # ticket would say each builds on all of them, which the history does not
12
+ # support. Asked of the store rather than remembered within a run, so a
13
+ # second run continues the chain the first one left.
14
+ module PredecessorFinder
15
+ module_function
16
+
17
+ # A commit naming two tickets with the same predecessor asks for that
18
+ # link once, which IntentLinker's find-or-create already settles, so the
19
+ # duplicate is left for it rather than removed twice.
20
+ def for(references)
21
+ references.filter_map { |reference| latest_intent_for(reference) }
22
+ end
23
+
24
+ def latest_intent_for(reference)
25
+ newest(intents_against(source_id(reference)))
26
+ end
27
+
28
+ def intents_against(source_id)
29
+ Models::IntentRecord.joins(:stakeholder_sources).where(stakeholder_sources: { id: source_id })
30
+ end
31
+
32
+ def newest(intents)
33
+ intents.order(created_at: :desc, id: :desc).first&.global_id
34
+ end
35
+
36
+ def source_id(reference)
37
+ Models::StakeholderSource.joins(:stakeholder_system)
38
+ .find_by(stakeholder_systems: { name: system_name(reference) },
39
+ uri: StakeholderNormalizer.uri(reference["uri"]))&.id
40
+ end
41
+
42
+ def system_name(reference)
43
+ StakeholderNormalizer.system_name(reference["system"])
44
+ end
45
+
46
+ private_class_method :latest_intent_for, :intents_against, :newest, :source_id, :system_name
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,70 @@
1
+ module IntentRecord
2
+ module Backfill
3
+ # Reads the stakeholder references a commit message names, as the
4
+ # `stakeholder_references` entries `record` already accepts. Nothing here
5
+ # reaches the database.
6
+ class ReferenceScanner
7
+ # A pattern that backtracks catastrophically would otherwise hang the
8
+ # command with no output. Ruby's engine memoises its way out of every
9
+ # such pattern this suite could construct, so the budget rarely decides
10
+ # anything; it is what stands between a report and a hang on an engine
11
+ # that gives up.
12
+ MATCH_TIMEOUT_SECONDS = 2.0
13
+
14
+ def initialize(system:, pattern:, uri_prefix:)
15
+ @system = system
16
+ @pattern = compiled(pattern)
17
+ @uri_prefix = uri_prefix.to_s
18
+ end
19
+
20
+ def call(message)
21
+ distinct(matches(message)).map { |match| reference(match) }
22
+ rescue Regexp::TimeoutError
23
+ raise ValidationError, timeout_message
24
+ end
25
+
26
+ private
27
+
28
+ def compiled(pattern)
29
+ Regexp.new(pattern, timeout: MATCH_TIMEOUT_SECONDS)
30
+ rescue RegexpError => e
31
+ raise ValidationError, "--pattern is not a valid regular expression: #{e.message}"
32
+ end
33
+
34
+ # Scanned as MatchData rather than with String#scan, because scan throws
35
+ # away the matched text as soon as the pattern has a group, and the title
36
+ # needs it.
37
+ def matches(message)
38
+ message.to_s.to_enum(:scan, @pattern).map { Regexp.last_match }
39
+ .map { |m| { uri: uri_for(key_of(m)), title: m[0] } }
40
+ end
41
+
42
+ # A message naming the same ticket twice, as merge commits do, asks for
43
+ # one source and not two. Keyed on the uri, because that is what makes a
44
+ # source the same source downstream.
45
+ def distinct(found)
46
+ found.uniq { |match| match[:uri] }
47
+ end
48
+
49
+ def reference(match)
50
+ { "system" => @system, "uri" => match[:uri], "title" => match[:title] }
51
+ end
52
+
53
+ def uri_for(key)
54
+ "#{@uri_prefix}#{key}"
55
+ end
56
+
57
+ # A pattern with a group says the uri is narrower than the text that found
58
+ # it: `ENG-(\d+)` finds `ENG-7` and means `7`, so the prefix can carry the
59
+ # project. With no group the whole match is the key.
60
+ def key_of(match)
61
+ match.size > 1 ? match[1] : match[0]
62
+ end
63
+
64
+ def timeout_message
65
+ "--pattern took longer than #{MATCH_TIMEOUT_SECONDS}s on one commit message; " \
66
+ "it probably backtracks catastrophically"
67
+ end
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,5 @@
1
+ require_relative "backfill/backfilled_intent"
2
+ require_relative "backfill/commit_specs"
3
+ require_relative "backfill/inspection"
4
+ require_relative "backfill/predecessor_finder"
5
+ require_relative "backfill/reference_scanner"
@@ -0,0 +1,37 @@
1
+ module IntentRecord
2
+ module Blame
3
+ # Reads `git blame --porcelain` into the lines the command takes.
4
+ #
5
+ # The JSON shape is the contract and this is a convenience, so that blaming a
6
+ # file from a git repository is one command rather than one command and a
7
+ # converter. Keeping it a separate reader is what stops the store learning
8
+ # anything about git: it produces the same payload a person could have
9
+ # written by hand, and a second version control system earns a second reader
10
+ # rather than a change here.
11
+ module Porcelain
12
+ # "<sha> <line in the original file> <line in this file> [<how many
13
+ # follow>]". The second number is the one a reader is asking about. Content
14
+ # lines are prefixed with a tab, so a file whose own text looks like a
15
+ # header is never read as one.
16
+ HEADER = /\A(?<id>[0-9a-f]{40}|[0-9a-f]{64}) \d+ (?<line>\d+)(?: \d+)?\z/
17
+
18
+ module_function
19
+
20
+ def lines(text)
21
+ found = text.to_s.lines.filter_map { |line| header(line) }
22
+ raise ValidationError, "No blame headers found. Expected `git blame --porcelain` output." if found.empty?
23
+
24
+ found
25
+ end
26
+
27
+ def header(line)
28
+ match = HEADER.match(line.chomp)
29
+ return nil if match.nil?
30
+
31
+ { "line" => match[:line].to_i, "external_id" => match[:id] }
32
+ end
33
+
34
+ private_class_method :header
35
+ end
36
+ end
37
+ end