diff --git a/.gitignore b/.gitignore index 5d3920fc..0dbdbc28 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,9 @@ target/ /server/scripts/capture-analysis-*/ # CodeChat Editor lexer: python. See TODO. + +# Local editor, OS, and personal files. +.DS_Store +.idea/ +/app.log +/out/ diff --git a/builder/src/main.rs b/builder/src/main.rs index b212989b..23b53048 100644 --- a/builder/src/main.rs +++ b/builder/src/main.rs @@ -690,7 +690,7 @@ fn run_extensions_build( let distflag = if dist { "--minify" } else { "--sourcemap" }; // The NAPI build. - let mut napi_args = vec!["napi", "build", "--platform", "--output-dir", "src"]; + let mut napi_args = vec!["exec", "napi", "build", "--platform", "--output-dir", "src"]; if dist { napi_args.push("--release"); } @@ -701,7 +701,7 @@ fn run_extensions_build( target = tmp; napi_args.extend(["--target", &target]); } - run_script("npx", &napi_args, VSCODE_PATH, true)?; + run_script("pnpm", &napi_args, VSCODE_PATH, true)?; // Ensure the JavaScript data structures generated from Rust are up to date. run_cmd!( diff --git a/extensions/VSCode/.gitignore b/extensions/VSCode/.gitignore index 65fa2a14..80023e8b 100644 --- a/extensions/VSCode/.gitignore +++ b/extensions/VSCode/.gitignore @@ -33,7 +33,7 @@ static/ # NAPI-RS src/index.d.ts src/index.js -src/codechat-editor-client.win32-x64-msvc.node +src/codechat-editor-client.*.node .windows/ *.log # CodeChat Editor lexer: python. See TODO. diff --git a/review.md b/review.md new file mode 100644 index 00000000..2496d2c8 --- /dev/null +++ b/review.md @@ -0,0 +1,91 @@ +Review: "Fragments in Markdown documents" (round 1) +================================================= + +Section reviewed: "Fragments in Markdown documents" (`cc-JzLRfBr83U`) in +`server/src/processing/cache-spec.md`, checked against the rest of the spec and +the current implementation (`server/src/processing.rs`: `hydrate_html`, +`hydrating_walk_node`, `store_fragment_contents`, `CLEAN_FRAGMENT_HTML`). The +implementation still rejects every fragment in a Markdown document, so this is +a review of the specification only. + +Findings +-------- + +1. **Medium: the opening contradicts the details.** The first paragraph says + that "the rules above don't apply" to a Markdown document, yet the details + say that "the other rules for fragments hold unchanged" (id, `following` + parsing, hoisting, errors, gather elements in the extent). The section + should name the rules it replaces: the extent, what `following` counts, what + `following="0"` encloses, clamping, and the rendered layout (line numbers, + indents, `cc-fragment-*` wrappers). + +2. **Medium: when blocks are counted is ambiguous.** "Blocks are counted in the + rendered HTML" doesn't say before or after hydration. Hydration adds a + top-level `
` after each gather element, which + would change `following` counts and section contents if counted. "Stored + content" implies the count happens before gather lists, but the extent rules + should say so directly: blocks are the top-level nodes of the HTML + translated from the Markdown, after hoisting fragment content and before + cache hydration. Math and diagram hydration replace elements one for one, + so they don't change the count. + +3. **Medium: top-level nodes other than elements aren't covered.** + * A raw HTML block (CommonMark type 7) can leave non-whitespace text at the + top level, e.g. text on the lines after `` alone on a line. Is it + a block, part of a neighboring block, or ignored? + * `` alone on a line, without its closing tag on that line, + is a type 7 HTML block, so the `` element is itself a top-level + node; after hoisting, the text which followed it is top-level too. Which + block "holds the tag" in that case is undefined. + +4. **Minor: trailing whitespace and comments.** "Stored content" says + whitespace and comments between enclosed blocks are kept and those before + the first enclosed block aren't, but says nothing about those after the + last enclosed block. + +5. **Minor: other parts of the spec still describe only source files.** + * The introduction says the cache stores "code/doc blocks for fragments". + * The fragments section says that fragments store "an HTML rendering of the + code and doc blocks they contain" which reproduces the source layout, that + `following="0"` "contains only the current doc block", and that + `following` is clamped to "the number of code/doc blocks". Each should say + "in a source file" or point to the Markdown section, as the paragraph at + the top of that section already does. + +6. **Minor: the test plan omits two needed tests.** + * `test_hydrate_fragment_in_markdown` in `processing/tests.rs` expects the + error "fragments are not allowed in Markdown documents"; the plan should + say it is replaced, not kept. + * The round-trip requirement (a paragraph holding only a `` tag is + saved as its own paragraph) needs a test through + `doc_block_html_to_markdown`, not only through hydration. + +7. **Minor: the section is placed under the implementation gather element.** + The new `h3` follows `

Implementation of + Fragments and gather elements

