Skip to content

feat(reanchor): bounded region search for single-line anchors and line-local suggestion merge - #309

Merged
nownabe merged 1 commit into
mainfrom
feat/269-region-search
Sep 20, 2026
Merged

nownabe merged 1 commit into
mainfrom
feat/269-region-search

Conversation

@nownabe

@nownabe nownabe commented Sep 20, 2026

Copy link
Copy Markdown
Owner

Why

In prose Markdown a source "line" is a whole paragraph, so the byte-identical LCS line map that re-anchoring relies on drops every comment on a paragraph the moment any sentence in it changes (ADR 0004 §3: "no fuzzy quote search" → outdated). The same granularity makes overlapping suggestions unapplyable: once one suggestion on a paragraph is accepted, the line no longer matches any other suggestion's quote, so every further accept on that paragraph fails with "Can't apply this suggestion".

This undermines the product's core promise — select any text range in prose and comment on it — because the anchor is dropped rather than tracked.

What

Re-anchoring (lib/pr/reanchor.ts). When the line map cannot resolve a single-line anchor, reanchor now runs a bounded region search (new exported locateLine):

  • the search space is only the current-source lines between the nearest line-mapped neighbours — the stretch the old line's content must have gone to — capped at REGION_CAP = 50 candidates around the expected position;
  • a candidate wins only if it is unique: the single line containing the quote, else the single best line by Levenshtein similarity to the old line with ratio ≥ SIMILARITY_MIN = 0.5. Ties, duplicates and an empty region all yield outdated;
  • sc/ec are carried across a character diff of the old line against the located line (diff_xIndex). The result is mapped when the quote verifies at the mapped columns, shifted when it does not — so a located-but-changed line is always visible to the user, never silently claimed correct.

"Never guess" is preserved: the search is never whole-file, every choice must be unambiguous, and a non-verifying quote is badged.

Accepting a suggestion (lib/suggest.ts). applyAcceptedSuggestion keeps its exact-quote fast path unchanged and gains a fallback for the case it refuses today: the target line is re-located directly in the author's edited source from the anchor-sha revision (new anchorSource argument) with the same region search, then the suggestion is applied as a line-local three-way merge — patch_make(quote → replacement) applied to that one line. Every hunk must apply or the accept is refused; nothing outside that line is ever touched, and the result is staged as tracked changes before commit.

Gate (entrypoints/review/uiHelpers.ts). canAcceptSuggestion now accepts shifted too; outdated is the only refusal. The merge's clean-apply requirement is the real gate, and it surfaces the existing error message when it refuses.

Wiring (entrypoints/review/App.tsx). acceptSuggestion resolves anchorSource from RemoteState.fileContents at (meta.sha, meta.path), falling back to baseSource when the anchor is at head, and null otherwise (fallback off).

ADR 0004 is amended accordingly (Context, §3 diagram + notes, §4 table, §5 edge cases, new §7 "Applying a suggestion", Deferred list).

Phase 1 scope

In scope: single-line anchors, single-line suggestion targets.

