Skip to content

Stop six ways of losing or corrupting text - #23

Merged
ckelsoe merged 2 commits into
mainfrom
fix/data-integrity
Aug 4, 2026
Merged

ckelsoe merged 2 commits into
mainfrom
fix/data-integrity

Conversation

@ckelsoe

@ckelsoe ckelsoe commented Aug 4, 2026

Copy link
Copy Markdown
Owner

Implements dev-docs/annoteca/pr-a-data-integrity-spec.md (private workspace). Every item was reproduced by execution in the 2026-08-04 project review rather than found by reading the code.

What changed

# Fix File
1 Import masks marker spans, fenced blocks (incl. blockquoted), and inline code imports.ts
2 Composer edit re-resolves the marker and stops writing through a stale range composer.ts
3 applySplices refuses stale offsets (vault.process); per-path write queue comment-service.ts
4 Trailing-line walk: first-met-wins, and a duplicate ends the walk without absorbing parser.ts
5 serialize sanitizes author tokens at all four emission sites parser.ts
6 Anchors round-trip at any length; both confirm-modal promises settle on every exit parser.ts, main.ts, confirm-modal.ts
7 findMalformedMarkers reports unclosed-opener and possible-merge parser.ts
8 Seeded 5,000-iteration round-trip fuzz test, red on main __tests__/parser-roundtrip-fuzz.test.ts

Parsing behaviour is deliberately unchanged in item 7. Whether an unclosed opener should refuse to merge is a format question with its own irreducible ambiguity, so the current merge behaviour is pinned by test rather than silently altered.

Verification

  • npx tsc --noEmit, npm run lint, npm run build: green.
  • npx jest: 413 tests, 22 suites, green. 41 of them are new.
  • 21 mutation checks, one per fix, each applied alone in a scratch copy: all 21 turned their named test red. Two early misses were my own fault and are worth recording: jest -t is a regex and [id=...] is a character class, so two mutations were never actually running; and the first anchor test was weak (it serialized first, so serialize's new cap meant the parser's pattern was never exercised). Both fixed, then re-run.
  • Codex (gpt-5.6-sol) reviewed the diff twice. Round 1 found a real defect introduced here: a refused write still returned written, so appendReply returned true and the popover would clear a reply the user had just typed while nothing reached the file. Round 2 found sanitizeAuthorToken throwing on a non-string authorTag from data.json. Both fixed and pinned by test and by mutation.

No CDP or live verification was run for this PR; it is all unit-level. Nothing here is claimed as hand-verified.

Deviations from the spec, all deliberate

  1. confirm-modal.ts is outside the declared footprint. The spec asks for Cancel to settle the promise but budgets no file for it. Charles chose adding an onCancel hook over the alternatives. It fires from onClose, not the Cancel button, because Escape and a background click are the common dismissals and neither touches the button.
  2. serialize strips ] from the anchor. Not in the spec text, but it is item 5's own principle (serialize must not emit what it cannot re-parse) at the same funnel. Unreachable from the UI today, since buildAnchorFromSelection already strips it. One line; trivially revertable.
  3. The duplicate-break rule covers six singletons, not four. The spec names id/date/author/anchor; addressed and resolution were already first-met-wins and had the same silent-deletion bug, so they get the same treatment.
  4. ANCHOR_LINE_RE keeps \r out of its character class. The spec writes [^\]\n]*; a greedy group would then swallow a trailing \r on CRLF files and store it in the anchor. The load-bearing parts (unbounded, *) are as specified.
  5. .github/copilot-instructions.md updated. Required by the commit gate's prose-drift rule: it still described the vault write path as vault.modify and gave 80 characters as the only anchor limit. Two new hard rules added while there, both footguns this PR introduces: honour applySplices's return value, and delegate to the *Unqueued verbs or deadlock.

Observations, not fixed here

  • The exported AI skill does not document the author token grammar. sanitizeAuthorToken covers the plugin's own writes, but an assistant hand-writing [author=Bob Smith] still produces a line the parser drops. Fixing it means a SKILL_SCHEMA_VERSION bump, which is its own decision.
  • CommentService.resolvedAuthor() calls .trim() on the raw setting and still throws on a non-string authorTag. Pre-existing, and PR C's settings-normalization item is the right place for it.
  • A code span crossing a newline is not masked by the importer. Legal CommonMark, rare in practice; the per-line matcher is what the spec specifies.
  • The stale-write refusal reuses the "moved or been deleted" notice. Accurate about the remedy, slightly off about the cause when the change was elsewhere in the file. Better than inventing a second message for the same user action.