`, so it reads as part of that gathered + implementation. Put it before that gather element, or make it an `h2` as the + other top-level topics are. + +8. **Nit: tables.** The details mention a tag in a list item or a block quote, + but not a tag in a table cell, which anchors to the whole table by the same + rule. One word would remove the doubt. + +9. **Nit: the examples' notation.** `` mixes the placeholder + `` with an attribute; say once that `` stands for + ``. + +Counts: 9 findings (0 major, 3 medium, 4 minor, 2 nit). + +Verified as correct +------------------- + +* All seven rows of the example table follow from the extent rules. +* `following` accepts surrounding spaces, matching `trim().parse::()` + in `hydrating_walk_node`. +* Removing other fragments' backlinks from the content matches + `CLEAN_FRAGMENT_HTML` (`add_clean_content_tags(["fragment"])`), and keeping + comments matches `strip_comments(false)`. +* Storing content after cross-reference hydration and before gather lists + matches the phase order in `hydrate_html` (`hydrate_dom`, then + `store_fragment_contents`, then `hydrate_gathers`), and keeps + `Fragment::content` in layer 3. diff --git a/server/src/processing.rs b/server/src/processing.rs index 6c02415d..173af2ef 100644 --- a/server/src/processing.rs +++ b/server/src/processing.rs @@ -1018,9 +1018,7 @@ pub fn source_to_codechat_for_web( }, version, source: if lexer.language_lexer.lexer_name.as_str() == MARKDOWN_MODE { - // Document-only files are easy: just encode the contents. Fragments - // aren't supported in Markdown documents; `hydrate_html` reports - // them as errors. + // Document-only files are easy: just encode the contents. let dry_html = markdown_to_html(file_contents); let html = hydrate_html(&dry_html, file_path, &cache) .map_err(|e| SourceToCodeChatForWebError::ParseFailed(e.to_string()))?; @@ -1094,7 +1092,7 @@ pub fn source_to_codechat_for_web( .count(); let dom = doc_blocks_to_dom(&html, doc_block_count) .map_err(|e| SourceToCodeChatForWebError::ParseFailed(e.to_string()))?; - let (dom, walk_context) = hydrate_dom(dom, file_path, &cache, false) + let (dom, walk_context) = hydrate_dom(dom, file_path, &cache) .map_err(|e| SourceToCodeChatForWebError::ParseFailed(e.to_string()))?; // 4. Serialize and split on the separator, giving each doc block's // hydrated HTML -- the form in which fragment contents are @@ -1118,9 +1116,10 @@ pub fn source_to_codechat_for_web( // outdated. store_fragment_contents( &walk_context, - Some((&code_doc_block_arr, &doc_block_html)), + &FragmentSource::CodeDocBlocks(&code_doc_block_arr, &doc_block_html), &cache, - ); + ) + .map_err(|e| SourceToCodeChatForWebError::ParseFailed(e.to_string()))?; // 6. Hydrate gather lists, now that every fragment's content -- // including those defined in this file -- is in the cache. hydrate_gathers(&walk_context, &cache) @@ -1679,13 +1678,13 @@ fn contains_sentinel( /// Phases 1 and 2 update the cache, and each update may outdate other files; /// `Cache::mark_outdated` sees that every outdated file is re-rendered. /// -/// This function runs all three phases for a Markdown document, where phase 2 -/// needs no doc block data (fragments aren't allowed in Markdown documents, so -/// every fragment's content is an error message). +/// This function runs all three phases for a Markdown document, whose fragments +/// enclose top-level blocks of the DOM rather than code/doc blocks; see +/// . fn hydrate_html(html: &str, file: &Path, cache: &Arc>) -> io::Result { let dom = nodes_to_dom(parse_doc_block(html)?)?; - let (dom, walk_context) = hydrate_dom(dom, file, cache, true)?; - store_fragment_contents(&walk_context, None, cache); + let (dom, walk_context) = hydrate_dom(dom, file, cache)?; + store_fragment_contents(&walk_context, &FragmentSource::Markdown(&dom), cache)?; hydrate_gathers(&walk_context, cache)?; dom_to_html(&dom) } @@ -1703,8 +1702,6 @@ fn hydrate_dom( file: &Path, // The cache for the project containing this file. cache: &Arc>, - // True when this is a Markdown document, in which fragments aren't allowed. - is_markdown: bool, // The parsed, patched DOM plus the walk results needed by later phases. ) -> io::Result<(Rc, WalkContext)> { // Everything below treats a `` as empty, so this comes first. @@ -1740,7 +1737,6 @@ fn hydrate_dom( let mut walk_context = WalkContext { facts: FileFacts::default(), path, - is_markdown, auto_ids, doc_block_index: 0, xrefs: Vec::new(), @@ -2073,41 +2069,212 @@ fn fragment_backlinks( Ok(children) } +/// Where a file's fragments take their content from. +enum FragmentSource<'a> { + /// A source file's code/doc blocks, paired with a map from the index of + /// each doc block in that slice to its hydrated HTML. + CodeDocBlocks(&'a [CodeDocBlock], &'a HashMap), + /// A Markdown document's hydrated DOM, whose top-level nodes are its + /// blocks. + Markdown(&'a Rc), +} + /// Phase 2 of hydration: store each fragment's content in the cache, which /// marks the files containing gather elements listing changed fragments as /// outdated. fn store_fragment_contents( // The walk results from `hydrate_dom`. walk_context: &WalkContext, - // The file's code/doc blocks, paired with a map from the index of each doc - // block in that slice to its hydrated HTML. `None` for Markdown documents, - // where every fragment's content is an error message. - blocks: Option<(&[CodeDocBlock], &HashMap)>, + // What the file's fragments enclose. + source: &FragmentSource, // The cache for the project containing this file. cache: &Arc>, -) { - let mut cache_guard = cache.lock().unwrap(); - // The ids whose content this pass has stored. Duplicates within this file - // share one entry in the cache, which holds the first in document order - // (see `Cache::commit_file`); storing each duplicate's content in turn - // would instead change that entry twice per pass, outdating every file - // which gathers the id each time this file is processed. + // An error only if a Markdown fragment's content can't be serialized; the + // cache is then left unchanged by this phase. +) -> io::Result<()> { + // The ids whose content this pass stores. Duplicates within this file share + // one entry in the cache, which holds the first in document order (see + // `Cache::commit_file`); storing each duplicate's content in turn would + // instead change that entry twice per pass, outdating every file which + // gathers the id each time this file is processed. let mut stored_ids: HashSet<&str> = HashSet::new(); + // Render every content before taking the lock, so that a failure leaves the + // cache alone. + let mut contents: Vec<(&str, String)> = Vec::new(); for fragment in &walk_context.fragments { if !fragment.cached || !stored_ids.insert(&fragment.id) { continue; } let content = if let Some(message) = &fragment.error { error_html(message) - } else if let Some((code_doc_blocks, chunks)) = blocks { - render_fragment_content(fragment, walk_context, code_doc_blocks, chunks) } else { - // Unreachable: every fragment in a Markdown document has its - // `error` set during the walk. - error_html("fragments are not allowed in Markdown documents") + match source { + FragmentSource::CodeDocBlocks(code_doc_blocks, chunks) => { + render_fragment_content(fragment, walk_context, code_doc_blocks, chunks) + } + FragmentSource::Markdown(dom) => { + render_markdown_fragment_content(fragment, walk_context, dom)? + } + } }; - cache_guard.update_fragment_content(&walk_context.path, &fragment.id, content); + contents.push((&fragment.id, content)); } + let mut cache_guard = cache.lock().unwrap(); + for (id, content) in contents { + cache_guard.update_fragment_content(&walk_context.path, id, content); + } + Ok(()) +} + +/// Render one fragment of a Markdown document: the cleaned HTML of the +/// top-level blocks it encloses, per . Its +/// cross-references and math are already hydrated, while gather lists aren't +/// yet inserted; the cleaning removes every `` with its backlinks. +fn render_markdown_fragment_content( + // The fragment to render. + fragment: &FragmentHydration, + // The walk results, which locate the document's gather elements. + walk_context: &WalkContext, + // The document's DOM, as `hydrate_dom` returned it. + dom: &Rc, + // The fragment's content, rendered as HTML. +) -> io::Result { + let root = get_dom_root(dom); + let children = root.children.borrow(); + let Some((first, last)) = markdown_fragment_extent(fragment, &root, &children) else { + return Ok(String::new()); + }; + // A fragment may not contain a gather element, even a nested one; see + // `render_fragment_content`. + if walk_context.gathers.iter().any(|gather| { + top_level_index(gather, &root, &children) + .is_some_and(|index| (first..=last).contains(&index)) + }) { + return Ok(error_html("a fragment may not contain a gather element")); + } + let enclosed: Vec> = children[first..=last] + .iter() + .filter(|child| !holds_only_fragments(child)) + .cloned() + .collect(); + let html = nodes_outer_html(&enclosed)?; + Ok(CLEAN_FRAGMENT_HTML.clean(&html).to_string()) +} + +/// True for a paragraph holding only `` tags and whitespace, as a +/// tag alone on its line produces, both as written and after a save closes an +/// unclosed tag. Such a paragraph isn't a block, and isn't part of the content. +fn holds_only_fragments(node: &Rc) -> bool { + get_node_tag_name(node) == Some("p") + && node + .children + .borrow() + .iter() + .all(|child| match &child.data { + NodeData::Element { .. } => get_node_tag_name(child) == Some("fragment"), + NodeData::Text { contents } => contents.borrow().trim_ascii().is_empty(), + _ => false, + }) +} + +/// Find the top-level nodes a Markdown document's fragment encloses, as the +/// indices of the first and last in `children`; `None` if it encloses nothing. +/// A *block* is a top-level element, other than a `` or a paragraph +/// holding only `` tags, or a top-level text node holding more than +/// whitespace; comments and whitespace between blocks are carried along, but +/// not counted. A fragment whose tag isn't in a block (a tag alone on its line, +/// closed or not) begins with the next block. +fn markdown_fragment_extent( + // The fragment. + fragment: &FragmentHydration, + // The DOM's root element. + root: &Rc, + // The root's children. + children: &[Rc], + // The indices into `children` of the first and last enclosed nodes. +) -> Option<(usize, usize)> { + let blocks: Vec = children + .iter() + .enumerate() + .filter(|(_, child)| match &child.data { + NodeData::Element { .. } => { + get_node_tag_name(child) != Some("fragment") && !holds_only_fragments(child) + } + NodeData::Text { contents } => !contents.borrow().trim_ascii().is_empty(), + _ => false, + }) + .map(|(index, _)| index) + .collect(); + let tag_index = top_level_index(&fragment.node, root, children)?; + let anchor = blocks.iter().position(|&index| index >= tag_index)?; + let block_level = |block: usize| heading_level(&children[blocks[block]]); + let last = if let Some(following) = fragment.following { + anchor.saturating_add(following).min(blocks.len() - 1) + } else { + // The level of the section holding the anchor block, or 7 (so that any + // heading ends it) before the document's first heading. + let level = (0..=anchor).rev().find_map(block_level).unwrap_or(7); + (anchor + 1..blocks.len()) + .find(|&block| block_level(block).is_some_and(|other| other <= level)) + .map_or(blocks.len() - 1, |block| block - 1) + }; + Some((blocks[anchor], blocks[last])) +} + +/// The level of a heading element (1 for `