Deferred (follow-ups to file):

  • multi-line anchors with an unmapped endpoint (run the region search per endpoint and verify the whole quote) — still outdated;
  • editor overlay / merge preview for shifted suggestions (buildSuggestionMarks still skips non-identical targets);
  • similarity-ranked disambiguation when the quote occurs in several candidates and similarity ties — still outdated;
  • re-anchoring drafts and pending suggestion hunks through the same region search at submit time ([High] Drafts are submitted with creation-sha line numbers against the current head commit #265 follow-up);
  • tuning SIMILARITY_MIN / REGION_CAP from real usage.

No data-model change (ADR 0002 untouched), no new statuses, no new dependency (diff-match-patch was already in use), no new modules.

Red-test log (TDD)

Every test below was written and run before its implementation.

tests/pr/reanchor.test.ts — describe("region search (issue #269)"), 5 failures, all Received: { "status": "outdated" }:

Test Expected
a sentence-level comment survives an edit elsewhere in the same paragraph { status: "mapped", range: { sl: 3, sc: 10, el: 3, ec: 18 } }
an edit before the quote moves the columns → mapped at the new columns { status: "mapped", range: { sl: 3, sc: 16, el: 3, ec: 24 } }
the quote itself was edited → shifted at the char-diff-mapped columns { status: "shifted", range: { sl: 3, sc: 10, el: 3, ec: 18 } }
a line-based suggestion anchor whose line was edited → shifted, columns stay 1/1 { status: "shifted", range: { sl: 2, sc: 1, el: 2, ec: 1 } }
region cap > a candidate inside the capped window is found { status: "mapped", range: { sl: 11, sc: 1, el: 11, ec: 16 } }

Then, on adding the direct locateLine test:

SyntaxError: Export named 'locateLine' not found in module '.../lib/pr/reanchor.ts'.

tests/suggest.test.ts — describe("line-local merge (issue #269)"):

(fail) two suggestions on one paragraph both apply in sequence
  Expected: "h\nOne one. TWO two. THREE three.\nt\n"
  Received: null
(fail) a fallback deletion removes the line's newline too (#191 parity)
  Expected: "h\nt\n"
  Received: null

tests/uiHelpers.test.ts:

(fail) canAcceptSuggestion > a shifted position is acceptable — the merge is the gate
  Expected: true
  Received: false

Guard tests written alongside and confirmed green both before and after the implementation (they pin the "never guess" rules rather than drive them): paragraph rewritten beyond the similarity floor → outdated; two candidates tie on similarity → outdated; multi-line anchor with an unmapped endpoint stays outdated; a candidate beyond the cap is never examined; a quote no longer anywhere in the region is refused; the merge refuses when the replacement's hunks do not apply cleanly; the fallback is skipped without an anchorSource.

Two existing tests in tests/pr/reanchor.test.ts encode behaviour this change could have altered and were re-verified green rather than assumed: "the anchored line was deleted → outdated" (empty region, lo > hi) and "never returns shifted when no LCS match found" (similarity of b against d/e/f is 0).

Checks

bun run test 669 pass / 0 fail across 61 files · check:lint · check:format · typecheck · build — all green.

Manual verification

  1. As reviewer, comment on one sentence of a paragraph; as author, edit a different sentence of that paragraph and commit; reload as reviewer: the comment highlight sits on the original sentence with no badge (mapped).
  2. Edit the commented sentence itself and commit: the comment shows the "position shifted" badge and the highlight covers the edited words.
  3. As author, with two submitted suggestions on the same paragraph, accept both: both changes appear as tracked changes; Submit commits a single line containing both.
  4. Rewrite the paragraph entirely and commit: comments on it show "position not found" and Accept is refused with the existing message.

Note: until #267 lands, currentSource is "" for files with no head-anchored comment, so the region search does not run in the app for old-sha comments on those files. The unit tests exercise it directly.

Closes #269

…e-local suggestion merge

In prose Markdown a source line is a whole paragraph, so a byte-identical LCS
line map dropped every comment on a paragraph as soon as any sentence in it
changed, and a second suggestion on the same paragraph could never be applied.
A single-line anchor is now looked for in the diff region between its nearest
mapped neighbours (bounded, uniqueness-gated, visibly shifted when the quote
no longer verifies), and an accept that misses its exact quote falls back to a
line-local three-way merge that must apply cleanly.
@nownabe nownabe self-assigned this Sep 20, 2026
@nownabe
nownabe merged commit 0f735da into main Sep 20, 2026
10 checks passed
@nownabe
nownabe deleted the feat/269-region-search branch September 20, 2026 05:58
nownabe added a commit that referenced this pull request Sep 20, 2026
…346)

## Why

The issue's first acceptance criterion already holds: since #303 and
#309 the
Planner routes every draft through the same `reanchor` entry point as
display.
What was missing is the **policy for `shifted`**, and this PR decides
it:
**refuse**.

