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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b2abf7a93c2bbefd6b31f0ff8ee7f08def82e721b1166885b8701f1f003162e7
4
- data.tar.gz: f5754926ff4e9b0ff7d339423196487610e816bdd164f3fc96344fb9423ef83c
3
+ metadata.gz: 5239cbb8afea221a339fcc6f4e5aef7c157027df3a85807c2865f72392e6920e
4
+ data.tar.gz: 3c49aca4a8542ad0d4f65cb34bc969bb24d170c76de5c1de12d580df3dc4d356
5
5
  SHA512:
6
- metadata.gz: 844a434054ae004e8bc75bb84b20e6d9a301842e860f66f715add6ac14926fa9c378d83a79d8fccabcdc97e9ff28a4b0c8fbed28194fc90b3f558ff687d6c5f5
7
- data.tar.gz: 38a447b34c8fb3a2f4543c2d1c1e8d5cbb4d71669804cdd499b88ec6dfd1e48439fc26670f9e4e5bba838fa8bc4857a535a0abe6d9a8f59a2ed6008478904708
6
+ metadata.gz: a07a693526fd43910b64889c03cf0a393310e306ecb125575fdf8ad8ebd29e507b8eac35a9957d0503839b734d404cb6e34077007e5560a513136cf43c7bf7af
7
+ data.tar.gz: 4867b4b8379e6f7d362e164dd63f9474e9c1d3fbe6ee84849a555d7f625023b39af8b78bcccc9be7af2a2ccbebc5b782fb3d87748b0cc9da32064cb63f720074
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
+ ## 2.0.0 - 2026-11-11
10
+
11
+ A major version because input that 1.2.0 accepted is now refused. Nothing else in the contract changes: every command, flag and output key works as before.
12
+
13
+ ### Changed
14
+
15
+ - `record`, `attach`, `blame` and `backfill` refuse a JSON key they do not read, at the top level or inside an entry, and the error names the keys they accept. A misspelt key used to be ignored, so a link the caller asked for was never made while the command still exited 0. A payload that carries extra keys on purpose now fails and has to drop them, for example one built by editing `show` output, which carries `intent_id`, `created_at` and `related_by_intents`.
16
+ - `related_intents`, the name the output uses, is refused on input with a pointer to `related_intent_ids` rather than accepted as a second spelling.
17
+ - `serve` runs on Puma 8, up from 6.
18
+
19
+ ## 1.2.0 - 2026-09-20
20
+
21
+ ### Added
22
+
23
+ - `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.
24
+ - 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`.
25
+ - 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.
26
+
27
+ ### Changed
28
+
29
+ - 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.
30
+ - 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`.
31
+ - 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.
32
+
9
33
  ## 1.1.0 - 2026-09-19
10
34
 
11
35
  ### Added
data/README.md CHANGED
@@ -3,10 +3,11 @@
3
3
  [![Gem Version](https://badge.fury.io/rb/intent-record.svg)](https://badge.fury.io/rb/intent-record)
4
4
  [![CI](https://github.com/beatmadsen/intent-record/actions/workflows/ci.yml/badge.svg)](https://github.com/beatmadsen/intent-record/actions/workflows/ci.yml)
5
5
 
6
- Local records storage for the intent behind individual code changes.
6
+ A local store for the reasoning behind code changes, linked to commits and tickets.
7
7
 
8
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.
9
9
 
10
+ - "Why is this line here?" (`git blame --porcelain f.rb | intent-record blame --format git-porcelain`)
10
11
  - "What was this commit for?" (`lookup <hash>`)
11
12
  - "What did we build for this Jira ticket, and why that way?" (`by-source <url-or-key>`)
12
13
  - "Have we touched retry logic before, and what were we thinking?" (`search retry`)
@@ -46,6 +47,9 @@ intent-record lookup 8f3a1c2
46
47
  # Or comes at it from the ticket
47
48
  intent-record by-source ACME-42 --contains
48
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
+
49
53
  # Or wants to read it in a browser
50
54
  intent-record serve
51
55
  ```
@@ -60,10 +64,11 @@ JSON in on stdin where input is needed, JSON out on stdout, exit code 0 on succe
60
64
  | `attach <intent_id>` | Link more commits, stakeholder references or related intents to an existing record (JSON via stdin) |
61
65
  | `show <intent_id>` | Full intent record with commits, stakeholder links and related intents |
62
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` |
63
- | `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 |
64
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 |
65
69
  | `recent [--limit N]` | Newest intents first |