`), or `None` for any other node. +fn heading_level(node: &Rc) -> Option { + match get_node_tag_name(node)? { + "h1" => Some(1), + "h2" => Some(2), + "h3" => Some(3), + "h4" => Some(4), + "h5" => Some(5), + "h6" => Some(6), + _ => None, + } +} + +/// The index in `children` of the top-level node which is or contains `node`; +/// `None` if `node` isn't in the tree under `root`. +fn top_level_index( + // The node to locate. + node: &Rc, + // The DOM's root element. + root: &Rc, + // The root's children. + children: &[Rc], +) -> Option { + let mut current = node.clone(); + loop { + let parent = parent_of(¤t)?; + if Rc::ptr_eq(&parent, root) { + return children + .iter() + .position(|child| Rc::ptr_eq(child, ¤t)); + } + current = parent; + } +} + +/// A node's parent, if it has one. +fn parent_of(node: &Rc) -> Option> { + // Read the parent link non-destructively: `Cell` only supports `take`. + let parent_weak = node.parent.take(); + node.parent.set(parent_weak.clone()); + parent_weak.and_then(|weak| weak.upgrade()) +} + +/// Serialize nodes, each including itself, back to an HTML string. +fn nodes_outer_html(nodes: &[Rc]) -> io::Result { + let mut bytes = vec![]; + for node in nodes { + let so = SerializeOpts { + traversal_scope: TraversalScope::IncludeNode, + ..Default::default() + }; + serialize(&mut bytes, &SerializableHandle::from(node.clone()), so)?; + } + String::from_utf8(bytes).map_err(io::Error::other) } /// Render one fragment's content: the hydrated HTML of the code/doc blocks it @@ -2604,9 +2771,6 @@ struct WalkContext { facts: FileFacts, /// The canonicalized path of the file being hydrated. path: PathBuf, - /// True when hydrating a Markdown document, in which fragments aren't - /// allowed. - is_markdown: bool, /// The ids `assign_auto_ids` generated for this file's `id="*"` elements. /// These are excluded from `facts`: they belong to the cache only after the /// file carrying them is written and re-read. @@ -2645,9 +2809,11 @@ struct FragmentHydration { /// number of blocks in the document; see /// `FragmentFact::code_doc_block_end_index`. end: usize, + /// The value of the `following` attribute, if present and valid. A Markdown + /// document's fragment without one encloses the rest of its section. + following: Option, /// When set, the fragment is in an error state detected during the walk (a - /// missing or invalid id, a fragment in a Markdown document, or an - /// unparsable `following` attribute): the message replaces both the + /// missing or invalid id, or an unparsable `following` attribute): the message replaces both the /// hydrated tag content and the cached fragment content. error: Option, /// False when the fragment wasn't recorded in `FileFacts` (its id is @@ -2687,15 +2853,17 @@ fn hydrating_walk_node(node: &Rc, mut walk_context: WalkContext) -> io::Re // aren't finalized during the walk -- so the caller stores it // later via `Cache::update_fragment_content`. if let Some(id) = id.filter(|id| !id.is_empty()) { - // The `following` attribute selects how many code/doc - // blocks after the current doc block the fragment encloses; - // the default is 1. + // The `following` attribute selects how many blocks after + // the first one the fragment encloses: code/doc blocks after + // the current doc block in a source file (default 1), or + // top-level blocks after the anchor block in a Markdown + // document (default: the rest of the section). let (following, following_error) = match get_attr_value(child, "following") { - None => (1, None), + None => (None, None), Some(following) => match following.trim().parse::() { - Ok(count) => (count, None), + Ok(count) => (Some(count), None), Err(_) => ( - 0, + Some(0), Some(format!( "the \"following\" attribute (\"{following}\") must be a whole number" )), @@ -2708,21 +2876,18 @@ fn hydrating_walk_node(node: &Rc, mut walk_context: WalkContext) -> io::Re // during this pass, which is otherwise hydrated normally // (nothing can reference an id no file contains yet, so its // backlinks are empty). - let (error, cached) = if !is_css_identifier(&id) { + let (error, cached) = if is_css_identifier(&id) { + (following_error, true) + } else { ( Some(format!("\"{id}\" is not a valid CSS identifier")), false, ) - } else if walk_context.is_markdown { - ( - Some("fragments are not allowed in Markdown documents".to_string()), - true, - ) - } else { - (following_error, true) }; let cached = cached && !walk_context.auto_ids.contains(&id); - let end = walk_context.doc_block_index.saturating_add(following); + let end = walk_context + .doc_block_index + .saturating_add(following.unwrap_or(1)); if cached { walk_context.facts.fragments.push(FragmentFact { id: id.clone(), @@ -2736,6 +2901,7 @@ fn hydrating_walk_node(node: &Rc, mut walk_context: WalkContext) -> io::Re id, start: walk_context.doc_block_index, end, + following, error, cached, }); @@ -2748,6 +2914,7 @@ fn hydrating_walk_node(node: &Rc, mut walk_context: WalkContext) -> io::Re id: String::new(), start: walk_context.doc_block_index, end: walk_context.doc_block_index, + following: None, error: Some("a fragment requires an \"id\" attribute".to_string()), cached: false, }); diff --git a/server/src/processing/cache-spec.md b/server/src/processing/cache-spec.md index 704d8cf5..9aa2f8f9 100644 --- a/server/src/processing/cache-spec.md +++ b/server/src/processing/cache-spec.md @@ -20,8 +20,9 @@ CodeChat Editor. If not, see Cache spec ========== -The cache stores the location (file name and ID) and content (inner HTML or -code/doc blocks for fragments) of targets and fragments. Targets are HTML +The cache stores the location (file name and ID) and content (inner HTML, or +for fragments the enclosed code/doc blocks or Markdown blocks) of targets and +fragments. Targets are HTML elements (excluding ``s and ``s) with an ID. The goal of the cache is to support cross-references and gather elements, and to @@ -142,12 +143,12 @@ example fragment tag, after cache hydration: `See Bazzy things, Zappy things`. A fragment's content by default includes the content of the current doc block and the content -of the following code/doc block; fragments are not allowed in Markdown documents -(in this case, the fragment content consists of an error message). Fragments may -include the `following` attribute to enclose a specific number of the following -code/doc blocks; for example, `` -includes the current doc block along with the next 3 code/doc blocks; -`following` must be a whole number. +of the following code/doc block. In a Markdown document, a fragment's extent +is instead defined by the document's structure; see +. Fragments may include the `following` +attribute to enclose a specific number of the following code/doc blocks; for +example, `` includes the current doc +block along with the next 3 code/doc blocks; `following` must be a whole number. Details: @@ -161,7 +162,7 @@ Details: the resulting output for this in the list of fragments is an error message. * If a gather element refers to an `id` that wasn't found or is a duplicate, its content will be replaced by an error message. -* Fragments store an HTML rendering of the code and doc blocks they contain, +* Fragments store an HTML rendering of the blocks they contain, excluding the content produced by hydrating the `` tags, to avoid duplication and circular dependencies. Cross-references in this rendering are hydrated in the fragment's file, so their links lead from there; a gather @@ -169,8 +170,8 @@ Details: gather element's file instead. An error message reads the same anywhere, so it's kept as is. See layer 4 under : this exclusion is what keeps a gather element and the fragments it lists from - outdating each other forever. The HTML rendering of a fragment reproduces the - layout of the source it came from: each doc block includes its indent, each + outdating each other forever. The HTML rendering of a source file's fragment + reproduces the layout of the source it came from: each doc block includes its indent, each line of a code block or the first line of a doc block is preceded by that line's number, and the two are aligned -- a doc block and a line of code indented equally in the source begin in the same column, with the line numbers @@ -184,9 +185,10 @@ Details: after the fragment's closing tag. Otherwise, the next save would erase it; this avoids data loss when a user first creates a fragment tag, but hasn't closed it. -* A `` is valid; it contains only the current doc block. -* The `following` attribute is clamped if it would exceed the number of code/doc - blocks in the document. +* A `` is valid; in a source file, it contains only the + current doc block. +* The `following` attribute is clamped if it would exceed the number of blocks + remaining in the document (code/doc blocks in a source file). * If the `following` value cannot be parsed to a whole number, an error message replaces the fragment content. * A gather element, as a type of `Target`, requires an `id`. A `data-gather` @@ -221,6 +223,239 @@ things

`: Implementation of Fragments and gather elements +

Fragments in Markdown documents