A `shifted` draft is one whose line was located but whose quoted text
changed
upstream. Posting it would attach the reviewer's words — and, for a
suggestion,
a replacement block GitHub can apply — to text they never saw, and the
posted
copy would carry a `quote` that is no longer the text at its range,
which is the
definition ADR 0002 §3 gives it (and what #279's digest restoration
relies on).
The reviewer already sees the same "position shifted" badge on the draft
before
Submit, so what is refused is exactly what was flagged; the parked draft
keeps
its `lastError` in the sidebar (#268) and is re-created on the current
text.

This reverses the lean recorded in the #269 design ("post at the located
range"), which predates the `quote` definition.

## What

- **lib/pr/planner.ts** — `toHeadCoordinates` returns `{comment} |
{error}`
instead of `Comment | null`, so the caller can tell the two refusals
apart.
A `shifted` position yields the new `SHIFTED_ANCHOR` error; `outdated`
keeps
its own message. `mapped` — including a range recovered by the region
search —
  still posts at the mapped range.
- No state-machine change: `reject-comment` already parks the comment as
  `draft + lastError`.
- **docs/adr/0003-operations-and-execution.md §5** — the policy
paragraph.
- **docs/adr/0004-reanchoring.md §4** — the `shifted` row notes the
submit-time
  refusal.

## Red-test evidence

`tests/pr/planner.test.ts` → "a draft whose quoted text changed upstream
(shifted) is refused": expected a `reject-comment`, received

```
{ kind: "post-review-batch", commitId: "current-head",
  comments: [{ anchor: { sha: "current-head",
                         range: {sl: 2, sc: 1, el: 2, ec: 12},
                         quote: "hello world" }, ... }] }
```

— the draft was posted at the located range carrying a quote that no
longer
matches the text there.

Two guards in the same block passed before and after: a draft whose
paragraph
changed *elsewhere* still posts at the located columns (`{sl:2, sc:6,
el:2,
ec:10}`, quote `"Two."`), and a draft whose line is gone is still
refused with
the *outdated* message, not the shifted one.

## Checks

`bun run test` (729 pass, 0 fail), `check:lint`, `check:format`,
`typecheck`,
`build` all pass.

Closes #313
nownabe added a commit that referenced this pull request Sep 20, 2026
…search (#347)

## Why

PR #309 (#269 Phase 1) gave *single-line* anchors a bounded region
search.
A multi-line anchor with an unmapped endpoint still went straight to
`outdated`,
so a comment spanning two prose paragraphs — or a multi-line suggestion
— lost
its position as soon as either paragraph was edited.

## What

- **lib/pr/reanchor.ts** — new exported `locateSpan(oldLines, newLines,
lineMap, range, quote)`: a mapped endpoint keeps its mapping; an
unmapped one
goes through the existing `locateLine` using as its Stage-A needle the
part of
`quote` that lies on that endpoint's line (`quote.split("\n")[0]` for
the
start, the last element for the end — exact under ADR 0002 §3's
definition of
`quote`). Null unless both endpoints resolve **and** the located end
lies
  strictly after the located start.
- **lib/pr/reanchor.ts** — `reanchorByRegion` loses its `sl !== el`
bail-out.
Multi-line columns are carried through the same `diff_xIndex` char diff
the
single-line path uses, `ec` clamped to the located end line's length;
the
range is then verified with the one rule, `extractTextAtRange ===
quote`, so
a moved span reports `mapped` and an edited quote reports `shifted` at
the
  located span. The single-line branch is unchanged.
- **lib/suggest.ts** — `applyAcceptedSuggestion`'s fallback uses the
same
`locateSpan` instead of refusing `sl !== el`; `mergeLine`/`replaceLine`
become
`mergeSpan`/`replaceLines` over the located span. The Phase-1
`simplify:`
  comment is gone.
- **docs/adr/0004-reanchoring.md** — §3 note and mermaid, §5 (the two
partial-
span bullets collapse into one per-endpoint rule), §7 (span-local
merge), and
  the Deferred entry is removed.

**Tie handling (the issue's open question): unchanged — a tie is
`outdated`,
now stated explicitly in ADR 0004 §3.** The expected position centres
the search
window but never ranks candidates; breaking a similarity tie by
proximity would
be a guess about which of two equally plausible lines the reviewer
meant, which
is the exact failure ADR 0004 removed.

## Red-test evidence

`tests/pr/reanchor.test.ts`, `describe("multi-line region search (issue
#311)")`:

- `locateSpan` direct test: `SyntaxError: Export named 'locateSpan' not
found in
  module lib/pr/reanchor.ts`.
- "a two-paragraph comment survives an edit elsewhere in the second
paragraph":
expected `{status: "mapped", range: {sl:3, sc:10, el:5, ec:13}}`,
received
  `{status: "outdated"}`.
- "the quoted text of a multi-line anchor was edited → shifted at the
located
span": expected `{status: "shifted", range: {sl:3, sc:10, el:5,
ec:13}}`,
  received `{status: "outdated"}`.

`tests/suggest.test.ts`, `describe("span-local merge for multi-line
targets
(issue #311)")`:

- "a two-line suggestion applies after an earlier accept changed its
first
  line": expected `"h\nALPHA ONE here\nbeta TWO\nt\n"`, received `null`.
- "a multi-line deletion via the fallback removes every span line and
its
  newline": expected `"h\nt\n"`, received `null`.

Three guards in the new block passed before and after and pin the rules
during
the change: an end line deleted with nothing in its place, endpoints
that cross
over, and a similarity tie for one endpoint all stay `outdated`. The
existing
Phase-1 guard ("a multi-line anchor with an unmapped endpoint stays
outdated")
keeps its assertion but is renamed — it now holds because a
one-character line
can neither contain the quote part nor reach the similarity floor, not
because
multi-line anchors are refused outright.

## Checks

`bun run test` (737 pass, 0 fail), `check:lint`, `check:format`,
`typecheck`,
`build` all pass.

Closes #311
nownabe added a commit that referenced this pull request Sep 20, 2026
…#354)

## Why

After #309/#311 a `shifted` suggestion — one whose target text drifted
since it was written — can be accepted through a span-local three-way
merge, and `canAcceptSuggestion` offers the Accept button for it. But
`buildSuggestionMarks` still skipped every non-verified target (the #176
guard), so the author saw no inline preview: the only way to learn what
the merge would do was to click Accept and inspect the tracked changes
afterwards.

This wires the preview to the same merge the accept runs, so the merge
path is reviewable before it is taken.

## What

- **`lib/suggest.ts`** — the private span-local merge is now exported as
`mergeSuggestionSpan(quote, replacement, spanText)`. Same function, same
algorithm, one call site added; `applyAcceptedSuggestion` keeps using
it.
- **`buildSuggestionMarks` (`entrypoints/review/reviewItems.ts`)** — a
`shifted` target now emits a mark whose span is the *located span* (via
the existing `headRangeToEditedOffsets`, so the strikethrough covers
exactly what Accept would replace, never `quote.length` characters of
drifted text — the original #176 hazard) and whose `replacement` is the
merged text, flagged `shifted: true`. When the merge refuses (`null`),
no mark is emitted — the overlay never promises an Accept that cannot
happen. `current` / `mapped` targets are untouched.
- **`entrypoints/review/suggestionView.ts`** — a `shifted` mark renders
the sidebar's existing "position shifted" badge (`badge
badge--reanchored`, label reused from `STATUS_LABEL`) as a widget right
after the replacement. No new CSS, no new tokens.
- **`docs/adr/0004-reanchoring.md`** — the overlay item moves out of
Deferred into §7 with the preview rule ("a span whose merge would be
refused gets no overlay at all"), plus the usual amendment line.

## Red-test evidence

`bun run test tests/suggest.test.ts tests/reviewItems.test.ts
tests/suggestionView.test.ts` before the implementation — 3 fail, 1
error:

```
tests/suggest.test.ts:
# Unhandled error between tests
SyntaxError: Export named 'mergeSuggestionSpan' not found in module '.../lib/suggest.ts'.

(fail) buildSuggestionMarks > merge preview for shifted targets (issue #312) > previews the merged span
error: expect(received).toHaveLength(expected)
Expected length: 1
Received length: 0

(fail) suggestionMarksField > a shifted suggestion adds the position-shifted badge
error: expect(received).toEqual(expected)
@@ -2,3 +2,3 @@
    "dr-sugg-new",
-   "badge badge--reanchored",
  ]

 79 pass
 3 fail
 1 error
```

The guard tests written alongside them — a shifted target whose merge is
refused draws nothing, a `mapped` target keeps its plain quote-sized
mark, an unshifted mark carries no badge — passed before and after,
which is what makes them guards.

After: 825 pass / 0 fail across 64 files (818 before).

## Manual check

1. `bun run build`, reload the unpacked extension, open a PR where a
reviewer's submitted Suggestion targets a line the author has since
edited (enough to make it `shifted`, but still recognisably the same
line).
2. As the author, look at that line in the editor **before** clicking
Accept: the located span is struck through, the merged result is shown
inline next to it, and a "position shifted" badge sits after it.
3. Click Accept — the staged tracked change matches what the preview
showed.
4. Rewrite the target line beyond recognition so the merge would be
refused: the overlay disappears entirely (and Accept still refuses),
rather than showing a preview that could not be applied.

## Checks

`bun run test` (825 pass), `check:lint`, `check:format`, `typecheck`,
`build` — all green.

Closes #312
nownabe pushed a commit that referenced this pull request Sep 20, 2026
🤖 I have created a release *beep* *boop*
---


##
[0.4.0](bark-v0.3.0...bark-v0.4.0)
(2026-09-20)


### Features

* **pr:** accept .markdown and .mdx as Markdown
([#322](#322))
([e22ee68](e22ee68)),
closes [#293](#293)
* **pr:** commit fork pull requests to the fork's repository
([#342](#342))
([4e2adef](4e2adef)),
closes [#273](#273)
* **pr:** create a top-level draft Comment's Thread with it
([#323](#323))
([6e192f3](6e192f3)),
closes [#272](#272)
* **pr:** resolve out-of-diff threads via the root comment fence
([#310](#310))
([7e0ecb9](7e0ecb9)),
closes [#270](#270)
* **reanchor:** bounded region search for single-line anchors and
line-local suggestion merge
([#309](#309))
([0f735da](0f735da)),
closes [#269](#269)
* **reanchor:** locate multi-line anchors per endpoint in the region
search ([#347](#347))
([f4fd457](f4fd457)),
closes [#311](#311)
* **review:** preview the merge for shifted suggestions in the editor
([#354](#354))
([f822f41](f822f41)),
closes [#312](#312)


### Bug Fixes

* **anchor:** define anchor.quote as the source text at anchor.range
([#327](#327))
([11a935d](11a935d)),
closes [#276](#276)
* **background:** focus an existing review tab instead of opening a
second one ([#325](#325))
([58efa63](58efa63)),
closes [#277](#277)
* **pr:** compose the quote and permalink for every out-of-diff post
([#351](#351))
([f85b99b](f85b99b)),
closes [#282](#282)
* **pr:** count patch lines starting with ++ or -- in parseRightRanges
([#314](#314))
([9dfbd46](9dfbd46)),
closes [#284](#284)
* **pr:** keep the rel=next link in the ETag cache so 304 pages still
paginate ([#318](#318))
([6472de2](6472de2)),
closes [#286](#286)
* **pr:** offer Resolve only when GitHub would accept it
([#335](#335))
([b05fdcc](b05fdcc)),
closes [#274](#274)
* **pr:** park a failed resolve toggle in synced, not draft
([#320](#320))
([56e815b](56e815b)),
closes [#275](#275)
* **pr:** post drafts in the current head's coordinates
([#303](#303))
([28ef345](28ef345))
* **pr:** recover comments stuck in syncing instead of re-posting them
([#305](#305))
([3548086](3548086))
* **pr:** refuse commits to a merged or closed PR
([#330](#330))
([2a239ff](2a239ff)),
closes [#288](#288)
* **pr:** refuse to submit a draft whose quoted text changed upstream
([#346](#346))
([d4118a4](d4118a4)),
closes [#313](#313)
* **pr:** route replies on the parent's GitHub object kind
([#326](#326))
([1df6462](1df6462)),
closes [#285](#285)
* **pr:** serialise refresh and execution under one Repository lock
([#336](#336))
([1864488](1864488)),
closes [#281](#281)
* **pr:** sweep entities left syncing at the end of a submit
([#331](#331))
([108caa9](108caa9)),
closes [#271](#271)
* **release:** pin publish-browser-extension to ^4.0.5
([#263](#263))
([b77104f](b77104f))
* **review:** derive a suggestion draft's cid from the hunk it
materialises ([#337](#337))
([963339d](963339d)),
closes [#308](#308)
* **review:** end a whole-line selection on the line it actually covers
([#319](#319))
([3364d18](3364d18)),
closes [#291](#291)
* **review:** map comment positions between head and edited coordinates
([#348](#348))
([9465718](9465718)),
closes [#283](#283)
* **review:** reject a suggestion by resolving its thread on GitHub
([#340](#340))
([d088a8d](d088a8d)),
closes [#287](#287)
* **review:** resolve accepted-suggestion threads only after the commit
lands ([#341](#341))
([770f901](770f901)),
closes [#278](#278)
* **review:** surface failed comment posts and keep the reviewer's edits
([#307](#307))
([48cb675](48cb675))
* **review:** validate the PR number from the review URL
([#321](#321))
([457a942](457a942)),
closes [#295](#295)
* **storage:** bound chrome.storage.local growth and stop quota errors
losing drafts ([#332](#332))
([1f96120](1f96120)),
closes [#289](#289)
* **suggest:** consume a longer closing fence instead of leaking a
backtick ([#316](#316))
([d2e0683](d2e0683)),
closes [#290](#290)


### Performance Improvements

* **reanchor:** replace the LCS table with a memoised line-level Myers
diff ([#344](#344))
([8caebdd](8caebdd)),
closes [#280](#280)

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: release-please-nownabe-bark[bot] <295690643+release-please-nownabe-bark[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[High] Line-granular re-anchoring makes prose paragraphs fragile; overlapping suggestions cannot both be accepted

1 participant