Seven fixes to paths that lose or corrupt a user's prose, plus the seeded
round-trip fuzz test that adjudicates three of them. Every item was reproduced
by execution in the 2026-08-04 project review, not found by reading the code;
the spec is dev-docs/annoteca/pr-a-data-integrity-spec.md.

Bulk import now masks the regions it must not rewrite: existing marker spans,
fenced code blocks (including inside a block quote), and inline code spans.
Only the HTML pass had a skip predicate and "Import all" runs the native pass
first, so a `%%...%%` inside a marker's body was converted where it stood,
nesting a marker in a marker: the outer one ended at the inner `-->` and its
remainder became visible prose. A predicate could not have covered it, because
it only ever saw the matched text and the question is about position.

The composer's edit path re-resolves the marker from the current document at
submit. It went through neither CommentService nor its freshness work, and both
of its inputs were captured when the form opened: the snapshot (which omitted
`addressed` entirely, so Reject silently degraded to Revise and the only copy of
the pre-edit prose left the file) and the editor range (which drifted whenever
the document changed above the marker, and the default composer is the panel,
where the editor stays live). A marker it can no longer identify now refuses and
leaves the form open, because the body field holds text the user just typed.

applySplices takes the exact content its caller computed offsets against and
refuses when the file no longer matches, via `vault.process` so the comparison
and the write share a lock. It used to read the file a SECOND time and apply the
old offsets to whatever came back. Both failures were executed: a sync landing in
that window spliced a `[resolved ...]` line into the middle of a word, and two
overlapping verbs lost one write while both reported success. A per-path write
queue closes the second one properly by putting the READ inside the critical
section; public verbs enqueue, and verbs that delegate call the `*Unqueued` form,
because queueing at both layers would deadlock.

The trailing-line walk prefers the marker's own line over a body line that mimics
one, and stops rather than absorbing when it meets a duplicate. serialize emits
the body raw and the walk runs bottom-up, so a comment whose text ended
`[id=deadbeef]` came back carrying that id, orphaning its star, its draft and
every later lookup, and the quoted line was deleted from the body as well. The
case that stays ambiguous (a mimic of a kind the marker does not already carry)
is irreducible and is pinned by name rather than papered over.

serialize sanitizes author tokens at all four emission sites. The tag reaches it
from data.json, which is untyped at runtime, so `Charles Kelsoe` produced a line
the parser could not read and the whole trailing block above it collapsed into
the body on the next write, and a tag holding `-->` ended the marker early. The
sanitizer is total against a non-string value: throwing would take the write with
it, which is worse than the malformed line it prevents. Validating the tag at the
settings boundary is PR C; this has to hold either way.

Anchors round-trip at any length. The pattern's own comment promised
forward-compatible parsing and a serialize-time cap, and neither existed: a value
over 200 characters fell through to the unknown-line shape, was absorbed, and
vanished. Now unbounded on read, capped on write, and `]` is stripped there for
the same reason `-->` is escaped.

findMalformedMarkers reports an opener with no `-->` of its own, and the marker
that has probably swallowed a second one. Parsing is deliberately unchanged and
the current merge behaviour is pinned by test: whether an unclosed opener should
refuse to merge is a format question with its own ambiguity. The scan is not
anchored to a line start, because markers lead the text they concern and most sit
mid-line; a false positive costs a line in a report, a false negative costs a
paragraph that has silently vanished.

Both confirmation-modal promises settle on every exit. A rejecting service call
left them pending forever, and so did backing out; cancellation fires from
onClose rather than the Cancel button, because Escape and a background click are
the common dismissals and neither touches the button.

__tests__/parser-roundtrip-fuzz.test.ts is 5,000 seeded iterations over
adversarial pools, red on main and green here. Its assertions are
one-directional (state that went in is still there) plus two structural
invariants, because absorbing a mimic legitimately adds state and the anchor and
inline fields are lossy by contract.