+ +A `` may be defined in a Markdown document as well as in a source +file. The rules below replace the source-file rules in + for fragment extent, what `following` counts, +what `following="0"` contains, clamping `following`, and gather-list layout. +All other rules in that section apply unchanged. They don't apply to Markdown +inside a source file's doc blocks: a fragment there encloses code/doc blocks, +even when its doc block contains headings. + +### Fragment boundaries + +Boundaries are computed on the HTML translated from Markdown, after content +placed inside a `` tag is moved after it and after `` and +backlink hydration, but before gather lists are inserted, so the `
` a +gather element hydrates to never counts as a block. Math and diagram rendering +replace elements one for one, so they don't change the count. + +* A *top-level block* is an element child of that HTML's root, other than a + `` or a paragraph holding only `` tags and whitespace. + Text holding only ASCII whitespace between blocks is ignored. Examples include + paragraphs, headings, lists (with all their items), tables, block quotes, code + blocks, thematic breaks, and elements written in raw HTML. One raw HTML block + in the Markdown may therefore produce several top-level blocks. +* Top-level nodes other than elements: + * A top-level text node which isn't whitespace-only, such as text a raw HTML + block leaves after an inline tag, counts as a block. + * A `` tag written alone in its own paragraph, separated from + neighboring text by blank lines, with or without its closing tag, isn't a + block: written unclosed, the tag is itself at the top level; closed, it + forms a paragraph holding only the tag. A tag on a line directly before or + after paragraph text belongs to that paragraph, as Markdown joins them. Its + anchor block is the next block after it, and the paragraph isn't part of any + content. Saving closes an unclosed tag, so this rule keeps the extent across + a save. If no block follows the tag, the fragment encloses nothing; this is + not an error. + * Comments never count as blocks. Those between enclosed blocks are kept in + the content; those before the first or after the last enclosed block + aren't. +* A *heading* is an `

`-`

` top-level block, whether written in Markdown + or HTML. Gather elements written as headings therefore count as headings. A + heading nested in a block quote, a list, or a raw HTML container such as + `
` isn't top-level, so it bounds nothing. +* The *anchor block* is the top-level block which contains the `` + tag. A tag inside a list item, table cell, or block quote anchors to the + whole list, table, or block quote, so `following="0"` there still encloses + the whole list, table, or block quote. A `` tag in a code span or + fenced code block is text, so it defines no fragment. + +A fragment's extent is: + +* **Without `following`: the anchor block through the end of its section.** + The extent starts at the anchor block itself, not at the section's heading, + so blocks before the tag are never enclosed. It ends just before the next + heading of the same or a higher level (`#` is the highest) than the nearest + heading at or before the anchor block, or at the end of the document. + Subsections belong to the fragment. If no heading is at or before the anchor + block, the extent ends just before the next heading of any level. +* **With `following="n"`: the anchor block and the next `n` top-level blocks**, + without treating headings as boundaries. `following` is clamped, and an + unparsable value is an error, as in a source file. + +The recommended placement is in a heading, as in `## Parsing `: the fragment then encloses that heading and its whole +section, subsections included. A tag alone in its own paragraph starts with +the next block, so `following` counts from that block. + +The blocks in the extent are cleaned like any other fragment content (see +); in particular, each `` is removed +with its backlinks, so a block which also held other text keeps only that text. +A gather element shows a Markdown fragment's content as the document's own HTML +after cleaning: without the line numbers, indents, or `cc-fragment-*` layout +wrappers of a source file's fragment. A gathered heading keeps its level and, +since cleaning strips its `id`, isn't a cross-reference target; cross-references +in the content link from the gathering file, as for any fragment. + +### Dependencies + +A Markdown fragment adds no new layer and no new kind of dependency; the +existing machinery in covers it: + +* The extent depends only on the document's own source, so `Fragment::content` + stays in layer 3: it is computed after `` hydration (layer 2). It + doesn't depend on backlinks (layer 4), which are hydrated before it but + removed by cleaning, or on gather lists (layer 5), which are inserted + afterwards. +* Any edit which changes the extent or the enclosed blocks -- adding a block to + the section, changing a heading's level, adding a heading which ends the + section earlier -- changes `Fragment::content`, which outdates every file in + the fragment's `dependents`, as for a source file. +* A cross-reference inside the extent makes the document a dependent of its + target, so a change to the target outdates the document, which changes the + fragment's content and in turn outdates the gathering files: the indirection + chain C → B → A, unchanged. +* Backlinks follow the reverse edge described under "Gather elements: the + reverse edge"; whether the fragment lives in a Markdown document or a source + file doesn't matter to it. +* A gather element in the same document as a fragment it lists needs no special + case: fragment contents are stored before gather lists are hydrated, so the + list sees the content from the same pass. + +### Interaction with gather elements + +* A gather element in any file may list fragments from Markdown documents and + source files alike. +* A gather element inside a fragment's extent is an error, as in a source file: + each gather element which lists that fragment shows an error message for it. + A gather heading at the same or a higher level than the section's heading is + not inside the section; it ends it. A gather element nested in a block quote + is inside the extent as well. A `following` which stops before a gather + element avoids the error, but one in the anchor block can't be excluded; move + the tag to another block. +* The `` tag hydrates to backlinks in place, exactly as in a source + file, and those backlinks are excluded from `Fragment::content` (layer 4). +* Extents may overlap; for example, two fragments without `following` in the + same section end at the same place, and the earlier one also encloses the + later one's blocks. + +### Errors + +This section adds no new error; a fragment in a Markdown document is valid. The +existing errors apply unchanged: a missing or invalid `id`, a duplicate `id`, an +unparsable `following`, and a gather element inside the extent. A fragment which +encloses nothing, such as a tag alone on the last line of a document, is not an +error; its stored content is empty, so a gather list shows only its "From …:" +link. + +### Saving and reopening + +Boundaries aren't stored. They're recomputed from the saved Markdown each time +the document is translated, so the saved source holds only the `` tag +the user wrote. Dehydration removes the backlinks and `contenteditable`, as in a +source file, and the Faithful translation mode of the HTML-to-Markdown +conversion keeps the tag as inline raw HTML (attribute order may change). An +`id="*"` is replaced as described in auto-assignment of ids. + +The round trip must keep the tag in the same top-level block. In particular, a +paragraph which holds only a `` tag must be saved as its own +paragraph, not merged into a neighbor, and an unclosed tag alone in its own +paragraph is saved closed, as a paragraph holding only the tag; neither is a +block. Reopening the file then reproduces the same extent. Edits which add, +remove, or change the level of a heading, or add or remove blocks, change the +extent on purpose. The resulting change to `Fragment::content` outdates gather +elements listing the fragment by the existing rules. + +### Examples + +Each example below is a separate document. + +```markdown +Intro text. + +## Install + + + +Run `./bt install`. + +### Windows + +* Install `pwsh` first. +* Then rerun the command. + +## Run +``` + +* `intro`: no heading precedes it, so it contains `Intro text.` and stops at + `## Install`. +* `install`: from the paragraph which held the tag through the end of the + `## Install` section: "Run `./bt install`.", `### Windows`, and its list, + stopping at `## Run`. The heading `## Install` precedes the tag, so it isn't + enclosed, and the paragraph holding only the tag isn't a block. +* `bt`: only the paragraph "Run `./bt install`.", keeping the code formatting. +* `win`: the whole two-item list, since the list is the anchor block. + +```markdown +## Design + +Rationale. + +

Notes

