Repository navigation
Stop six ways of losing or corrupting text - #23
Conversation
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.
|
@coderabbitai full review |
✅ Action performedFull 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. |
|
Warning Review limit reached
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 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 configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (6)
📝 WalkthroughSummary by CodeRabbit
WalkthroughChangesComment integrity and lifecycle consistency
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
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
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. |
| 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]; |
There was a problem hiding this comment.
🧹 Nitpick comments (4)
composer.ts (1)
303-306: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low valueConsider also comparing the marker end offset for id-less markers.
The id-less branch accepts any marker that starts at
editingStartOffsetand has the same category.CommentService.freshCommentis 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 winAdd coverage for the id-less edit branch.
Every test here uses a marker with
id: 'edit0001', so only the id branch ofresolveEditTargetruns. The id-less branch carries theeditingStartOffsetreasoning documented incomposer.tslines 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.tsabout 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 winAdd 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.tsstay untested:
- The
mergedset, which collapses several openers inside one container into a singlepossible-mergefinding.- 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 winAdd anchor and date properties to the gate.
The loop asserts survival for
id,category,author, reply bodies,addressed, andresolution. It asserts nothing aboutanchorordate, 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
ANCHORSalready contains the 300-character and-->cases that reproduce it.- The date has no lossy transform, so
parsed.datemust equalinput.datewhenever 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
📒 Files selected for processing (14)
.github/copilot-instructions.mdCHANGELOG.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.tscomment-service.tscomposer.tsconfirm-modal.tsimports.tsmain.tsparser.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.
Second commit:
|
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
imports.tscomposer.tsapplySplicesrefuses stale offsets (vault.process); per-path write queuecomment-service.tsparser.tsserializesanitizes author tokens at all four emission sitesparser.tsparser.ts,main.ts,confirm-modal.tsfindMalformedMarkersreportsunclosed-openerandpossible-mergeparser.tsmain__tests__/parser-roundtrip-fuzz.test.tsParsing 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.-tis 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, soserialize's new cap meant the parser's pattern was never exercised). Both fixed, then re-run.gpt-5.6-sol) reviewed the diff twice. Round 1 found a real defect introduced here: a refused write still returnedwritten, soappendReplyreturnedtrueand the popover would clear a reply the user had just typed while nothing reached the file. Round 2 foundsanitizeAuthorTokenthrowing on a non-stringauthorTagfromdata.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
confirm-modal.tsis outside the declared footprint. The spec asks for Cancel to settle the promise but budgets no file for it. Charles chose adding anonCancelhook over the alternatives. It fires fromonClose, not the Cancel button, because Escape and a background click are the common dismissals and neither touches the button.serializestrips]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, sincebuildAnchorFromSelectionalready strips it. One line; trivially revertable.id/date/author/anchor;addressedandresolutionwere already first-met-wins and had the same silent-deletion bug, so they get the same treatment.ANCHOR_LINE_REkeeps\rout of its character class. The spec writes[^\]\n]*; a greedy group would then swallow a trailing\ron CRLF files and store it in the anchor. The load-bearing parts (unbounded,*) are as specified..github/copilot-instructions.mdupdated. Required by the commit gate's prose-drift rule: it still described the vault write path asvault.modifyand gave 80 characters as the only anchor limit. Two new hard rules added while there, both footguns this PR introduces: honourapplySplices's return value, and delegate to the*Unqueuedverbs or deadlock.Observations, not fixed here
sanitizeAuthorTokencovers the plugin's own writes, but an assistant hand-writing[author=Bob Smith]still produces a line the parser drops. Fixing it means aSKILL_SCHEMA_VERSIONbump, which is its own decision.CommentService.resolvedAuthor()calls.trim()on the raw setting and still throws on a non-stringauthorTag. Pre-existing, and PR C's settings-normalization item is the right place for it.