21 mutations were applied one at a time in a scratch copy, one per fix, and each
turned its named test red. Codex reviewed the diff twice; the first round found a
real defect introduced here (a refused write still reported as written, which
would have cleared a reply draft) and the second found the non-string author
crash. Both are fixed and pinned.
Copilot AI lite review requested due to automatic review settings August 4, 2026 19:30
@ckelsoe

ckelsoe commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 59 minutes.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@ckelsoe, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 25 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f51e2f68-3636-447c-811d-a360bf278460

📥 Commits

Reviewing files that changed from the base of the PR and between 2d5f283 and 5a61727.

📒 Files selected for processing (6)
  • __tests__/composer.test.ts
  • __tests__/imports.test.ts
  • __tests__/parser-roundtrip-fuzz.test.ts
  • __tests__/parser.test.ts
  • composer.ts
  • imports.ts
📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Improved comment editing to preserve replies, metadata, and addressed status during concurrent changes.
    • Added safer deletion and resolution handling with clear failure notices.
    • Added cancellation handling for comment deletion dialogs.
  • Bug Fixes

    • Prevented concurrent edits from overwriting each other.
    • Protected existing comments and code blocks during comment conversion.
    • Improved parsing, validation, escaping, truncation, and malformed-marker diagnostics.
    • Fixed pending operations and unhandled failures during destructive actions.
  • Tests

    • Expanded coverage for concurrent updates, parser edge cases, imports, editing, cancellations, and serialization round trips.

Walkthrough

Changes

Comment integrity and lifecycle consistency

Layer / File(s) Summary
Parser and serialization safety
parser.ts, __tests__/parser.test.ts, __tests__/parser-roundtrip-fuzz.test.ts, .github/copilot-instructions.md
Parser metadata handling, serialization limits, author normalization, marker diagnostics, and round-trip validation were expanded.
Protected comment conversion
imports.ts, __tests__/imports.test.ts, CHANGELOG.md
Comment conversion now skips existing markers and protected code regions while preserving idempotent behavior.
Queued conflict-safe lifecycle writes
comment-service.ts, __tests__/comment-service.test.ts
Lifecycle mutations now queue per file, re-resolve markers, validate snapshots, use editor or vault atomic writes, and propagate refusal results.
Current-marker editing and modal lifecycle
composer.ts, confirm-modal.ts, main.ts, related tests
Composer edits re-resolve markers and preserve current metadata. Modal cancellation and lifecycle-write failures now settle callbacks and notices.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant Composer
  participant CommentService
  participant EditorOrVault
  User->>Composer: submit comment edit
  Composer->>CommentService: resolve current marker
  CommentService->>EditorOrVault: apply snapshot-checked replacement
  EditorOrVault-->>CommentService: write result
  CommentService-->>Composer: success or refusal
  Composer-->>User: close form or show notice
Loading

Possibly related PRs

Suggested reviewers: copilot

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.55% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the pull request's primary focus on preventing text loss and corruption.
Description check ✅ Passed The description directly explains the integrity fixes, affected files, verification results, and deliberate deviations.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This pull request hardens Annoteca’s core data-integrity paths (importing, parsing/serializing markers, editing, and lifecycle writes) to prevent text loss/corruption under stale snapshots, malformed marker shapes, and concurrent writes.

Changes:

  • Makes marker parsing/serialization more forward-compatible and safer (unbounded anchor parsing, serialize-time caps, singleton trailing-line walk rules, author token sanitization, improved malformed-marker diagnostics).
  • Prevents stale or racing writes from silently corrupting notes (writer queue + stale-offset refusal via vault.process, composer edit re-resolve).
  • Makes import conversion skip protected regions (existing markers, fenced blocks, inline code) and adds extensive regression + fuzz testing.