+``` + +* `design` contains the gather element `notes`, so every gather element listing + `design` shows an error for it. Writing `following="1"` instead limits it to + the heading and `Rationale.`. + +```markdown +### Parsing + +> #### Note +> +> Quoted text. + +#### Tokens + +## Output +``` + +* `parsing`: the heading `### Parsing`, the block quote, and `#### Tokens`, + stopping at `## Output`. The `####` heading inside the block quote isn't + top-level, so it neither ends the section nor counts as a heading. + +### Rationale + +The tag stays a single empty element, as in a source file, so hoisting, backlink +hydration, dehydration, and the HTML-to-Markdown round trip on save need no +change; a paragraph holding only tags isn't a block, so closing a tag on save +doesn't move an extent. The extent follows the outline a reader already sees, so +paragraphs added to a section join the fragment without edits, and no closing +tag can go missing. A narrower fragment is written with `following`. The cost is +that a tag in a long section may enclose more than intended, and that a +`following` count shifts when blocks are inserted; the gathered content shows +the rest of the section, which prompts the author to add `following`. Starting +at the tag rather than at the section's heading lets a fragment skip a section's +introduction; a tag in the heading still encloses the whole section. Showing the +document's cleaned HTML keeps a quotation from a Markdown document looking like +that document, since it has no source lines to number or indent. + +### Tests + +The unit tests translate a Markdown document through the same entry point as a +source file and compare the complete stored content, or check that no fragment +is stored. The tests are `test_markdown_fragment_*` in `processing/tests.rs`. +They cover the examples above literally (`_spec_examples`), `following` values, +a tag alone in its own paragraph (closed or not) and one with no block after it +(`_extent`), errors, a tag in code, and an invalid `id` (`_errors`), a gather +element in the extent, also nested and in the anchor block (`_gather`), raw HTML +headings, a heading nested in a block quote, and a block added to a section +(`_extent`, `_gathered`). Round-trip tests (`_round_trip`), including an +unclosed tag, go through the HTML-to-Markdown conversion on save, not only +through hydration. + Search (future work) -------------------- @@ -291,10 +526,11 @@ to track dependents of an id, so that files containing these dependencies can be marked `Outdated` (see below); these are sent to the `Cache::consumer_tx` channel for processing. Dependencies are tracked at file granularity, on the id rather than on the item defining it: `IdEntry::dependents` is the set of files -whose rendered output depends on this id, by any means -- an `` -or a `data-gather` list naming it. One uniform set suffices in all three -`IdState`s because the typical action taken on a dependent is marking this file -outdated (fragments also use their dependents to generate "See x" links). +whose rendered output depends on this id, by either means -- an +`` or a `data-gather` list naming it. One uniform set +suffices in all three `IdState`s because the typical action taken on a +dependent is marking this file outdated (fragments also use their dependents to +generate "See x" links). Updating dependencies requires a definition of what constitutes a difference which would trigger outdating dependencies. The state which is checked for @@ -389,6 +625,9 @@ HTML stored as cross-reference optional content, `Target` inner HTML, or as * `Fragment` content must preserve the `data-content` attribute of each ``, since a gather element re-hydrates the `` from it so that its link leads from the gather element's file. +* `Fragment` content removes each `` together with its contents (its + backlinks), keeps comments, strips `data-gather`, and keeps `contenteditable` + only on `` and ``, and only when its value is `false`.
Implementation of HTML cleaning diff --git a/server/src/processing/cache.rs b/server/src/processing/cache.rs index 5af223a6..b4f16da6 100644 --- a/server/src/processing/cache.rs +++ b/server/src/processing/cache.rs @@ -269,7 +269,8 @@ pub(super) struct Xref { /// `Target`, the id is the key of `FileEntry::fragments` and the containing /// file is the entry holding this value. pub(super) struct Fragment { - /// The code/doc block content of this element rendered as HTML. This is + /// The content this element encloses rendered as HTML: code/doc blocks in a + /// source file, or top-level blocks in a Markdown document. This is /// empty until the fragment's doc blocks are finalized and the caller /// stores the result via `Cache::update_fragment_content`. pub(super) content: String, @@ -928,7 +929,7 @@ impl Cache { path: &Path, // The fragment's id. id: &str, - // The fragment's code/doc block content, rendered as HTML. + // The fragment's content, rendered as HTML. content: String, // The files (other than `path`) marked outdated by this change, as // described by `CommitOutcome::outdated`. diff --git a/server/src/processing/tests.rs b/server/src/processing/tests.rs index a9f1e37c..e7d9d158 100644 --- a/server/src/processing/tests.rs +++ b/server/src/processing/tests.rs @@ -2894,25 +2894,281 @@ fn test_duplicate_fragment_in_one_file() { assert!(content.contains("First.") && !content.contains("Second.")); } -// Verify that a fragment in a Markdown document is an error. +// Translate a Markdown document, returning the content cached for the given +// fragment, or `None` if no content is cached for it. +fn markdown_fragment_content(markdown: &str, id: &str) -> Option { + let cache = Arc::new(Mutex::new(Cache::default())); + source_to_codechat_for_web( + markdown, + Path::new("foo.md"), + 0.0, + false, + Some(cache.clone()), + ) + .unwrap(); + let cache = cache.lock().unwrap(); + cache + .files + .get(Path::new("foo.md")) + .and_then(|file| file.fragments.get(id)) + .map(|fragment| fragment.content.clone()) +} + +// Verify the extent of a fragment in a Markdown document, per the examples in +// the cache spec's "Fragments in Markdown documents". #[test] -fn test_hydrate_fragment_in_markdown() { +fn test_markdown_fragment_extent() { + for (markdown, content) in [ + // A tag in a heading encloses its section, subsections included. + ( + "# T\n\nIntro.\n\n## A \n\nOne.\n\n### A.1\n\nTwo.\n\n## B\n\nThree.\n", + "

A

\n

One.

\n

A.1

\n

Two.

", + ), + // A tag in a paragraph begins with that paragraph. + ( + "## A\n\nSkipped.\n\nKept. \n\n* A list.\n\n# B\n", + "

Kept.

\n
    \n
  • A list.
  • \n
", + ), + // A lower heading ends nothing; a higher one ends the section. + ( + "### C \n\n#### C.1\n\n## D\n", + "

C

\n

C.1

", + ), + ( + "## A \n\n## B\n\nText.\n", + "

A

", + ), + // A tag in a list item anchors to the whole list; before the first + // heading, any heading ends the fragment. + ( + "* First.\n* Second \n\nAfter.\n\n###### Low\n", + "
    \n
  • First.
  • \n
  • Second
  • \n
\n

After.

", + ), + // `following` counts blocks, headings included. + ( + "Start. \n\n## H\n\nAfter.\n", + "

Start.

", + ), + ( + "Start. \n\n## H\n\nAfter.\n\nEnd.\n", + "

Start.

\n

H

\n

After.

", + ), + // `following` is clamped at the end of the document. + ( + "Start. \n\nEnd.\n", + "

Start.

\n

End.

", + ), + // A raw HTML heading bounds a section; one in a block quote doesn't. + ( + "## A \n\n> ## Quoted\n\n

B

\n\nAfter.\n", + "

A

\n
\n

Quoted

\n
", + ), + // Content inside the tag moves after it and is part of the content. + ( + "Start inside.\n\nEnd.\n", + "

Start inside.

", + ), + // A tag alone on its line, closed or not, isn't a block: it begins + // with the next block. + ( + "\n\nNext.\n\nEnd.\n", + "

Next.

", + ), + ( + "\n\nNext.\n\nEnd.\n", + "

Next.

", + ), + // A tag with no block after it encloses nothing, without an error. + ("Text.\n\n\n", ""), + // Other fragments' backlinks, ids, and comments between blocks are + // cleaned as for a source file. + ( + "

A

\n\n\n\nText. \n", + "

A

\n\n

Text.

", + ), + ] { + assert_eq!( + markdown_fragment_content(markdown, "f").as_deref(), + Some(content), + "{markdown}" + ); + } +} + +// Verify the examples in the cache spec's "Fragments in Markdown documents" +// literally. +#[test] +fn test_markdown_fragment_spec_examples() { + let install = "Intro text. \n\n## Install\n\n\n\nRun `./bt install`. \n\n### Windows\n\n* Install `pwsh` first. \n* Then rerun the command.\n\n## Run\n"; + let list = + "
    \n
  • Install pwsh first.
  • \n
  • Then rerun the command.
  • \n
"; + let run = "

Run ./bt install.

"; + let design = "## Design \n\nRationale.\n\n

Notes

\n"; + let parsing = "### Parsing \n\n> #### Note\n>\n> Quoted text.\n\n#### Tokens\n\n## Output\n"; + for (markdown, id, content) in [ + (install, "intro", "

Intro text.

".to_string()), + (install, "install", format!("{run}\n

Windows

\n{list}")), + (install, "bt", run.to_string()), + (install, "win", list.to_string()), + ( + design, + "design", + "a fragment may not contain a gather element" + .to_string(), + ), + ( + &design.replace("id=\"design\">", "id=\"design\" following=\"1\">"), + "design", + "

Design

\n

Rationale.

".to_string(), + ), + ( + parsing, + "parsing", + "

Parsing

\n
\n

Note

\n

Quoted text.

\n
\n

Tokens

".to_string(), + ), + ] { + assert_eq!( + markdown_fragment_content(markdown, id).as_deref(), + Some(content.as_str()), + "{id}" + ); + } +} + +// Verify that a fragment tag in code defines no fragment, and that an invalid +// id or `following` value is an error, as in a source file. +#[test] +fn test_markdown_fragment_errors() { assert_eq!( - source_to_codechat_for_web( - "", - Path::new("foo.md"), - 0.0, - false, - None + markdown_fragment_content("``\n", "f"), + None + ); + assert_eq!( + markdown_fragment_content("```\n\n```\n", "f"), + None + ); + assert_eq!( + markdown_fragment_content("Text \n", "1f"), + None + ); + assert_eq!( + markdown_fragment_content("Text \n", "f") + .as_deref(), + Some( + "the \"following\" attribute (\"x\") must be a whole number" + ) + ); +} + +// Verify that a gather element among the enclosed blocks, even a nested one, +// makes the fragment's content an error, and that a `following` which stops +// before it avoids the error. +#[test] +fn test_markdown_fragment_gather() { + let error = "a fragment may not contain a gather element"; + for (markdown, content) in [ + ( + "## A \n\nText.\n\n