66
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`) |
67
72
  | `backfill` | Recover intent records from a history of commit messages (JSON via stdin) |
68
73
  | `serve [--port N]` | Start the web GUI on 127.0.0.1 (default port 4791) |
69
74
 
@@ -81,6 +86,8 @@ JSON in on stdin where input is needed, JSON out on stdout, exit code 0 on succe
81
86
  }
82
87
  ```
83
88
 
89
+ A key this shape does not list is refused with the list of keys that are accepted, so a misspelt key fails the command instead of silently dropping the link it asked for. The same holds inside each entry, and for the `blame` and `backfill` input. The output lists related intents under `related_intents`, but the input key is `related_intent_ids`, and the error says so if you send the output name.
90
+
84
91
  Options take either `--name value` or `--name=value`. Unknown options and stray arguments are rejected rather than ignored.
85
92
 
86
93
  `lookup` without `--vcs` searches every system and prefers an exact id match over a prefix match. Git commits must be full SHA-1 or SHA-256 hashes; they are stored lowercase. Prefix lookup applies to hash-based systems only (git, mercurial, fossil, sapling, pijul, darcs), so a Perforce changelist `1234` never matches `12345`. URIs are normalised (lowercase scheme and host, no trailing slash) and system names are lowercased and hyphenated, so `Jira` and `jira`, or a ticket URL with and without a trailing slash, are one source. A later non-blank `title` for a source replaces the stored one.
@@ -89,6 +96,79 @@ Options take either `--name value` or `--name=value`. Unknown options and stray
89
96
 
90
97
  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.
91
98
 
99
+ ## Searching
100
+
101
+ Results come back most relevant first, not newest first, with a term in a summary
102
+ counting for more than the same term somewhere in a long body. Each result carries a
103
+ `snippet`: the part of the body the terms landed in, or the opening of the body when
104
+ the match was a literal one, so a page of hits is readable without opening any of them.
105
+
106
+ ```bash
107
+ intent-record search retry backoff # either word
108
+ intent-record search retry backoff --match all # both
109
+ intent-record search "retry the fetch" # the words in that order
110
+ ```
111
+
112
+ A plain word also matches the other forms of itself, so `retry` finds a record that
113
+ said `retried`. A term carrying punctuation is matched as the literal you typed:
114
+ `100%` does not match "100 percent", and `ACME-4` still finds `ACME-42` the way a
115
+ substring search does.
116
+
117
+ A term can name one field, for when a common word turns up everywhere:
118
+
119
+ ```bash
120
+ intent-record search summary:retry # summary, body, uri or title
121
+ ```
122
+
123
+ Only those four names count, so a ticket URL is searched as itself rather than read
124
+ as a field called `https`.
125
+
126
+ ## Why is this line here
127
+
128
+ `lookup` answers for a commit, which means finding the commit first. That is three
129
+ steps: run blame, copy the hash, look it up. `blame` does the whole thing.
130
+
131
+ ```bash
132
+ git blame --porcelain lib/fetch.rb | intent-record blame --format git-porcelain
133
+ git blame --porcelain -L 40,60 lib/fetch.rb | intent-record blame --format git-porcelain
134
+ ```
135
+
136
+ The answer is one entry per change rather than one per line, because neighbouring
137
+ lines from the same change collapse into a span:
138
+
139
+ ```json
140
+ {"spans": [
141
+ {"from": 40, "to": 44,
142
+ "asset_version": {"vcs": "git", "external_id": "8f3a1c2d..."},
143
+ "intents": [{"intent_id": "EUt4WMY", "summary": "Retry flaky fetches with backoff", "...": "..."}]},
144
+ {"from": 45, "to": 45,
145
+ "asset_version": {"vcs": "git", "external_id": "b2c4e6f8..."},
146
+ "intents": []},
147
+ {"from": 46, "to": 46,
148
+ "asset_version": {"vcs": "git", "external_id": "0000000000..."},
149
+ "intents": [], "uncommitted": true}
150
+ ]}
151
+ ```
152
+
153
+ A change nothing was recorded against still gets a span, with no intents. A line you
154
+ have edited but not committed is marked `uncommitted`, because there was never
155
+ anything to record against it.
156
+
157
+ The same change appearing twice in a file with someone else's edit between is
158
+ answered as two spans.
159
+
160
+ ### Other version control systems
161
+
162
+ `--format git-porcelain` is a convenience. The contract is JSON, and any tool that
163
+ can say which change a line came from can feed it:
164
+
165
+ ```bash
166
+ echo '{"vcs": "perforce", "lines": [{"line": 40, "external_id": "12345"}]}' | intent-record blame
167
+ ```
168
+
169
+ `vcs` defaults to `git`. Line numbers start at 1, and the same line given twice is
170
+ rejected rather than answered from one of the two changes.
171
+
92
172
  ## Backfilling an existing repo