Reviewed changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
parser.ts Forward-compatible anchor parsing; safer trailing-line walk; author token sanitization; improved malformed marker reporting; exports marker scanning for import masking.
imports.ts Adds protected-region masking to avoid rewriting inside markers/fences/inline code during bulk imports.
composer.ts Re-resolves edit targets against current document state and refuses stale/ambiguous edits without discarding user input.
comment-service.ts Serializes writes per-path and refuses stale-offset splices using vault.process / editor-value comparisons; propagates refusal outcomes.
confirm-modal.ts Ensures cancel/dismissal paths settle the caller’s promise (via onCancel fired from onClose).
main.ts Ensures confirm-modal promises settle on failures/cancel; adds a shared failure notice helper for lifecycle verbs.
CHANGELOG.md Documents the user-visible integrity fixes and diagnostics.
.github/copilot-instructions.md Updates repository guidance to reflect the new write/refusal and queueing rules.
__tests__/parser.test.ts Adds targeted regression tests for trailing-line mimicry, author token sanitization, anchors, and malformed-marker diagnostics.
__tests__/parser-roundtrip-fuzz.test.ts Adds a seeded 5,000-iteration serialize/parse fuzz gate to catch integrity regressions.
__tests__/imports.test.ts Adds protected-region import tests, including idempotency and fence/code-span protections.
__tests__/confirm-modal.test.ts Adds cancellation-settlement test coverage for confirm modal dismissal paths.
__tests__/composer.test.ts Adds edit-path tests for freshness, addressed preservation, drift refusal, and ambiguity handling.
__tests__/comment-service.test.ts Adds staleness-window and concurrency tests for applySplices refusal and per-file write serialization.

Comment thread imports.ts
Comment on lines +55 to +64
const out: ProtectedRange[] = [];
for (const m of scanMarkers(content))
out.push({ from: m.start, to: m.end });