G

\n", + error, ), - Ok(build_codechat_for_web( - MARKDOWN_MODE, - "

fragments are not allowed in Markdown documents", - vec![] - )) + ( + "## A \n\n> G\n", + error, + ), + ( + "## A \n\nText.\n\n

G

\n", + "

A

\n

Text.

", + ), + // A gather element in the anchor block can't be excluded. + ( + "Text G \n", + error, + ), + ] { + assert_eq!( + markdown_fragment_content(markdown, "f").as_deref(), + Some(content), + "{markdown}" + ); + } +} + +// Verify that a gather element in one Markdown document lists a fragment from +// another, which renders a backlink to it, and that adding a block to the +// fragment's section outdates the gathering file. +#[test] +fn test_markdown_fragment_gathered() { + let cache = Arc::new(Mutex::new(Cache::default())); + let translate = |source: &str, path: &str| { + let translation = + source_to_codechat_for_web(source, Path::new(path), 0.0, false, Some(cache.clone())) + .unwrap(); + let CodeMirrorDiffable::Plain(code_mirror) = translation.source else { + panic!("No diff!"); + }; + code_mirror.doc + }; + let gathering = "

Gathered

\n"; + let fragment = "## A \n\nOne.\n"; + translate(fragment, "b.md"); + assert_eq!( + translate(gathering, "a.md"), + "

Gathered

A

One.

" + ); + assert_eq!( + translate(fragment, "b.md"), + "

A See Gathered

One." + ); + translate( + "## A \n\nOne.\n\nTwo.\n", + "b.md", + ); + assert_eq!( + cache.lock().unwrap().files[Path::new("a.md")].status, + FileStatus::Outdated ); } +// Verify that saving a Markdown document keeps each fragment tag in its block, +// including a tag alone in its own paragraph or left unclosed, so that +// reopening it reproduces the same extent. (Level 1 and 2 headings are saved as setext headings.) +#[test] +fn test_markdown_fragment_round_trip() { + for (source, saved) in [ + ( + "## A \n\nOne.\n\n## B\n", + "A \n------------------------------\n\nOne.\n\nB\n-\n", + ), + ( + "Before.\n\n\n\nAfter.\n\nEnd.\n", + "Before.\n\n\n\nAfter.\n\nEnd.\n", + ), + ( + "* First.\n* Second \n\nAfter.\n", + "* First.\n* Second \n\nAfter.\n", + ), + // Saving closes an unclosed tag alone on its line; the extent is kept. + ( + "\n\nNext.\n\nEnd.\n", + "\n\nNext.\n\nEnd.\n", + ), + ] { + let save = |source: &str| { + codechat_for_web_to_source( + &source_to_codechat_for_web(source, Path::new("foo.md"), 0.0, false, None).unwrap(), + ) + .unwrap() + }; + assert_eq!(save(source), saved, "{source}"); + assert_eq!(save(saved), saved, "{saved}"); + assert_eq!( + markdown_fragment_content(saved, "f"), + markdown_fragment_content(source, "f"), + "{source}" + ); + } +} + // Verify that a fragment without an id -- whether its `id` attribute is missing // or empty -- hydrates to an error message requesting the id. Dehydration // removes the message, so saving the hydrated result writes back a bare diff --git a/submission.md b/submission.md new file mode 100644 index 00000000..dc2fdb43 --- /dev/null +++ b/submission.md @@ -0,0 +1,354 @@ +Project 2 submission +==================== + +Repeat the following block for each team member. + +Team member: Arsen Zhexenbiyev (GitHub: Arsen-kbtu) +--------------------------------------------------- + +### Contribution (5 points) + +Reviewed and revised the team's earlier "Inline inclusion of fragments" section +of `server/src/processing/cache-spec.md` (commits `3061a13` and `8808984`), +which the team later replaced with "Fragments in Markdown documents", and +verified that the project builds and runs on Windows. + +### Build and run check (5 points) + +Prompt: "Verify that you can build and run the project in the current git repo." + +Summary of the LLM's output (Claude Opus 5.5, Windows 10, Rust/cargo 1.100.0, +Node.js 20.11.1): + +* `./bt install` installed pnpm and the Client and VSCode extension npm + packages, and fetched all crates. It then failed at installing cargo-binstall, + since that step requires `pwsh` (PowerShell 7), which isn't installed. + `cargo-nextest`, which the build requires, was installed instead with `cargo + install cargo-nextest --locked`; the other tools (cargo-dist, cargo-audit, and + so on) aren't needed to build. +* `./bt build` built the Rust workspace (server and standalone binary; one + `unreachable_code` warning and two unused-dependency warnings), passed the 13 + `export_bindings` tests, and bundled the Client with esbuild. It then failed + at `node HashReader.js`: Node 20 can't read `package.json5`, so it didn't + treat the ES module as one. Rerunning with + `NODE_OPTIONS=--experimental-detect-module` built the Client and passed `tsc + -noEmit`. +* The VSCode extension build (`npx napi build`) still failed: `@inquirer/core` + imports `util.styleText`, which Node 20.11 lacks. CI uses Node 26; upgrading + Node is required to build the extension. +* Running `target/debug/codechat-editor-standalone --port 8080 serve` started + the server: `/ping` returned `pong`, `/` redirected to the file browser + `/fw/fsb/`, and opening `README.md` through it returned the Client page (HTTP + 200). The standalone server and Client build and run; the VSCode extension + does not build with Node 20. + +### Review rounds (10 points) + +The section reviewed is "Inline inclusion of fragments" in +`server/src/processing/cache-spec.md`, as of commit `8808984`. The team later +replaced that section with "Fragments in Markdown documents", so neither it nor +this review's `review.md` is in the current branch; both are in `8808984`. + +| Round | Findings | Main changes made | +| ----- | -------- | ----------------- | +| 1 | 10 (4 major, 2 medium, 3 minor, 1 nit); see `review.md`. Major: the hydrated form lost `ref`; block inclusion was unreachable and produced a `div` inside a `p`; ``s in included content linked from the wrong file; Markdown support was left open. | Kept `` in every hydrated form and defined dehydration for each; redefined block inclusion as a top-level `

` replaced by a `div`; required `` re-hydration as in gather lists; allowed `` in Markdown documents; added TinyMCE and sanitizer requirements; completed the flattening rules; fixed the example; added layer 6 and `` to the cache-design section. | + +### Last review (10 points) + +Prompting Claude Opus 5.5 (Claude Code), high effort, with `Review the spec +and make the changes` (the original prompt was in Russian: "сделай ревью +спеки и внеси изменения") produced the following findings, saved in +`review.md` at commit `8808984`, for the section "Inline inclusion of fragments" in +`server/src/processing/cache-spec.md`; strikethrough indicates LLM output +that I deemed incorrect or irrelevant. + +1. **Major: the hydrated form loses `ref`.** The example hydrates `` to a bare ``, and dehydration + is said to leave ``. With the `` + element gone, dehydration has no way to recover the `ref`; the first save + would erase the include. `` avoids this by keeping its element in the + hydrated form. + +2. **Major: block inclusion (case 2) can never occur, and its output is invalid + HTML.** Doc blocks and Markdown documents are Markdown, so an `` + alone on a line parses as `

` (see + `test_hydrate_fragment_in_markdown` for ``). The include is never + "the only content of its doc block"; its host is always a `

`. Inserting + the proposed `

` inside that `