93
173
 
94
174
  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.
@@ -194,9 +274,9 @@ Related-intent links may form cycles; the store records what it is told and leav
194
274
 
195
275
  ## Agent integration
196
276
 
197
- 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.
277
+ Any agent that can run a process and read stdout can use it. Record after each commit, `blame` before changing lines whose history you do not know, `by-source` when picking up a ticket that has history, and `backfill` once when adopting the tool on a repository that already has history.
198
278
 
199
- 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:
279
+ For Claude Code and Cursor there is a skill that says when to do each of those and what a usable `body` contains, with a hook that shows an agent the intents behind the lines it reads: [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:
200
280
 
201
281
  ```bash
202
282
  git clone https://github.com/beatmadsen/claude-skills.git ~/claude-skills
@@ -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,115 @@
1
+ # Feature findings
2
+
3
+ A rulebook for building intent-record features that put records in front of agents at
4
+ the moment of an edit. Each rule was decided by a rendered pentsection search (eleven
5
+ rounds, each judged by a panel of three agents on real fun-ci records) and should hold
6
+ after the candidates are forgotten. The rounds and their candidates are in the git
7
+ history of `design/features/`; this file keeps only what they decided.
8
+
9
+ ## What to build first
10
+
11
+ - A reading feature earns its place only if a record changes an edit, and the store has
12
+ no sign one ever has. Build the collision guard these rules describe first. Before it,
13
+ every reader (blame, search, the guard) needs to tell a backfilled stub from a real
14
+ record, without deleting the stub or the ticket links backfill recovered.
15
+ - A hash that resolves in no repository never comes out of blame, so it cannot mislead
16
+ the guard; the records that can are false sentences on real commits, which no hash
17
+ check sees. Checking a hash resolves before recording is still worth having, and it
18
+ belongs to the skill: the tool runs no VCS and stores no repository identity.
19
+ - Log every stop and every ack the guard makes. The next decision about it should rest on
20
+ how often it fires and how often it changes an edit.
21
+
22
+ ## Showing records
23
+
24
+ - A record's value to a reader sits in a few sentences of its body: what was ruled out,
25
+ what would break, which constraint forced the shape. A view that repeats whole bodies
26
+ per line change buries them; seven decisions read as fifteen spans of JSON.
27
+ - Do not read the stub count as neglect at writing time. The stubs are backfill; the
28
+ records written at the time have bodies. What goes wrong at writing time is false
29
+ sentences and invented hashes, and a feature that makes accepting a draft easier
30
+ makes that worse.
31
+
32
+ ## Delivering records
33
+
34
+ - An agent does not ask. Nothing in the store shows an intent read before an edit,
35
+ although the skill and the owner's rules both say to blame first. A reading feature
36
+ that waits to be called is not used; the record has to arrive at the edit.
37
+ - The moment belongs to the skill (a hook on the agent's edit); the tool renders what
38
+ that moment shows. The tool stays free of any notion of when.
39
+ - Labelling sentences as "ruled out" or "constraint" by reading prose at read time is
40
+ inference, which the tool refuses. Structure a reader relies on is written at record
41
+ time.
42
+ - Say nothing where nothing is recorded. A "no reason recorded" line would appear on
43
+ most files of any older repository, and an agent that learns to skim a hook's output
44
+ skims its warnings too. The gap belongs in the on-demand view, not the push. A
45
+ backfilled stub counts as nothing recorded: it carries no reasoning, and stubs are
46
+ most lines of any older history.
47
+ - Scope a pushed warning to the lines the edit changes, and phrase it as the collision
48
+ it is ("this edit changes line 35, which mjtLNZa pins"). A briefing of everything in
49
+ the file put the one decision that mattered fourth of seven.
50
+ - A pre-edit hook already sees the new text, so a collision is caught before the edit
51
+ lands; before and after are one tool call apart, not two features.
52
+ - A warning claims only what a record says or what a run produced. The tool cannot
53
+ judge code ("interpolates unquoted"). It may state text facts about an edit ("removes
54
+ the text `stage_command` from this line").
55
+ - Say what the runs showed and stop: where the guard lives, whether its test failed or
56
+ only errored, and the text fact about the edit, in as few words as an agent will read.
57
+ - Trust evidence is only worth showing if it bears on whether the sentence is true. Age
58
+ and author do not; a test that bites, or a later dispute, do.
59
+ - Evidence is linked, not edited in: a test is a source with system `test`, so an old
60
+ record gains one by `attach` and stays unedited.
61
+
62
+ ## When an edit collides with a record
63
+
64
+ - A collision stops the edit. A warning that stops nothing is read past; a stop that
65
+ costs nothing to release teaches the agent to send every edit twice.
66
+ - Release it with something the agent must mean and a hook can see: an exact command
67
+ naming the kind of override (`within`, or `wrong` with a test). A repeated edit is a
68
+ reflex; a message that merely names the record opens the stop in passing; Claude
69
+ Code's Edit takes no reason argument.
70
+ - That command holds session state, so it belongs to the skill, not the tool.
71
+ - `within` is for an edit that must still change the pinned line while keeping what the
72
+ record protects; an agent that routes around the line does not collide again.
73
+ - Never write an agent's edit-time reason onto the record it collided with. It is typed
74
+ in a hurry to get past a stop, can misread the record, is tied to no commit, and
75
+ outlives a reverted edit.
76
+ - The reason for going against or around a record belongs in the intent of the change
77
+ that acts on it, linked to the old record as related. Blame already shows
78
+ `related_by_intents`, so the old record's next reader reaches it with no new link kind.
79
+ - Never make an agent record a `within` it has just said it does not mean; that writes a
80
+ false sentence on purpose.
81
+
82
+ ## Tests as evidence
83
+
84
+ - A test named in a record vouches for the unit it exercises, not for the line the
85
+ record is shown on. Measured on fun-ci: `mjtLNZa`'s test fails with the quoting in
86
+ `ProjectConfig#stage_command` undone and passes with stage_runner.rb line 35 rewritten
87
+ unquoted. Never push a named test's green run as clearance.
88
+ - A test pins a line only if reverting that commit's own hunk on the line turns it red.
89
+ Revert mechanically; a break the skill writes is a judgement about code, and two runs
90
+ can disagree.
91
+ - A reverted hunk that removes an added method makes the test error, not fail (measured
92
+ on e2faf98: NoMethodError). An error shows the test depends on the code, not that it
93
+ checks the behaviour; only a failure pins.
94
+ - A collision on a line no test pins is a missing test, and the collision is the moment
95
+ to write it: green on today's code, then red on the edit.
96
+ - Evidence that is a run, not a sentence, may reach an old record: a test written at a
97
+ collision is attached to the record once reverting that record's own hunk turns it
98
+ red. Otherwise every later agent is asked to write the same test again.
99
+ - Vet a record's test at its first collision, not at record time, and keep the verdict:
100
+ a revert of a past commit's hunk gives the same answer forever, and most records never
101
+ meet an edit.
102
+
103
+ ## Disputes
104
+
105
+ - A dispute (`wrong`) is accepted with a test that asserts the counter-claim and passes
106
+ on the new commit, and the commit must change or remove the record's own test with a
107
+ reason. Asked for such a test, an agent tends to disprove its own false dispute.
108
+ - Never treat the record's own test passing as proof the record is right.
109
+ - A dispute no test can settle stays unsettled in the new intent and out of the next
110
+ agent's warning: an agent reads "disputed, unsettled" as permission to act on it.
111
+ - Only the owner can settle one, and the list must reach the human alone. An agent shown
112
+ a stands-or-wrong prompt will answer it for the owner. A session start or a push is not
113
+ evidence the owner is present; this owner runs agents unattended.
114
+ - Two sessions of the same model are not independent witnesses; agreement between them
115
+ certifies a shared guess, not a fact.
@@ -6,6 +6,8 @@ module IntentRecord
6
6
  # checked before any is returned, so a payload with a bad entry late in the
7
7
  # list never reaches the database. Nothing here needs one.
8
8
  module CommitSpecs
9
+ ENTRY_KEYS = %w[commit message author ref].freeze
10
+
9
11
  module_function
10
12
 
11
13
  def from(input)
@@ -13,12 +15,14 @@ module IntentRecord
13
15
  end
14
16
 
15
17
  def entries(input)
18
+ InputValidator.known_keys!(input, %w[commits])
16
19
  InputValidator.array!(input, "commits")
17
20
  end
18
21
 
19
22
  def spec(entry)
20
23
  raise ValidationError, "commits entries must be objects" unless entry.is_a?(Hash)
21
24
 
25
+ InputValidator.known_keys!(entry, ENTRY_KEYS, within: "commits entries")
22
26
  { commit: InputValidator.required_string!(entry, "commit"),
23
27
  message: message(entry),
24
28
  author: InputValidator.optional_string!(entry, "author"),
@@ -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
@@ -0,0 +1,75 @@
1
+ require_relative "../input_validator"
2
+
3
+ module IntentRecord
4
+ module Blame
5
+ # Reads a blame payload into the spans a reader is answered with.
6
+ #
7
+ # A blame tool answers per line, and a reader asked about a range. Answering
8
+ # per line would bury the useful part in repetition, so neighbouring lines
9
+ # from one change become one span. Neighbouring, not merely equal: the same
10
+ # change either side of someone else's edit is two places in the file, and
11
+ # one span across them would claim a line it does not own.
12
+ #
13
+ # Nothing here reaches the database, so a malformed payload is refused before
14
+ # the store is asked anything.
15
+ class Spans
16
+ Span = Struct.new(:external_id, :from, :to)
17
+
18
+ def initialize(lines)
19
+ @lines = lines
20
+ end
21
+
22
+ def call
23
+ collapse(sorted)
24
+ end
25
+
26
+ private
27
+
28
+ def sorted
29
+ raise ValidationError, "At least one line is required" unless @lines.is_a?(Array) && @lines.any?
30
+
31
+ entries = @lines.map { |line| entry(line) }.sort_by(&:first)
32
+ reject_repeats(entries)
33
+ entries
34
+ end
35
+
36
+ # Sorted, so a repeat is adjacent. The same line attributed to two changes
37
+ # is a contradiction in the payload, and answering it would mean choosing
38
+ # one of them silently.
39
+ def reject_repeats(entries)
40
+ entries.each_cons(2) do |(earlier, _), (later, _)|
41
+ raise ValidationError, "Line #{earlier} is given more than once" if earlier == later
42
+ end
43
+ end
44
+
45
+ def entry(line)
46
+ raise ValidationError, "Each line needs a line and an external_id" unless line.is_a?(Hash)
47
+
48
+ InputValidator.known_keys!(line, %w[line external_id], within: "lines entries")
49
+ [line_number(line["line"]), InputValidator.required_string!(line, "external_id")]
50
+ end
51
+
52
+ # A string is read in base ten: Integer() on its own reads "010" as
53
+ # octal and answers about line 8, a wrong answer given confidently. A
54
+ # fraction is refused rather than truncated for the same reason.
55
+ def line_number(raw)
56
+ number = raw.is_a?(Integer) ? raw : Integer(raw.to_s, 10, exception: false)
57
+ raise ValidationError, "line must be a positive integer, got #{raw.inspect}" if number.nil? || number < 1
58
+
59
+ number
60
+ end
61
+
62
+ # Walks in file order, extending the span in hand while the next line both
63
+ # follows the last one and names the same change.
64
+ def collapse(entries)
65
+ entries.each_with_object([]) do |(number, id), spans|
66
+ extends?(spans.last, number, id) ? spans.last.to = number : spans << Span.new(id, number, number)
67
+ end
68
+ end
69
+
70
+ def extends?(span, number, id)
71
+ !span.nil? && span.external_id == id && span.to == number - 1
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,23 @@
1
+ require_relative "../blame/porcelain"
2
+ require_relative "stdin_json"
3
+
4
+ module IntentRecord
5
+ class CLI
6
+ # What `blame` reads from stdin. The JSON shape is the contract; a format
7
+ # names a reader that produces it from what some blame tool already prints.
8
+ module BlameInput
9
+ FORMATS = { "git-porcelain" => Blame::Porcelain }.freeze
10
+
11
+ module_function
12
+
13
+ def read(format, stdin)
14
+ return StdinJson.read(stdin) if format.nil?
15
+
16
+ reader = FORMATS[format]
17
+ raise ValidationError, "Unknown --format #{format}. Known formats: #{FORMATS.keys.join(", ")}" if reader.nil?
18
+
19
+ { "lines" => reader.lines(stdin.read) }
20
+ end
21
+ end
22
+ end
23
+ end
@@ -11,6 +11,8 @@ require_relative "../commands/recent"
11
11
  require_relative "../commands/attach"
12
12
  require_relative "../commands/systems"
13
13
  require_relative "../commands/backfill"
14
+ require_relative "../commands/blame"
15
+ require_relative "blame_input"
14
16
 
15
17
  module IntentRecord
16
18
  class CLI
@@ -122,6 +124,11 @@ module IntentRecord
122
124
  finish! { command.call(stdin_json) }
123
125
  end
124
126
 
127
+ def run_blame
128
+ format = @parser.take_flag("--format")
129
+ finish! { Commands::Blame.new.call(BlameInput.read(format, @streams.stdin)) }
130
+ end
131
+
125
132
  def run_systems
126
133
  finish! { Commands::Systems.new.call }
127
134
  end
@@ -8,10 +8,11 @@ module IntentRecord
8
8
  attach <intent_id> Link more commits / stakeholder refs / related intents (JSON via stdin)
9
9
  show <intent_id> Full intent record
10
10
  lookup <commit> [--vcs name] Intents recorded against a commit (full hash or unique prefix)
11
- search <terms...> [--match all] Substring search over summary and body
11
+ search <terms...> [--match all] Search over summary, body and ticket links, best match first
12
12
  by-source <uri> [--contains] Intents linked to a stakeholder uri (Jira ticket, Confluence page, ...)
13
13
  recent [--limit N] Newest intents first
14
14
  systems Known vcs and stakeholder system names
15
+ blame [--format git-porcelain] Intents for the commits a blame output names (JSON via stdin)
15
16
  backfill [options] Recover intents from commit messages (JSON via stdin, see below)
16
17
  serve [--port N] Start the local web GUI
17
18
 
@@ -28,6 +29,17 @@ module IntentRecord
28
29
  --order <which-first> newest-first (default, as git log prints) or oldest-first
29
30
  --dry-run Report what it would write, write nothing
30
31
 
32
+ Search terms:
33
+ Ranked best first. A plain word also matches its other forms, so `retry`
34
+ finds "retried". A term carrying punctuation is matched literally, so
35
+ `100%` does not match "100 percent". A term may name one field:
36
+ summary:retry, body:retry, uri:ACME-42, title:flaky. The name is read in
37
+ any case. Only those four names count, so a ticket url is searched as itself.
38
+
39
+ Input shape for blame (vcs defaults to git):
40
+ {"vcs": "git", "lines": [{"line": 40, "external_id": "<hash>"}]}
41
+ With --format git-porcelain, `git blame --porcelain` output goes in as-is.
42
+
31
43
  Input shape for backfill:
32
44
  {"commits": [{"commit": "<hash>", "message": "<commit message>",
33
45
  "author": "...", "ref": "<branch name>"}]}
@@ -37,6 +49,9 @@ module IntentRecord
37
49
  "commits": ["<git hash>"], "asset_versions": [{"vcs": "perforce", "external_id": "123"}],
38
50
  "stakeholder_references": [{"system": "jira", "uri": "https://...", "title": "..."}],
39
51
  "related_intent_ids": ["<intent_id>"]}
52
+
53
+ A key these input shapes do not show is refused, inside entries too.
54
+ The output's related_intents is set on input by related_intent_ids.
40
55
  USAGE
41
56
  end
42
57
  end
@@ -3,12 +3,14 @@ require_relative "../models/intent_record"
3
3
  require_relative "../linkers/asset_version_linker"
4
4
  require_relative "../linkers/stakeholder_linker"
5
5
  require_relative "../linkers/intent_linker"
6
+ require_relative "../linkers/link_keys"
7
+ require_relative "../input_validator"
6
8
 
7
9
  module IntentRecord
8
10
  module Commands
9
11
  # Links more commits, stakeholder sources or related intents to an existing intent record.
10
12
  class Attach
11
- LINK_KEYS = %w[commits asset_versions stakeholder_references related_intent_ids].freeze
13
+ LINK_KEYS = Linkers::LINK_KEYS
12
14
 
13
15
  def initialize(intent_id:)
14
16
  @intent_id = intent_id
@@ -17,6 +19,8 @@ module IntentRecord
17
19
  def call(input)
18
20
  record = Models::IntentRecord.find_by(global_id: @intent_id)
19
21
  raise NotFoundError, "Intent record not found: #{@intent_id}" unless record
22
+
23
+ InputValidator.known_keys!(input, LINK_KEYS, renamed: Linkers::OUTPUT_NAMES)
20
24
  raise ValidationError, "Nothing to attach: provide one of #{LINK_KEYS.join(", ")}" if nothing_to_attach?(input)
21
25
 
22
26
  ActiveRecord::Base.transaction { link_all(record, input) }