let offset = 0;
let openFence: { char: string; length: number; from: number } | undefined;
for (const line of content.split('\n')) {
const lineEnd = offset + line.length;
const fence = FENCE_LINE_RE.exec(line);
const run = fence?.[2];

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (4)
composer.ts (1)

303-306: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

Consider also comparing the marker end offset for id-less markers.

The id-less branch accepts any marker that starts at editingStartOffset and has the same category. CommentService.freshComment is stricter for the same case: it compares start, end, category, and body. The composer cannot compare the body, because the body is what the user is changing. It can still compare the end offset, which is unchanged in the file until this write lands. That closes the narrow case where a different same-category marker now begins at the captured offset and would receive the edited body.

♻️ Proposed tightening
 		const at = parseAt(content, this.editingStartOffset);
-		if (at !== undefined && at.category === snapshot.category) return at;
+		if (
+			at !== undefined &&
+			at.category === snapshot.category &&
+			at.marker.end === snapshot.marker.end
+		)
+			return at;
 		new Notice(VANISHED_MESSAGE);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@composer.ts` around lines 303 - 306, In the id-less marker lookup using
parseAt within the composer flow, also require the parsed marker’s end offset to
match the originally captured marker end offset before returning it. Preserve
the existing start-offset and category checks, and continue showing
VANISHED_MESSAGE and returning undefined when any identity check fails.
__tests__/composer.test.ts (1)

234-278: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the id-less edit branch.

Every test here uses a marker with id: 'edit0001', so only the id branch of resolveEditTarget runs. The id-less branch carries the editingStartOffset reasoning documented in composer.ts lines 57-62 and is the branch that can point at unrelated text. Two cases would pin it: an id-less marker edited with no document change (writes at the captured offset), and an id-less marker after an insertion above it (refuses with the vanished notice).

Based on the coding guideline for __tests__/**/*.test.ts about preserving and extending test coverage, add these as new tests rather than modifying the existing ones.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@__tests__/composer.test.ts` around lines 234 - 278, Add two new tests in the
composer edit test suite covering the id-less branch of resolveEditTarget:
verify an id-less marker with no document changes writes at the captured
editingStartOffset, and verify an insertion above that marker causes submission
to refuse, preserve the document, and log the vanished notice while keeping the
form open. Use a marker without an id and preserve the existing tests unchanged.

Source: Coding guidelines

__tests__/parser.test.ts (1)

1740-1832: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the dedup and sort paths in findMalformedMarkers.

The suite covers one merge, one unclosed opener, and the clean case. Two new behaviours in parser.ts stay untested:

  • The merged set, which collapses several openers inside one container into a single possible-merge finding.
  • The final out.sort((a, b) => a.start - b.start), which interleaves findings from the two loops.

A single fixture with two nested openers inside one merged marker plus a second problem later in the document exercises both.

💚 Suggested additional test
	it('reports one finding per container and sorts findings by position', () => {
		const text = [
			'<!-- annoteca/clarify: first',
			'[id=dup00001]',
			'',
			'<!-- annoteca/tone: swallowed one',
			'<!-- annoteca/note: swallowed two',
			'[id=dup00002]',
			'-->',
			'',
			'Later prose. <!-- annoteca/tone: never closed',
			'[id=dup00003]',
		].join('\n');
		const found = findMalformedMarkers(text);
		// Two openers inside one container collapse to a single finding.
		expect(
			found.filter((f) => f.kind === 'possible-merge'),
		).toHaveLength(1);
		expect(found.map((f) => f.kind)).toContain('unclosed-opener');
		// And the report reads in document order.
		expect(found.map((f) => f.start)).toEqual(
			[...found.map((f) => f.start)].sort((a, b) => a - b),
		);
	});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@__tests__/parser.test.ts` around lines 1740 - 1832, Add a test in the parser
malformed-marker suite using one container with multiple nested openers and a
later unclosed opener. Assert nested openers produce exactly one possible-merge
finding, an unclosed-opener finding is present, and all findings are ordered by
ascending start position, covering the merged deduplication and final sort
behavior of findMalformedMarkers.
__tests__/parser-roundtrip-fuzz.test.ts (1)

250-311: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add anchor and date properties to the gate.

The loop asserts survival for id, category, author, reply bodies, addressed, and resolution. It asserts nothing about anchor or date, and both are in the generated input.

  • The anchor is the field this PR changed most. A nonblank anchor must come back defined, at or under the 200-character ceiling. The dropped over-long anchor is the exact defect described at Line 18, and ANCHORS already contains the 300-character and --> cases that reproduce it.
  • The date has no lossy transform, so parsed.date must equal input.date whenever the input carries one.

Both properties are one-directional, so they fit the contract stated at Lines 26-28.

💚 Suggested additional properties
 			if (parsed.category !== input.category)
 				throw new Error(context(`category changed: ${first}`));
 
+			// The date has no lossy transform, so it must survive verbatim.
+			if (input.date !== undefined && parsed.date !== input.date)
+				throw new Error(
+					context(
+						`date ${input.date} -> ${String(parsed.date)}: ${first}`,
+					),
+				);
+
+			// A nonblank anchor is capped, never dropped. An over-long anchor
+			// being absorbed and deleted is the defect this gate exists for.
+			if (
+				input.anchor !== undefined &&
+				input.anchor.text.trim() !== ''
+			) {
+				if (parsed.anchor === undefined)
+					throw new Error(context(`anchor dropped: ${first}`));
+				if (parsed.anchor.text.length > 200)
+					throw new Error(
+						context(
+							`anchor over the ceiling: ${String(parsed.anchor.text.length)}`,
+						),
+					);
+			}
+
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@__tests__/parser-roundtrip-fuzz.test.ts` around lines 250 - 311, Extend the
round-trip assertions in the fuzz-test loop after parsing to validate anchor and
date: for a nonblank input.anchor, require parsed.anchor to be defined and no
longer than 200 characters, and when input.date is defined require parsed.date
to equal it. Use the existing context-based error reporting and preserve the
current one-directional checks for lossy anchor sanitization.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@__tests__/composer.test.ts`:
- Around line 234-278: Add two new tests in the composer edit test suite
covering the id-less branch of resolveEditTarget: verify an id-less marker with
no document changes writes at the captured editingStartOffset, and verify an
insertion above that marker causes submission to refuse, preserve the document,
and log the vanished notice while keeping the form open. Use a marker without an
id and preserve the existing tests unchanged.

In `@__tests__/parser-roundtrip-fuzz.test.ts`:
- Around line 250-311: Extend the round-trip assertions in the fuzz-test loop
after parsing to validate anchor and date: for a nonblank input.anchor, require
parsed.anchor to be defined and no longer than 200 characters, and when
input.date is defined require parsed.date to equal it. Use the existing
context-based error reporting and preserve the current one-directional checks
for lossy anchor sanitization.

In `@__tests__/parser.test.ts`:
- Around line 1740-1832: Add a test in the parser malformed-marker suite using
one container with multiple nested openers and a later unclosed opener. Assert
nested openers produce exactly one possible-merge finding, an unclosed-opener
finding is present, and all findings are ordered by ascending start position,
covering the merged deduplication and final sort behavior of
findMalformedMarkers.

In `@composer.ts`:
- Around line 303-306: In the id-less marker lookup using parseAt within the
composer flow, also require the parsed marker’s end offset to match the
originally captured marker end offset before returning it. Preserve the existing
start-offset and category checks, and continue showing VANISHED_MESSAGE and
returning undefined when any identity check fails.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 80babd3a-c837-411b-862c-cb833a1458a6

📥 Commits

Reviewing files that changed from the base of the PR and between bf1612a and 2d5f283.

📒 Files selected for processing (14)
  • .github/copilot-instructions.md
  • CHANGELOG.md
  • __tests__/comment-service.test.ts
  • __tests__/composer.test.ts
  • __tests__/confirm-modal.test.ts
  • __tests__/imports.test.ts
  • __tests__/parser-roundtrip-fuzz.test.ts
  • __tests__/parser.test.ts
  • comment-service.ts
  • composer.ts
  • confirm-modal.ts
  • imports.ts
  • main.ts
  • parser.ts

The fence and code-span scanners added in the previous commit walked the whole
document line by line without regard to marker spans. Marker bodies are
arbitrary user text and the format stores the annoteca-original block as a
literal fence, so ``` lines inside a marker are ordinary rather than exotic:
a body holding a single unbalanced one opened a block that never closed, and
every subsequent line counted as protected. Bulk import then converted nothing
after that marker and reported "converted 0", which reads as "there was nothing
to convert." Executed: two real comments after such a marker, converted 0.

Marker interiors are skipped entirely now, which costs nothing because every
marker span is already protected on its own account. A fence opened OUTSIDE a
marker still spans it, matching how a renderer reads the same text.

This was the question the parser's own fence rule turns on, asked about a new
mechanism instead of the one being fixed: what can a body CONTAIN?

Also folds in the four review nitpicks, since a push was happening anyway:

- The id-less composer lookup compares the marker's end offset as well as its
  start and category, matching CommentService.freshComment for the same case.
  It cannot compare the body, because the body is what the user is changing, so
  extent is the only other identity the file carries.
- Coverage for the id-less branch of resolveEditTarget, which no test reached:
  writes at the captured offset when nothing moved, refuses on an insertion
  above it, and refuses when a different same-category marker now starts there.
- Coverage for findMalformedMarkers' per-container dedup and its final sort.
  The sort test needed a document where the two scans genuinely disagree about
  order; the first attempt passed without the sort and was rewritten.
- The fuzz gate asserts the anchor survives sanitization within the 200-char
  ceiling, and that the date comes back byte-identical.

25 mutations, all killed.
@ckelsoe

ckelsoe commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

Second commit: 5a61727

A regression this PR introduced, found by Copilot and reproduced by execution. The fence and code-span scanners added in the first commit walked the whole document without regard to marker spans. Marker bodies are arbitrary user text and the format stores the annoteca-original block as a literal fence, so a body holding one unbalanced ``` line opened a block that never closed, and everything after it counted as protected. Bulk import then converted nothing after that marker and reported converted 0, which reads as "there was nothing to convert." Measured: two real comments after such a marker, converted 0.

Marker interiors are now opaque to both scanners, which costs nothing because every marker span is already protected in its own right. A fence opened outside a marker still spans it, matching how a renderer reads the same text.

This was the question the parser's own fence rule turns on, asked about a new mechanism rather than the one being fixed: what can a body CONTAIN?

The four review nitpicks are folded in, since a push was happening anyway:

  • The id-less composer lookup compares the marker's end offset as well as start and category, matching CommentService.freshComment. It cannot compare the body, because the body is what the user is editing.
  • Coverage for the id-less branch of resolveEditTarget, which no test reached: writes at the captured offset when nothing moved, refuses on an insertion above, refuses when a different same-category marker now starts there.
  • Coverage for findMalformedMarkers' per-container dedup and its final sort. The sort test needed a document where the two scans genuinely disagree about order; my first attempt passed without the sort and was rewritten.
  • The fuzz gate now asserts the anchor survives sanitization within the 200-character ceiling, and that the date returns byte-identical.

Verification: tsc, lint, build green. 421 tests across 22 suites. 25 mutations, all 25 killed.

Review status, stated plainly: the APPROVED decision above is CodeRabbit's review of 2d5f283. It has not reviewed 5a61727. Re-review was skipped on Charles's explicit instruction, so this merges below the repo's normal bar by decision, not by oversight.

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.

2 participants