` is invalid, and the HTML parser would + split the paragraph. + +3. **Major: cross-references in included content link from the wrong file.** + `Fragment::content` hydrates each `` relative to the fragment's file. + A gather list re-hydrates them from `data-content` (layer 5); the include + section doesn't, so relative links break whenever the including file is in + a different directory. + +4. **Major: Markdown is left as an open question.** The branch is " + for Markdown", yet whether `` works in Markdown documents is left + open. Markdown documents can't define fragments, so including fragments + from source files is the main way a Markdown document can use them. The + spec should allow it and describe the round trip through the + HTML-to-Markdown conversion. + +5. **Medium: the Client and sanitizer requirements are missing.** `include` is + in neither the TinyMCE `custom_elements` and `extended_valid_elements` lists + nor the Server's Ammonia allowlist (`AMMONIA_OPTIONS`), so the element would + be stripped before hydration or dropped by the Client. + +6. **Medium: the flattening rules (case 1) are incomplete.** + * They say nothing about elements that are neither block wrappers nor the + listed inline formatting (diagrams, `iframe`, images, display math). + * They don't cover an `` inside a link, which would produce nested + `` elements. + * They don't cover an `` inside `` optional content. + * Empty blocks aren't dropped. In the spec's own example, the fragment's + doc block also holds the `` tag, whose paragraph is empty after + cleaning. Without trimming, this adds a stray space. + +7. **Minor: the example is ambiguous.** A fragment includes the *following* + code/doc block by default. The example doesn't say what follows the `

`, + so if a doc block follows, its text would be included too. Use + `following="0"` or say that a code block follows. + +8. **Minor: the rest of the spec isn't updated.** + * The cache-design layer list stops at 5, even though this section + introduces "layer 6". + * The definition of `IdEntry::dependents` lists only `` and + `data-gather` as ways to depend on an id. + * The fragments section still says only that fragments aren't allowed in + Markdown. + * The new `h2` has no `id`, unlike the other `h2`s, so it can't be + cross-referenced. + +9. **Minor: same-file ordering is asserted, not explained.** "Including a + fragment from the same file needs no special case" holds only if include + hydration runs after the file's own fragments are committed, as gather-list + hydration does. The case of a fragment including itself isn't mentioned. + +10. **Nit: the error rules don't match the fragment rules.** A `ref` that is + empty should be treated like a missing one, matching the rule for a + fragment's `id`. + + +Team member: Aruzhan Matzhan (GitHub: ar_matzhan) +------------------------------------------------- + +### Contribution (5 points) + +Wrote and revised the "Fragments in Markdown documents" section of +`server/src/processing/cache-spec.md`, implemented it in +`server/src/processing.rs` with Markdown fragment tests, and ran its two review +rounds. + +### Build and run check (5 points) + +Prompt: "Verify that you can build and run the project in the current git repo." + +Summary of the LLM's output (Claude Opus 5.5, macOS 26.4 on Apple Silicon, +Rust/cargo 1.99.1, Node.js 26.4.0, npm 11.17.0; dependencies were already +installed by an earlier `./bt install`): + +* `./bt build` succeeded with exit code 0. It built the Rust workspace and + passed the 13 `export_bindings` tests on both runs (199 skipped). It bundled + the Client with esbuild and passed `tsc -noEmit`. It also built the VSCode + extension's native module with napi + (`codechat-editor-client.darwin-arm64.node`), bundled `extension.js`, and + passed `tsc -noEmit` there. The only warnings were cargo's notes that it + ignores the `min-publish-age` settings. +* `cargo nextest run --lib` in `server/`: 161 tests passed, 1 skipped, + including the new Markdown fragment tests. +* `target/debug/codechat-editor-standalone --port 8085 serve` started the + server. `/ping` returned `pong`, `/` redirected (307) to the file browser + `/fw/fsb/`, and opening `README.md` through it returned the CodeChat Editor + page (HTTP 200). `stop` shut the server down cleanly. + +### Review rounds (10 points) + +The section reviewed is "Fragments in Markdown documents" (`cc-JzLRfBr83U`) in +`server/src/processing/cache-spec.md`, checked against the rest of the spec and +`server/src/processing.rs`. All rounds used Claude Opus 5.5. These rounds are +numbered separately from Dustin's rounds 1-3 below. They review the section +after it was rewritten and implemented on this branch. + +| Round | Findings | Main changes made | +| ----- | -------- | ----------------- | +| 1 | 9 (0 major, 3 medium, 4 minor, 2 nit); see `review.md`. Medium: the opening contradicted the details; it didn't say when blocks are counted relative to hydration; top-level non-element nodes and an unclosed `` were undefined. | Named the source-file rules the section replaces and excluded Markdown in source-file doc blocks; computed boundaries before cache hydration; defined top-level text, unclosed tags, and comments; marked the intro and fragments section as source-file only; mentioned table cells; made the section an `h2`; wrote examples with full tags. | +| 2 | 7 necessary (0 major, 1 medium, 4 minor, 2 nit), 5 optional; see below. Medium: saving an unclosed top-level `` closes it, which may move a `following="0"` extent on reopening (unverified, no test). | Fixed finding 1 with option (a): a paragraph holding only `` tags isn't a block. Corrected the phase order (after `` and backlink hydration, before gather lists); added the fragment-content cleaning rules to "HTML cleaning"; replaced "contributes nothing" and "verbatim"; defined a tag with no block after it; rewrote the Tests subsection. Also adopted the optional suggestions: updated stale comments, "ASCII whitespace", examples as separate documents, straight quotes. | +| 3 | 5 necessary (0 major, 1 medium, 3 minor, 1 nit), 5 optional; see "Last review". All five checked and confirmed; findings 1 and 3 with a test. | Applied all five: a tag must be alone in its own paragraph (separated by blank lines), and a tag on a line next to paragraph text joins that paragraph; the no-heading fallback now says "at or before" and ends at the next heading; "as is" became "after cleaning", and the `contenteditable` cleaning rule is limited to `` and ``; the Tests subsection describes what the tests cover instead of requiring a test per rule; the "Errors" wording now says a Markdown fragment is valid and an empty one shows only its "From …:" link. | + +### Last review (10 points) + +Model: Claude Opus 5.5, run read-only. Effort: default (no separate effort +setting was chosen). Input: the working-tree +`server/src/processing/cache-spec.md`, `processing.rs`, and +`processing/tests.rs`, after the round 2 fixes. + +Exact prompt: + +```text +Review only the section "Fragments in Markdown documents" (`

`, from that heading up to "Search (future work)") in `server/src/processing/cache-spec.md` (repo root: /Users/kaspi/kbtu/project/CodeChat_Editor), and its direct interactions with the rest of that spec: the "Fragments and gather elements" section (`cc-gKXTXIZnFm`), "Cache design" layers (`cc-P-g5o100jN`), "Gather elements: the reverse edge", and "HTML cleaning" (`cc-2dkkF9YJnL`). + +Also check the section against the implementation in `server/src/processing.rs`: `hydrate_html`, `hydrate_dom`, `store_fragment_contents`, `render_markdown_fragment_content`, `holds_only_fragments`, `markdown_fragment_extent`, `heading_level`, `top_level_index`, `hydrate_gathers`, `CLEAN_FRAGMENT_HTML`, and the Markdown fragment tests in `server/src/processing/tests.rs` (search for "test_markdown_fragment"). You may run read-only commands (grep, reading files, `git diff`). Do NOT edit any file, do not build, and do not run tests; do not claim test results. + +Strictly read-only: do not modify, create, or delete any file. + +Return, in English Markdown: +1. Necessary findings, numbered, each with a severity (major / medium / minor / nit), the spec line numbers, what is wrong, and a concrete suggested fix. A finding is necessary only if the spec is wrong, self-contradictory, ambiguous in a way that changes behavior, or disagrees with the implementation. +2. Optional suggestions, separately. +3. A short "Verified as correct" list (what you checked and found consistent, including code references). +4. Counts: "Necessary findings: N (x major, y medium, z minor, w nit). Optional: M." +5. One table row summary: | Round | Findings | Main changes recommended | +``` + +Output, condensed (necessary findings, optional suggestions, and counts; the +"Verified as correct" list is omitted). The reviewer numbered its summary row +"1" because it didn't see the earlier rounds; it is round 3 here. I checked +every finding: findings 1 and 3 were confirmed by running the cases through +`markdown_fragment_content`; none is struck through. + +1. **Medium: "alone on its line" doesn't match how Markdown splits paragraphs** + (spec lines 253-259, 288-289, 360-363). An HTML line can't interrupt a + paragraph in CommonMark, and a following line continues it. So + `Before.\n\n\nNext.` is one paragraph, which + becomes the anchor and encloses `Before.`, not `Next.`; likewise + `\nNext.` joins `Next.` into the tag's paragraph. + `holds_only_fragments` and `markdown_fragment_extent` work on the parsed + paragraph, not on source lines. Fix: say "alone in its own paragraph, + separated from neighbouring text by blank lines", and add that a tag on a + line directly before or after paragraph text belongs to that paragraph. +2. **Minor: the no-heading fallback conflicts with the main rule when the anchor + is a heading** (lines 277-281). The main rule uses "the nearest heading at + or before the anchor block", but the fallback says "if no heading precedes + the anchor block, the extent ends just before the document's first + heading". If the anchor is itself the first heading, a literal reading gives + an empty extent. The code uses "at or before" (`processing.rs:2216`; + `tests.rs:2934`). Fix: "If no heading is at or before the anchor block, the + extent ends just before the next heading of any level." +3. **Minor: "as is" overstates what a gather element shows** (lines 294-295, + 626-628). `CLEAN_FRAGMENT_HTML` is an Ammonia allowlist: a raw-HTML block + counts as a block but may partly disappear (elements outside the allowlist, + most classes and attributes). `contenteditable` is kept only on `span` and + `xref` (`processing.rs:1338`, `1345`), not on any element as line 627-628 + implies. Fix: say "the document's own HTML after cleaning", and limit the + `contenteditable` rule to `` and ``. +4. **Minor: the Tests section requires a test for every rule, and several + rules have none** (lines 445-455): a top-level non-whitespace text node as a + block; comments before the first or after the last enclosed block; a + missing or duplicate `id` in a Markdown document; a gather element in the + same document listing a Markdown fragment. `_gathered` and `_round_trip` + don't compare the stored content. Fix: add these tests, or change "Each + rule above needs a unit test" to describe what the tests cover. +5. **Nit: two wording problems in "Errors"** (lines 344-349). "No longer an + error" describes the spec's history; say "a fragment in a Markdown document + is valid". The comparison with "an empty doc block in a source file" is + wrong: such a doc block still renders its wrapper and line number. Fix: + "its stored content is empty; the gather list shows only its 'From …:' + link". + +Optional suggestions: give the "Gather elements: the reverse edge" heading an +`id` and refer to it with ``; state that an empty `

