Skip to content

feat(mcp): read, grep and edit parts of a document - #770

Merged
pikann merged 42 commits into
Paca-AI:masterfrom
msammu07:feat/mcp-partial-doc-tools
Nov 15, 2026
Merged

pikann merged 42 commits into
Paca-AI:masterfrom
msammu07:feat/mcp-partial-doc-tools

Conversation

@msammu07

@msammu07 msammu07 commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Part of #747 (docs pull / push / content check for coding agents). Lets an agent read, search and change part of a document through the MCP server without sending or rewriting the whole document. Builds on #751, #753, #754, #759 and #769.

Two concerns, kept as separate commits. The last commit (fix(api): clear content_text when content changes without it) is a follow-up to #768: it was pushed for that PR minutes after it was merged, so it is included here with its own migration. It can be split into its own PR if you prefer.

MCP tools

  • read_doc takes one of outline (headings with line numbers), section (one heading's part) or lines ("40-80"). Returned lines are numbered, and the header shows the document's ETag.
  • grep_docs (new) finds lines across documents: literal or regex, ignoreCase, path to limit it to a folder or one document, context (0 to 5 lines), limit. Output is Folder/Title:12: text, where the line number is a line of the Markdown read_doc returns.
    • A single plain word is narrowed through the server search first; every other pattern scans the folder (up to 200 documents, with a notice when the cap is hit).
    • A regex runs in a worker that is stopped after 2 seconds.
  • edit_doc (new) replaces an exact string (old_string, new_string, optional replace_all), by document id or by path.
    • Only the blocks the text touches are rewritten. Every other block is sent back exactly as it was stored: ids, colours, alignment and nested blocks included.
    • The write carries If-Match. On a 412 it reads again and retries once; a second conflict is reported with who wrote, when, their note and client.
    • An edit that would lose something Markdown cannot carry in a touched block (a mention chip, underline or text colour, a toggle, a table without a header row) is refused, names the block and the loss, and changes nothing.
    • A block that holds such formatting is either left exactly where it is or edited in place. An edit that would reorder, move, split, merge or retype it is refused and asks for smaller edits; the same holds for reordering rows or columns of a table with cell formatting or column widths. Blocks without such formatting can be restructured freely.
    • The result is checked before it is written: a final audit compares the stored blocks with the new ones at every depth, independent of how the result was built, and the new blocks must read exactly as the edited Markdown does. An edit that changes nothing, or that would change how the blocks after it are read (an unclosed code fence), is refused.
    • A locked managed copy is refused with the repository file to edit instead.
  • The document client gains patchDocument (a content write with If-Match). batchGet from feat(mcp): add pull and push commands for documents #769 is reused.

API follow-up to #768 (last commit)

A writer that changes a document's content without filling content_text (an API pod from before this change during a rolling upgrade, or a manual UPDATE) left the old text in the search index: the row is not NULL, so the backfill never revisits it, and search kept returning the document for text it no longer has.

  • Migration 000092 adds a trigger that sets content_text back to NULL when content changes, unless the transaction declared that it wrote content_text itself (paca.content_text_written, transaction-local, the same mechanism as paca.skip_doc_seq). updateDocumentLocked, the only code path that updates content, declares it.
  • A NULL row is found through the old JSON match, and the backfill refills it at the next API start.
  • 000091 is unchanged. 000092 is up-only and safe to apply twice.
  • The description of feat(api): search document text across formatting with a trigram index #768 mentions this trigger as part of 000091; it arrives with this PR instead.

Decisions, listed so they can be challenged

  1. edit_doc matches against the Markdown read_doc shows, so what an agent reads is what it can replace.
  2. A lossy edit is refused, not applied with a warning. The reply points at the web editor, or write_doc when the loss is acceptable. This includes restructuring edits around formatted blocks: text similarity never decides where formatting goes, so when an edit cannot be told from a reorder it is refused rather than guessed.
  3. One automatic retry on 412, not more.
  4. grep_docs trusts the server search only for a single plain word; anything else scans, so a match read_doc would show is never missed because of how search tokenises.
  5. The Playwright suite now needs the MCP build (.github/workflows/e2e-tests.yml gains a build step), because the new spec runs the built tool against the stack.

Known gaps

  • A grep_docs single word that exists only in Markdown syntax the search does not index (for example inside a code fence's language tag) can be missed by the narrowed path.
  • A context line past limit is not marked as a match.
  • A cleared row (trigger above) stays unindexed, still found through the old match, until the next API start or the next edit.
  • edit_doc refuses some edits a person would consider safe: changing text in a block that contains a mention chip, underline or coloured text; changing the type of a formatted block; deleting one of several blocks that read the same when one of them is formatted; a replace_all where one of the matches changes nothing.
  • A rewrite of several formatted blocks in one edit is compared by words with the blocks' old text to catch a disguised reorder. A reorder reworded so far that it shares no words with the original is treated as new text in the same place.
  • Against a server older than feat(api): add a document content hash with ETag, If-Match and no-op writes #751, edit_doc writes without If-Match, as write_doc does.

Type of Change

  • New feature (MCP package), plus a bug fix with a migration (API)

Testing

  • apps/mcp: tsc clean; lint reports 4 warnings, all in files this PR does not touch; vitest 1142 of 1142, also in a Linux container limited to 2 CPUs. New: tools/doc-edit.test.ts (direct tests of the audit on hand-built wrong results; a seeded fuzz by edit kind, including swaps, splits, merges, indents, duplicates with different formatting and formatted tables, whose checks are written in the test and do not call the audit; scaling tests that bound how the cost grows with list length and nesting depth), tools/filesystem-doc-tools-partial.test.ts, utils/markdown-sections.test.ts, api/doc-client-batch-patch.test.ts.
  • services/api, CI's commands in a Linux container: go vet, unit tests with -race and ./test/e2e/... pass.
    • test/e2e/doc_partial_edit_test.go: a write that changes one of ten blocks leaves the other nine stored byte for byte.
    • test/e2e/doc_text_search_test.go: a raw content update clears content_text and search follows the new text; the same content written again keeps it; a formatting-only change through the API keeps it; the backfill refills it without moving the change feed; 000092 applied twice leaves one trigger.
  • apps/e2e: new tests/docs/mcp-edit-doc.spec.ts runs the built edit_doc against the stack through the gateway, by document id and by path, and checks that the nine untouched blocks are stored unchanged. Both pass. The by-path variant is the one that found the If-Match bug fixed in fix(api): accept a document ETag with a compression suffix in If-Match #759.
  • Browser specs (tests/docs and tests/realtime, chromium) on a stack built from this branch: 217 passed, 6 skipped, 1 failed. The failure is docs.spec.ts:640 (edit own comment, uses Control+a on macOS), which fails the same way on master.

Checklist

  • The change is focused and scoped: two concerns, see the note at the top.
  • Related documentation is updated: apps/mcp/CHANGELOG.md; tool descriptions.

read_doc takes outline, section and lines, numbers the lines it returns
and shows the ETag. grep_docs finds lines across documents (literal
through the server search, or regex over a folder, at most 200 documents)
and prints grep-style Markdown line numbers. edit_doc replaces an exact
string: only the touched blocks are re-parsed, every other block is sent
back as the object read, with PATCH and If-Match, one retry on 412, and a
clear error for a locked managed copy.

The doc client gains batchGet and patchDocument.
A block the edit rewrites is first rendered to Markdown and parsed back;
when that does not give the same block (ids aside, after the colours a
one-for-one replacement inherits), the edit is refused with the line and
the reason instead of dropping mentions, underline, toggles, diagrams,
nested blocks or a table's header row. Nested blocks equal to the stored
ones are kept as the stored objects.
Server search matches one formatting run of the stored text, so only a
single plain word is narrowed through it; a phrase, Markdown syntax or a
word the search misses scans the documents (at most 200). A regex runs in
a worker thread and is stopped after 2 seconds with a tool error.
Documents that cannot be read are counted in the reply, and write_doc
points to edit_doc for a partial change.
An edit whose old and new strings are equal writes nothing. An old_string
that became ambiguous after a 412 re-read carries the other writer's
details, and a 409 DOC_LOCKED from the write re-reads the document so the
reply names the repository file it is locked to.
… merge, split or delete coloured blocks

The round-trip check now ignores whitespace Markdown does not show, and the re-parsed text drops the space the parser adds after a soft line break. Deleted blocks are not checked. A merge keeps the first block's colours and alignment, a split gives them to every part, and only a change that spreads blocks with different props over a different number is refused. Refusal messages read as one sentence.
…d and time regexes per document

A multi-word literal asks the server search for its longest word of three or more letters, matches the candidates' Markdown, and scans (capped, with the notice) only when that finds nothing. A regex gets 500 ms per document and 10 s in all; a slow document is named in a notice instead of failing the call, and the run stops after three slow documents.
… old block agrees

A merge, split or change of type now carries colour and alignment only when every old block in the stretch has the same values and, when they are not the defaults, the new blocks keep the old type. Otherwise the edit is refused, naming the lines. Inline code stays compared strictly, and table cell text is compared with the same loose whitespace as paragraphs.
A writer that changes a document's content without filling content_text
(an API pod from before this change during a rolling upgrade, or a manual
UPDATE) left the old text in the search index: the row is not NULL, so the
backfill never revisits it, and search kept returning the document for
text it no longer has.

Migration 000092 adds a trigger that sets content_text back to NULL when
content changes, unless the transaction declared that it wrote
content_text itself (paca.content_text_written, transaction-local, set in
updateDocumentLocked). A NULL row is found through the old JSON-path match
and refilled by the backfill at the next start.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

edit_doc does not always keep its central promises ("every other block is sent back exactly as it was stored", "a lossy edit is refused, not applied with a warning"). When a blank paragraph sits directly before a list, an edit to an item of that list silently drops the item's text colour (a mention chip or underline goes the same way), loses the item's id, and moves the blank paragraph. The identical content is refused as unsafe in a list with no blank paragraph in front.

Reviewed changes

  • read_doc partial views — outline, section and lines render from the same blocknoteToMarkdown numbering grep_docs reports, number every line, and put the document ETag in the header.
  • grep_docs — new tool over up to 200 documents: literal or regex, case folding, path scope, context hunks, match limit, server-search narrowing for plain words, and an eval-worker regex scan bounded per document and in total.
  • edit_doc — new tool that matches old_string against the Markdown read_doc returns, re-parses only the touched units, keeps untouched blocks by object identity, refuses rewrites Markdown cannot carry, and writes through PATCH /docs/{docId} with If-Match plus one 412 retry that names the other writer.
  • patchDocument — the doc client gains a by-id content write with If-Match, reusing batchGet from #769.
  • API content_text fix — migration 000092 adds a trigger that nulls content_text when content changes unless the transaction declares it wrote the text, which updateDocumentLocked now does; the backfill refills such rows at the next start.
  • Tests — new vitest suites (including a 300-iteration seeded fuzz), two Go e2e files for untouched-block identity and the trigger/backfill/change feed, a Playwright spec that runs the built tool against the stack, and a CI step that builds apps/mcp.

🚨 A blank block before a list turns edit_doc's paired rewrite into an unchecked insert + delete

align emits the edit's insertion before an empty block's deletion (the lcs[i][j+1] >= lcs[i+1][j] tie-break), so the pure-insertion flush skips inherit, and the replaced block is recorded as deleted, which later skips markdownLoss entirely. I ran this against the branch: [emptyParagraph, bullet("alpha", {textColor: "red"})] with "alpha" → "ALPHA" returns [bullet{id: <new>, textColor: "default", content: "ALPHA"}, emptyParagraph], and the same list item holding a teamMention chip is accepted with the chip flattened to the plain text @Ann (id: u1). Both differ from the documented behaviour, and from what the same edit does without the blank paragraph.

Technical details
# An empty block in a list unit splits the ins/del pair

## Affected sites
- `apps/mcp/src/tools/doc-edit.ts:505-507` — `ins` flushed as a pure insertion: no `inherit`, so the edited block loses its id and every prop Markdown cannot carry.
- `apps/mcp/src/tools/doc-edit.ts:518-520` — the empty block's `del` becomes a `keep` after that insertion, so it lands after the edited block.
- `apps/mcp/src/tools/doc-edit.ts:616-617` — `how: "deleted"` skips `markdownLoss`, so the loss is never reported.
- `apps/mcp/src/tools/doc-edit.ts:447` — the tie-break that emits `ins` before the empty block's `del`.
- `apps/mcp/src/tools/doc-edit.ts:62-68` — `joinable` folds a block whose render is `""` into the neighbouring list, which is what puts it in the same unit as the edited item.
- `apps/mcp/src/__tests__/tools/doc-edit.test.ts:635-729` — the fuzz cannot catch this: it asserts rendered-Markdown equality (invariant under the reorder) and widens `[lo,hi]` over exactly the empty and list blocks via `isList`.

## Reproductions (run against this head)
- `spliceEdit([emptyParagraph, bullet("alpha", {textColor:"red"})], "alpha", "ALPHA", false)` → `[bullet{id:<new>, textColor:"default"}, emptyParagraph]`.
- `spliceEdit([emptyParagraph, bullet(["hi ", teamMention, " there"])], "there", "THERE", false)` → accepted; chip replaced by `@Ann (id: u1)`.
- Both documents without the leading empty paragraph keep the id and refuse the mention loss, as intended.

## Required outcome
- A block that renders to nothing and sits before the touched block keeps its position, and the touched block still goes through `inherit`/`markdownLoss`, so a lossy rewrite is still refused. Either the pairing survives the empty block, or the empty block must not let the insertion detach from its deletion.

## Suggested approach
- Do not let the empty-block `keep` decision (line 518) sit between an `ins` and the `del` that pairs with it: walk empties first, or flush `ins` together with the following `del` run when that run holds only empty blocks.

⚠️ grep_docs reports every line for a pattern made only of emphasis markers

stripEmphasis deletes every * run and every _ that is not inside a word, so for pattern: "*", "**" or "_" the stripped pattern is "" and includes("") is true for every line: the tool returns the whole document as matching lines, counted in the header. pattern allows this (z.string().min(1)), and neither the search narrowing nor the regex syntax check applies to literals.

Technical details
# literalMatcher fabricates matches when the stripped pattern is empty

## Affected sites
- `apps/mcp/src/utils/markdown-sections.ts:177-181` — `stripped` becomes `""` for a markers-only pattern; the fallback then matches everything.
- `apps/mcp/src/tools/filesystem-doc-tools.ts:1068` — the only construction site of `literalMatcher`.

## Required outcome
- `literalMatcher("**")("no asterisk here")` must be `false`; a literal pattern should never match a line that does not contain it, with or without its emphasis markers.

## Suggested approach
- Skip the stripped comparison when `stripped === ""` (or when it equals `plain`).

ℹ️ A refusal names the wrong line for numbered list items

lineOf looks for a block's standalone first line inside the full Markdown, but a numbered item renders as 1. … on its own and 2. …, 3. … in place, so the search misses and the fallback returns the unit's first line. Editing "1. alpha\n\n2. beta" in [intro, red "alpha", blue "beta", "z"] reports "lines 3 and 3" where the blocks are on lines 3 and 5, so an agent following the message edits the wrong block. Computing each block's offset from the preceding renders gives the right line without a search.

Technical details
# lineOf's indexOf fallback collapses to the unit start

## Affected sites
- `apps/mcp/src/tools/doc-edit.ts:610-615` — `full.indexOf(renders[idx].split("\n")[0], unit.start)`, with `unit.start + …` as the fallback.

## Required outcome
- `SpliceError.lines` and the messages built from it name the line each replaced block starts on, for every block type the tool accepts.

## Suggested approach
- Inside a unit `full` is the blocks' renders concatenated, so accumulate `renders[k].length` (plus the separator) instead of searching for the first line; keep `indexOf` only as a fallback.

ℹ️ A document stopped by the total time budget is reported as a slow regex

regexScan arms each document's timer with Math.max(0, Math.min(perDocMs, deadline - Date.now())), so a document stopped because the 10 s total ran out also lands in timedOut and is reported as having "run longer than 500 ms"; after three of them the notice tells the user to simplify a pattern that may be fine. Keep the two reasons apart so the reason given matches the cause.

Technical details
# One list mixes "the pattern stalled" and "the budget ran out"

## Affected sites
- `apps/mcp/src/tools/filesystem-doc-tools.ts:1054-1066` — the notices built from `scan.timedOut` / `scan.unsearched`.
- `apps/mcp/src/utils/markdown-sections.ts:255-262` — the timer clamp that produces the ambiguous `timedOut` entry.

## Required outcome
- A document that was never really searched because the total deadline passed is not described as slow, and the "simplify the regex" advice is only given when the pattern is what stalled.

## Suggested approach
- Have `regexScan` report a `budgetStopped` index list separately from `timedOut`, and word the notice from that.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

…ists

An empty paragraph before a list item split the edit's insertion from the deletion it pairs with, so the edited block lost its id and colours, skipped the loss check (a mention chip became text), and the empty block moved. Every run of changes between two kept blocks is now one stretch; blocks that render to nothing always stay at their place and never split a pairing. A block deleted in one stretch while text is inserted in another is checked for loss. The fuzz now compares every untouched block's identity and position, and generates empty paragraphs, colours, mention chips and underline.
A numbered item renders "1. beta" alone but "2. beta" in its list, so searching for its own render missed and the refusal named the list's first line. Blocks are now located inside their unit in order, by text without the list marker; the old search remains the fallback.
…t searched, not slow

regexScan armed each document's timer with the smaller of its own limit and the time left, so a document stopped by the 10 s budget was recorded as slow and the notice blamed the pattern. It now records only documents that ran past their own limit as slow, leaves budget-stopped ones unsearched, and says why the run stopped (stoppedBy).
… language, and refuse edits it cannot show

inherit kept the old block's start when the new Markdown left it at its default, so "3. a" to "1. a" kept 3 and reported success. Props Markdown writes now come from the parsed edit. Each edited range must also render as the edited text parsed as a whole and differ from before; otherwise the edit is refused (no_change for an edit Markdown cannot show).
…locks as stored

Nested children were paired by index, so deleting or inserting a child shifted ids and colours onto its siblings, and a retyped coloured child lost its colour silently. Children are now aligned like top-level blocks, recursively, with the same loss checks (a nested refusal names the top-level block). An old block whose render reappears anywhere among the changed blocks at its level (moved, swapped, indented, outdented) is returned as the stored object. In a merge or split, empty blocks between the old blocks follow the first new block.
A final check over the old and new trees, at every depth and independent of how the result was built: no id appears twice; an old block holding what Markdown cannot carry (colours, alignment, mention chips, underline, a type Markdown has no form for) that is not returned as stored must keep its id with the same such data, must not see its content move to another block, and may only disappear when the edit adds no new block; and an id never ends up on text that came from another old block. A merge keeps the first old block's id on the first new block.
…ey continue

Blocks with the same Markdown swapped colour, type or id on an indent or outdent, because a move pass paired each with the first equal block in document order, and a split gave the old id and colours to the first new block whatever its text.

Both trees are now flattened in document order (parents before children) and aligned once over every depth: the longest common subsequence of own Markdown pairs blocks in order, and such a block keeps its type, props, text and id, with only its nested blocks replaced. Blocks the order leaves out pair as moves when they read the same, in order. The rest, between two such pairs, are rewritten: one to one at their positions when no other new block continues an old block's text better (common prefix plus suffix), otherwise each old block goes to the new block that continues its text most, and new blocks nothing continues are plain. Where the edit could mean either of two equal blocks that differ in colour, type or chips (deleting one of them, or a split into equal halves of a coloured block), it is refused and the lines are named.
…e blocks are equal

An 800-item list with replace_all took 108 s and one edit in a 3000-item list 4.5 s: the exporter ran inside nested searches. Renders are now cached per object for the edit, blocks equal as Markdown sees them are compared without rendering, blank blocks are found without rendering those that show a marker or text, and the whole-document re-read is skipped when the new document's Markdown is the edited text. Now about 1.0 s and 1.5 s, with a test bound.
…ed into it

A coloured block merged into the middle of another block's text shares no prefix or suffix with it, so the alignment took it as deleted and its colour was lost. The alignment now counts text found inside a new block as continuing there (so the colours must agree), and the audit refuses an old block holding what Markdown cannot write whose id is gone while its text sits inside a block the edit wrote without that data.
…or chips

Adds duplicate pairs (coloured, check items, a mention chip next to the plain text that reads the same, a duplicate nested under its twin) and edit kinds that indent, outdent, split and insert before them, and swaps of any two neighbouring lines. The in-test checks gain: no new block continues an old block's text better than the block that kept its id, and siblings that read the same keep their order.
…ition in a split

With pairing by text, a plain block whose whole text changed ("a" to "A") in a split had no new block continuing it, so it was deleted and its id lost. Such blocks now give their ids, in order and by type, to the new blocks nothing continues. Blocks that carry colours, chips or other data Markdown cannot write still count as deleted, and the audit decides.
Inside an edited range, a block holding data Markdown cannot write (or
holding a nested block that does) is now either kept (same own part,
same parent, all kept blocks in their old order), edited in place in a
range that maps one to one by position, or deleted when its Markdown is
unique in the range. Anything else is refused and the message says to
make the change in smaller edits. Text similarity no longer decides
where such data goes: swapped sections, swapped list subtrees, a reorder
rewritten as edits, splits and merges of blocks with data are refused.

Ranges without data are free: ids are best effort there, so the audit's
id checks (rules 3 to 5) apply to blocks with data only.

Table column widths, header settings and cell props now count as data,
and an in-place cell edit keeps them. Empty nested blocks no longer make
their parent unrewritable.
…aps and tables

The fuzz now checks the rule on its own, per edited run that holds data:
every block with data was kept under the same parent with all kept blocks
in order, edited in place in a run that maps one to one by position with
no text moved between blocks, or deleted while unique; and no block was
deleted next to an equal block with data. It replaces the id-closeness
and equal-render order checks.

New kinds: section swap (with and without renaming), list subtree swap,
swap with both ends rewritten, deleting one of three equal blocks, and
tables with column widths and cell colours (cell edit, deleting one of
two equal tables). 4200 iterations.
Inside a table with column widths, header settings or cell props, an
edit may now only change cell text in place: when two or more rows
change and one row's new text equals, or shares more words with, another
changed row's old text than its own, the edit is refused (the formatting
stays by index, so it would land on the other row). The same check runs
over columns when every row changed. The audit checks the table on its
own.

Across blocks edited in place by position, when two or more are edited
and one holds data, a data block's new text must not share more words
with another edited block's old text than with its own, and no edited
block's new text may share more words with the data block's old text
than the data block's new text does. Word overlap is a Dice score on
lower-cased words. This is a guard against reordered and reworded
blocks, not a guarantee: it only refuses, and names both lines.
…ders

The fuzz no longer repeats the implementation's text-inclusion test.
Instead, new kinds generate disguised reorders and assert they are
refused whenever a moved block holds data: swaps and rotations of
one-line blocks with each text reworded (prefix and suffix added,
upper-cased, one shared word replaced), and, in tables with column
widths or a coloured cell, row swaps, column swaps and replacing one
row with another.
…sted

Whether Markdown nests a block's children was checked for every block
of a range by rendering and parsing its whole subtree, so a list nested
d deep cost about d cubed. Once a block's whole subtree reads back with
the same nesting, the blocks inside it did too, so they are no longer
parsed again. A leaf edit at depth 100 takes about 0.3 s, down from
3.8 s.
@msammu07

Copy link
Copy Markdown
Contributor Author

Pushed 539de2c8..e14361eb (only apps/mcp).

The four findings from the review summary

  1. Empty block before a list broke edit_doc's pairing: fixed; empty blocks keep their place before, between and after list items.
  2. A grep_docs literal made only of emphasis markers matched every line: fixed.
  3. The refusal named the wrong line for numbered list items: fixed; each item's own line is named.
  4. Documents cut off by the time budget were reported as a slow regex: now reported as not searched.

Further edit_doc problems found by our own review rounds on the same code, each a case where formatting Markdown cannot carry (colour, alignment, chips, toggles, table widths and cell colours) or a block id could end up on the wrong block without a refusal: nested children paired by index; a list start edit reported as done while nothing changed; moved or indented blocks losing colour; a split giving the old id to the first new block; same-text blocks swapping formatting; section and row swaps. Instead of making the pairing smarter, edit_doc is now narrower: a block with such formatting stays in place or is edited in place, and anything else is refused. A final audit enforces this on every result. A replace_all over a long list was quadratic (800 items: 108 s) and now takes under a second.

The description is updated (behaviour, decision 2, known gaps, test counts). Checks on this tip: tsc, lint (4 old warnings), vitest 1132 of 1132, build, and mcp-edit-doc.spec.ts against the stack, by id and by path.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The new doc-edit tests pin wall-clock time to one machine's speed. On a 4-core GitHub Actions runner using the versions in bun.lock, the full vitest run fails the 4200-iteration fuzz (80 s against its 60 s cap) and the 3000-item edit (6.4 s against its 6 s bound). mcp-pr-ci runs exactly that suite, so the job goes red with no product bug behind it.

Reviewed changes

Delta against the prior pullfrog review at 539de2c (22 commits; the API follow-up, the doc client and the tool wiring are unchanged since then).

  • Replaced edit_doc's block pairing with one rule applied at every depth — positional LCS first, then moves, then text continuation — and placed blocks that render to nothing by their neighbours, so a blank paragraph before a list no longer detaches an edit's insertion from its deletion.
  • Added a final audit over every edited range (auditEdit, staysInPlace): a block carrying colour, a chip, underline, a toggle or table formatting may only be kept as stored, edited in place under a position-preserving mapping, or deleted when unique — never moved, split, merged or retyped.
  • Added reorder guards for rewrites masquerading as in-place edits (alike/closerToOther, tableMoves), so reworded swaps and formatted-table row or column reorders are refused while plain reorders still apply; the guards only refuse.
  • Refused edits that change how Markdown reads the blocks after them (an unclosed code fence) and edits that change nothing in Markdown, the latter through a new no_change kind.
  • Report refusal lines from the document's own block offsets (blockStarts), which fixes numbered list items, and name nested blocks through lineOfBlock.
  • Cached per-block renders (ownKey, subKey, canonOwn, ownText) and skipped reparsing subtrees whose parent already reads back nested, cutting the cost of replace_all over 800 items, a depth-100 list and a 3000-item list.
  • Fixed grep_docs's emphasis-only literal pattern matching every line, and reported documents cut off by the 10 s budget separately from documents whose regex stalled.
  • Added audit unit tests on hand-built wrong results, a 4200-iteration fuzz by edit kind with checks written independently of the implementation, empty-block, nested, move and formatted-table cases, and a regex-budget test.

⚠️ The new wall-clock bounds are tighter than a CI runner's runtime

mcp-pr-ci runs bun run test on ubuntu-latest. On a 4-core AMD EPYC runner with the versions in bun.lock, the suite fails two of the new time assertions: the fuzz test takes ~80 s against its 60 s cap, and the 3000-item edit takes 6.4 s against its 6 s bound once the rest of the suite runs in parallel. Neither is a product bug, but the bounds make the suite machine-dependent, so it fails for anyone on a runner slower than the author's.

Technical details
# Wall-clock bounds set to the author's machine

## Affected sites
- `apps/mcp/src/__tests__/tools/doc-edit.test.ts:2048` — the fuzz `it(...)`, whose timeout is `60_000` at :3007; measured 80.4 s, also when run alone.
- `apps/mcp/src/__tests__/tools/doc-edit.test.ts:1677` — `expect(Date.now() - t0).toBeLessThan(6000)`; measured 6396 ms in the full-suite run, passes alone.
- `.github/workflows/mcp-pr-ci.yml:56` — `bun run test`, job timeout 10 min.

## Measured (this head, `@blocknote/[email protected]`, `[email protected]`)
- `npx vitest run` in `apps/mcp`: 2 failed, 1130 passed, 47 files, 4-core AMD EPYC 9V74.
- The fuzz alone with its timeout raised to 600 s: passes in 80 368 ms.
- The other two bounds (800-item `replace_all` < 6 s, depth-100 leaf < 1.5 s) passed, in the same margin range.

## Required outcome
- The suite passes on a 4-core CI runner with default worker parallelism, without turning machine speed into a failure.

## Suggested approach
- Raise the fuzz timeout to real headroom (e.g. 180 s) or cut iterations, and loosen the long-list bounds (or assert operation counts instead of wall time).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

Comment thread apps/mcp/src/tools/doc-edit.ts Resolved
…refusals

A nested block's line was found by searching for its own Markdown, but a
nested numbered item renders "1. dup" alone where the document writes
"2. dup", so the search missed and the refusal named the top-level
block's line. The search now drops the list marker and accepts a match
only where it starts a line after indentation, quote marks and a marker.
Tested for bullet, numbered (with and without a stored start), check and
toggle items at depths 2 and 3.
CI runners are slower than a laptop, so absolute bounds failed there
(3000 items took 6.4 s against 6 s). Each test now times two sizes,
best of three, and bounds the ratio: 4x the items must cost under 9x
(about 4.1-4.4x measured; quadratic would be 16x), and 4x the depth
under 20x (7.5x measured; the cubic walk before e14361e measured 27.8x).
The kind fuzz ran 4200 cases in 26 s here and 80 s on CI, past its
60 s timeout. It now runs the first 1560 cases of the same seeded
stream (about 10 s here), with a 180 s timeout, and FUZZ_ITER=<n> runs
a longer search. Floors scale with the cases per kind, and every kind
must still apply and refuse where it did at 4200 cases. The bugs the
fuzz found (the open-fence edit, the section swap) keep their own tests.
@msammu07

Copy link
Copy Markdown
Contributor Author

Pushed e14361eb..5ab53c4e. The MCP job failure was the tests, not the tool: two doc-edit tests asserted wall-clock times. The performance tests now time two sizes and bound the ratio (4x the items must cost under 9x; depth 25 to 100 under 20x), with a timeout only as a hang guard, and the fuzz runs 60 cases per kind (1560) with a 180 s timeout; FUZZ_ITER=<n> runs a longer search. The suite (1142 tests) passes locally and in a Linux container limited to 2 CPUs running the workflow's lint, build and test steps.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Incremental review of the four commits since e14361e: the refusal line-number fix plus the test changes that answer the previous timing finding.

  • Named the right lines for nested numbered items in edit_doc refusals: the nested lookup now strips the item's own list marker and only accepts a match that starts a line (lineStartOf), with tests over bullet, numbered, numbered-with-start, check and toggle items at depths 2 and 3.
  • Replaced edit_doc's wall-clock bounds with scaling assertions: each operation runs at two sizes (best of three) and the ratio must stay well below the quadratic or cubic prediction, with a 5 ms floor so timer noise cannot inflate it.
  • Cut the by-kind fuzz to 1560 iterations (about 60 per kind), raised its timeout to 180 s, and made each kind's assertions relative to the case count.

Verified on a 4-core runner: npx vitest run in apps/mcp passes 47 files / 1142 tests (fuzz 23.6 s against its 180 s timeout; ratios 4.01, 4.06 and 7.86 against bounds of 9, 9 and 20). The previous ⚠️ about machine-dependent bounds going red on CI is resolved, and the nested line-naming thread is fixed as described.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@pikann pikann left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM! Thank you for the contribution! 🚀

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.

[Feature] Docs: efficient pull/push/content-check for coding agents (change feed, ETags, upsert by path, partial reads)

2 participants