` also isn't a +block; say "a cross-reference in the document (in particular, inside the +extent)"; state that whitespace around `following` is allowed; note that a +`

` holding only fragments inside the extent range still triggers +the gather error. + +Necessary findings: 5 (0 major, 1 medium, 3 minor, 1 nit). Optional: 5. + +| Round | Findings | Main changes recommended | +| ----- | -------- | ------------------------ | +| 1 | 5 necessary (0 major, 1 medium, 3 minor, 1 nit), 5 optional | Say "alone in its own paragraph" instead of "alone on its line"; make the no-heading fallback say "at or before"; replace "as is" with "after cleaning" and limit the `contenteditable` cleaning rule to ``/``; add the missing tests or relax "each rule needs a test"; fix the "Errors" wording. | + + +Team member: Dustin Johnson (GitHub: drj228) +------------------------------------------ + +### Contribution (5 points) + +Fixed and verified the Windows build and standalone editor, and used Claude reviews to correct the specification to define Markdown fragments, address boundary and consistency findings, and reach zero necessary corrections. + +### Build and run check (5 points) + +ChatGPT assisted with troubleshooting and reviewed the terminal output and screenshots; Dustin executed the commands on Windows. + +Environment: Rust 1.99.1, Cargo 1.99.1, Node.js v26.14.0, npm 11.21.3. + +The initial installation was blocked at the cargo-binstall bootstrap by antivirus protection. Installed cargo-nextest directly using `cargo install cargo-nextest --locked`. + +The build then failed when npx invoked the NAPI launcher. Switching the build helper to `pnpm exec napi build` resolved the failure (commit `65a38bf`). + +`cargo run --manifest-path .\builder\Cargo.toml -- build` completed successfully, including the Rust workspace, client bundles, VS Code native extension, and TypeScript checks. All 13 export_bindings tests passed on both invocations; the other 196 tests were filtered out. + +Started `.\target\debug\codechat-editor-standalone.exe --port 8080 serve` and verified that the browser displayed the file browser and rendered README.md in the CodeChat editor. The full test suite was not run. + +### Review rounds (10 points) + +Reviewed with Claude Opus 5.5, Medium effort, in a separate browser session. + +| Round | Findings | Main changes made | +| ----- | -------- | ----------------- | +| 1 | 7 necessary (3 major, 2 medium, 2 minor); 5 optional | Defined Markdown fragments: section and block-count boundaries, gather interactions, layout, save/reopen rules, and examples; removed the Markdown-fragment ban. | +| 2 | 3 necessary (1 medium, 2 minor); 4 optional | Defined boundaries on HTML before hydration, explicitly listed the source-file rules being replaced, and corrected the formatted example and overlap statement. | +| 3 | 0 necessary; 6 optional (4 carried over, 2 new) | Confirmed N1-N3 were resolved; made no further changes and left the optional suggestions unadopted. | + +ChatGPT prepared the targeted patch for the round 2 corrections; Dustin applied +it locally before requesting round 3. These were specification reviews, not +implementation verification of the proposed Markdown fragment feature. + +### Last review (10 points) + +Model: Claude Opus 5.5. Effort: Medium. Tool: Claude in a separate browser +session. Input: the corrected `server/src/processing/cache-spec.md`. + +Exact prompt: + +```text +Review only the corrected "Fragments in Markdown documents" section and its direct interactions with existing rules. Do not edit anything. + +Confirm whether N1, N2, and N3 are resolved. Report any remaining necessary corrections together. Keep optional suggestions separate and do not expand the scope. + +Do not claim implementation or test results. Finish with finding counts and a concise review-table summary. +``` + +Exact response (the reviewer numbers the rounds from 2, so its "round 3" and +"round 4" are rounds 2 and 3 here): + +> N1, N2 and N3 are all resolved, and I found no new necessary corrections. This is a review only: I didn't edit anything and made no claims about implementation or tests. +> +> ### Status of the previous findings +> +> | Finding | Status | Where | +> | -------------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +> | **N1:** blocks and headings were defined partly on the Markdown and partly on the HTML | Resolved | Lines 234–243 now compute boundaries on the HTML translated from the Markdown, before cache hydration. Blocks are the root's element children, whitespace between them is ignored, and a heading is any top-level `

`–`

`. That settles `following` counts and HTML gather headings. It also matches "depends only on the document's own source" (line 266) and "recomputed from the saved Markdown" (line 294). | +> | **N2:** the section didn't list every existing rule it replaces | Resolved | Lines 227–230 name all five: extent, what `following` counts, what `following="0"` contains, clamping, and gather-list layout. | +> | **N3:** two statements were wrong | Resolved | The `bt` example keeps its code formatting (line 333). The overlap statement now applies only to fragments without `following` (lines 280–281). | +> +> I rechecked the examples under the new HTML-based definition and they still hold: +> +> - A tag written alone on its own line stays a paragraph. +> - `

` is a top-level heading, so `design` contains a gather element. +> - `following="1"` gives the heading plus `Rationale.`. +> - `win` anchors to the whole list. +> +> ### Remaining necessary corrections +> +> None. +> +> ### Optional suggestions +> +> These four from the last review haven't been adopted and are still optional: +> +> - **O1:** End a default section just before a gather element as well. This avoids errors in the common layout of a section with a nested "Implementation of …" gather heading. +> - **O2:** Add one sentence on why "text inside the tag" and "an end tag" weren't chosen. +> - **O3:** Pin down the line number shown in a gather list (line 264) as the source line where the extent begins, even if that block is empty after cleaning. +> - **O4:** Add an example showing that a nested heading such as `> ## Note` doesn't end a section. +> +> Two new ones: +> +> - **O5:** Line 237 covers whitespace-only text at the top level but not other stray text. A raw HTML block such as `
a
tail` leaves the text "tail" directly under the root, outside any block. One clause would close the gap, for example: "non-whitespace top-level text belongs to the preceding block." +> - **O6:** Line 333 uses curly quotes (“…”). The rest of the spec uses straight quotes or backticks. +> +> **Necessary findings: 0. Optional findings: 6 (4 carried over, 2 new).** +> +> | Round | Findings | Main changes recommended | +> | ----- | -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +> | 4 | N1–N3 from round 3 resolved; 0 necessary and 6 optional (4 carried over, 2 new). | No necessary changes. Optional: end sections before gather elements; explain why the other options weren't chosen; pin down the line number; add a nested-heading example; cover stray top-level text; use straight quotes. |