From b136a5fcceefe2a164caba5cb0302f45458907cb Mon Sep 17 00:00:00 2001 From: Azamat Ayapbergenov Date: Sat, 28 Nov 2026 18:10:47 +0500 Subject: [PATCH 1/8] Spec: define fragments in Markdown documents --- cache-spec.md | 315 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 315 insertions(+) create mode 100644 cache-spec.md diff --git a/cache-spec.md b/cache-spec.md new file mode 100644 index 00000000..aec7c511 --- /dev/null +++ b/cache-spec.md @@ -0,0 +1,315 @@ +Cache specification +=================== + +**Status: DRAFT.** This document specifies the strategy used by `cache.rs` to +cache all targets and fragments in a CodeChat Editor project. It is written for +review; items marked *Open question* are unresolved. + +Purpose and scope +----------------- + +The CodeChat Editor renders a file by translating its source to HTML. Some of +that HTML depends on *other* files: a cross-reference (``) shows +text taken from its target, and a `` shows backlinks to the gather +elements (`data-gather`) which list it. The cache records, for every file in a +project, what each file defines and what it references, so that: + +1. An id can be resolved to its definition without reading the file defining it + (`resolve_id`). +2. A change to one file identifies exactly the other files whose rendered output + is now stale, so that only those are re-rendered. +3. The above stays correct as files are created, edited, renamed, and deleted + by any program, not only by the IDE connected to the Server. + +The cache does *not* store rendered pages, and does not (yet) index file +contents for search. + +Terminology +----------- + +* **Project**: a directory tree whose root contains `toc.md`. A file opened + without a `toc.md` is a single-file "project" whose cache has no consumer or + watcher. +* **Target**: any HTML element with an `id`, other than a ``. A + *gather element* is a target with a non-empty `data-gather` list. +* **Fragment**: a ``: a series of code/doc blocks starting with + a doc block. +* **Cross-reference**: an `` naming an id. +* **Dependent** (of an id): a file whose rendered output depends on that id, + because it cross-references it or lists it in a gather element. +* **Outdated**: a file whose cached facts are current, but whose *rendered* + output must be regenerated. +* **Connection**: one Client/IDE session. Its *current file* is the file it + shows; the connection, not the cache, owns that file's text. + +Data model +---------- + +A project's `Cache` holds: + +* `files`: a map from each file's normalized absolute path to a `FileEntry`. + The map is ordered by path component, so all files beneath a directory are + contiguous and can be found by a range query. +* `ids`: a map from id to an `IdEntry`. +* `root`, the project root. +* `connections`: the connections whose current file lies in this project. + +A `FileEntry` records: a **stamp** (see below), a **status** (`Unknown`, +`Outdated`, `UpToDate`), the file's **targets** and **fragments** (each keyed by +id), its **cross-references**, and an index of its **gather elements**. + +An `IdEntry` records the id's **state** and its **dependents**: + +| State | Meaning | +| ---------- | ----------------------------------------------------------------- | +| `Single` | Exactly one definition, in one file. | +| `Multiple` | More than one definition; maps each defining file to its count. | +| `Missing` | Referenced but not defined. | + +Targets and fragments share one id namespace. A duplicate id is an error which +is reported wherever the id is referenced. + +Invariants +---------- + +1. Every id in `ids` is either defined or has at least one dependent. An entry + which is neither is removed. +2. `IdEntry::dependents` contains file *F* if and only if *F*'s most recently + committed version references that id. +3. A file is never marked outdated by its own commit. +4. A cache is never evicted from the `CacheMap` while a connection is registered + in it. +5. The lock on a cache is never held during file system I/O or during a long + operation spanning many files. + +Committing a file (`commit_file`) +--------------------------------- + +The facts collected from translating one file (its targets, cross-references, +and fragments, in document order) are applied in one transaction, under one +lock acquisition: + +1. **Take the old version** out of the entry. +2. **Unlink** the file from the dependents of every id the old version + referenced. +3. **Build the new definitions.** If an id is defined several times in the file, + the first definition in document order is stored, but all definitions are + counted. A surviving fragment keeps its previous content until + `update_fragment_content` supplies the new content. +4. **Update id states.** For each id defined before or now, replace this file's + contribution to the id's definition map. If the resulting state differs from + the old state (id appeared, disappeared, moved, or became or ceased to be a + duplicate), every dependent of that id is outdated. +5. **Outdate dependents of modified definitions.** A change to a target's inner + HTML, or an id changing kind between target and fragment, leaves the state + unchanged but still outdates the id's dependents. +6. **Outdate the files defining regathered fragments** (the *reverse edge*, + below). +7. **Store** the new version, set the status to `UpToDate`, and **link** the + file as a dependent of every id it references (creating `Missing` entries as + needed). +8. **Forget unused ids**, then mark the outdated files, excluding the committed + file. + +### The reverse edge + +A `` renders a backlink to each gather element listing it, so a +fragment's file depends on those gather elements. Unlike cross-references, this +cannot be handled by unlinking and relinking, because the set of gather elements +is observable output. Instead the old and new gather lists are diffed before +being overwritten: + +* If a gather element's inner HTML changed (including being added or removed), + every id in the union of its old and new lists is affected, since that HTML is + the text of each backlink. +* Otherwise only the symmetric difference of the old and new lists is affected. + +The file defining each affected fragment is outdated. An affected id with no +definition needs nothing: when it is defined, its file renders its backlinks in +that same pass. This does not loop: outdating a +fragment's file re-renders it, which changes the fragment's content only if +doing so changes what gather elements display, and gather elements display +their own text, not the fragment's. + +*Open question*: this termination argument should be stated more rigorously; it +holds as long as a gather element's `inner_html` never includes rendered +fragment content. + +### Fragment content + +A fragment's rendered content is known only after its doc blocks are finalized, +after `commit_file`. `update_fragment_content` stores it; if it changed, every +dependent of the fragment's id other than the fragment's own file is marked +outdated. Gather elements in the fragment's own file are updated in the same +processing pass. + +### Removing a file + +`remove_file` commits an empty set of facts (which withdraws all definitions and +references, outdating dependents) and then drops the entry. + +Resolving ids +------------- + +`resolve_id` returns the target or fragment an id names along with its file, +`Missing`, or `Multiple`. `gathers_referencing` returns every gather element +listing a fragment id, sorted by (file, gather id) so that rendered backlinks +are deterministic. + +Auto-assignment of ids +---------------------- + +An element with `id="*"` is assigned a new id of the form `cc-` followed by 10 +characters from `A-Z a-z 0-9 - _` chosen at random, which collides with no id +in the cache and none assigned earlier in the same pass. The new id is +deliberately **not** recorded in the cache: it enters the cache only when the +file containing it is saved and read again. This way a failed or abandoned save +cannot leave the cache describing an id which no file contains. + +Cache population and maintenance +-------------------------------- + +A project cache is kept current by three cooperating pieces. Each holds only a +weak reference to the cache, so none keeps a dropped cache alive. + +* The **watcher** reports changes to files and directories in the project + (debounced for 2 seconds). A rename is reported as a deletion plus a creation. + If the platform reports lost events, the whole project is re-walked. + Symlinks are not followed. If the watcher cannot start (for example, inotify + limits), a warning is logged; the cache remains usable but learns only of + files found by the initial walk. +* The **walker** filters reported paths and walks directories. It obeys the same + rules as ripgrep: hidden files and directories, `.ignore`, and (inside a Git + repository) `.gitignore` and Git's exclude rules are skipped. A change to an + ignore file triggers a re-walk of the directory it governs (the whole project + for `.git/info/exclude`). A directory reported as created is walked. +* The **consumer** applies the walker's results to the cache. + +The watcher is registered *before* the initial walk, so a file created during +the walk is reported by at least one of them. Registration may be slow, so it +occurs on its own thread rather than delaying the translation which created the +cache. + +### Messages to the consumer + +| Message | Meaning | +| ------------------------------ | ---------------------------------------------------------- | +| `CreatedOrModified(path)` | Scan this file. | +| `Deleted(path)` | The path may no longer exist. | +| `WalkStarted(dir)`, `WalkFinished` | Bracket the files found by walking `dir`. | +| `Rescan(path)` | Bring an already-cached file up to date; not evidence that the file isn't ignored. | + +### Scanning a file + +1. Read the file's metadata (without holding the lock). If the path is no longer + a file, forget it. +2. Skip the file if it is some connection's current file (that connection keeps + it current from the IDE's text). If it is also the TOC and has changed, + notify connections. +3. Skip the file if the cache has it, it is unmodified per its stamp, and its + status is `UpToDate`. A file not in the cache is scanned only if the walker + sent it. +4. Read the file as text. If the first 8 KB is not UTF-8 the file is binary and + is not translated; a file which cannot be read is left as-is. +5. Translate the file (converting `\r\n` to `\n`), which commits its facts. +6. Record the stamp taken *before* reading, not after: a write between reading + and stamping would otherwise make the cache describe the old text with the + new stamp, so the watcher's report of that write would be skipped. +7. A file with no lexer commits empty facts and its stamp, withdrawing anything + it previously defined. A failed translation discards the stamp so that the + next walk retries it. + +### Detecting changes: file stamps + +A stamp is a snapshot of length, modification time, and (on Unix) change time, +device, and inode. Modification times are compared only for equality, never +order. As in Git, a stamp is **racy**, and never matches, if the file was +modified within 3 seconds of the snapshot, if its modification time is in the +future, or if the platform reports none. On Windows the creation time is not +used: NTFS "tunneling" can give a newly-saved file the creation time of the +file it replaced. + +### Deletions and walks + +* A deleted path whose type is unknown is looked up as a file; if the cache has + no such file, every cached file beneath it is forgotten. A deletion for a + path which exists again (a VCS checkout, or an editor which saves by + renaming) is a scan, not a forget. +* A walk of directory *D* records the cached files beneath *D* before it starts. + Those not found by `WalkFinished` are forgotten, since they were deleted or + are now ignored. A `Rescan` never counts as "found". +* The lock is released between files while forgetting. + +### Forgetting a shown file + +A file shown by a connection (its current file, or the TOC when any connection +exists) is never removed from the cache by a deletion or an ignore change, since +the IDE may still hold its text. Instead the connection is told to re-translate +it, which keeps it cached; for the TOC every connection reloads it. + +Connections +----------- + +A `ConnectionRegistration` lists a connection and its current file in the cache +and removes the listing when dropped. Registering replaces any earlier +registration for the same connection id (the old one is dropped first). On drop, +if no other connection shows the file, a `Rescan` checks it against disk; if +unchanged, the content committed from the IDE remains. + +When files become outdated, `mark_outdated` sets their status and then: + +* sends `CurrentFileOutdated` to each connection whose current file is outdated; +* sends `TocOutdated` to every connection if the TOC is outdated; +* sends `Rescan` to the consumer for every outdated file *not* shown by a + connection. + +`TocChanged` is sent when the TOC's text changes on disk or the TOC is deleted. +Notification channels are unbounded because the cache lock is held while +sending; a failed send means the connection has exited and is ignored. + +Project cache map and eviction +------------------------------ + +The Server keeps a `CacheMap`: an LRU map from project root to cache. + +* Capacity is *n* × 10 + 1 for *n* connections. This balances memory against + the cost of reloading an evicted project. +* Insertion and resizing evict the least recently used caches **with no + connections** first. A cache with connections is never evicted; if all + entries have connections, the map is grown by one to make room. +* Lock order: the outer map lock before any single cache's lock. + +Shutdown +-------- + +Only the `CacheMap` owns a cache strongly. When a cache is dropped, its watcher +is dropped (stopping the watch), the watcher's channel closes, the walker exits, +the consumer's sender closes, and the consumer exits. The consumer upgrades its +weak reference per message, so it never delays this. + +Error handling +-------------- + +| Condition | Behavior | +| --------------------------------- | ----------------------------------------------------- | +| Watcher cannot start | Log a warning; continue without watching. | +| Watcher reports an error | Log only. | +| File unreadable (locked) | Leave cache unchanged; rely on a later watch event. | +| File not UTF-8 | Not translated; no definitions. | +| Translation fails | Log; discard stamp so it is retried. | +| Duplicate id | Reported at each reference; first definition stored. | +| Poisoned lock in `Drop` | Recover the inner value rather than panic. | + +Open questions and known gaps +----------------------------- + +* `IdResolution::Multiple` is not yet used by callers, so duplicates within a + single file are not yet reported distinctly. +* Line numbers in targets and fragments are always 0 until the markdown HTML + writer preserves them; the Client cannot yet scroll to an anchor. +* The `SaveOnScan` option (write auto-assigned ids back during a scan) is + unimplemented. +* Search indexing (id, contents, file name) is not yet designed. +* `notify` cannot yet filter event kinds at the source. +* On Windows, stamps lack change time and file index, so same-length edits + within the racy window depend on the 3-second rule. From f14d2159ef78dec4bbbc7fce6092f98ac51387ce Mon Sep 17 00:00:00 2001 From: Aldiyar24x <146171329+Crazy24-x@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:30:26 +0500 Subject: [PATCH 2/8] More spefic spec for fragment --- .../src/processing/markdown-fragments-spec.md | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 server/src/processing/markdown-fragments-spec.md diff --git a/server/src/processing/markdown-fragments-spec.md b/server/src/processing/markdown-fragments-spec.md new file mode 100644 index 00000000..f8cf21f9 --- /dev/null +++ b/server/src/processing/markdown-fragments-spec.md @@ -0,0 +1,130 @@ +Fragments in Markdown documents +------------------------------- + +A Markdown document has no code blocks or doc blocks, so the rules which count +code/doc blocks cannot apply to it. This section defines what a `` +encloses in a Markdown document, so that a gather element can display it just as +it displays a fragment in a source file. The rest of the cache (ids, dependents, +the reverse edge, outdating) is unchanged; only the *extent* and *content* of a +Markdown fragment are new. + +This replaces the earlier rule that fragments are not allowed in Markdown +documents: such a fragment is now valid and has the extent defined below. + +### What a fragment encloses + +The rules are expressed in terms of the document's **top-level blocks**: the +children of the rendered document's root (a paragraph, heading, list, block +quote, code block, table, and so on). A block nested inside another (a list item +inside a list) belongs to its top-level block. + +* **Default.** The fragment encloses the top-level block containing the + `` tag, then every following top-level block up to, but not + including, the next heading whose level is the same as or higher (a smaller + number) than that of the closest heading at or before the tag. If no heading + precedes the tag, the fragment ends at the end of the document. If the tag is + inside a heading, that heading is the closest one, and it is included in the + fragment. Skipped heading levels (a `###` directly under a `#`) make no + difference: only the numeric levels are compared. +* **`following="N"`.** The fragment encloses the block containing the tag plus + the next `N` top-level blocks, regardless of headings. `N` must be a whole + number; `following="0"` encloses only the block containing the tag. A value + larger than the number of remaining blocks is clamped to the end of the + document. A value which isn't a whole number replaces the fragment's content + with an error message, as in source files. +* The `` tag itself is never part of the content: it is removed, along + with any backlinks hydrated into it. + +### Example + +````markdown +## Request + + + +The client sends a `POST` to `/upload`. + +* The body is JSON. +* The reply is `204`. + +## Response + +The server replies... +```` + +`req` encloses the block holding the tag, the paragraph, and the list, and stops +before `## Response`, since that heading has the same level as `## Request`. +Replacing the tag with `` encloses +only the tag's block and the paragraph. + +### Content stored in the cache + +The cache stores each Markdown fragment's content as cleaned HTML, produced by +the same cleaner used for source-file fragments: + +* All `id` attributes are removed, so a gather element never duplicates an id. +* `` tags are removed with their contents, so backlink hydration is + excluded from the stored content; this is what keeps a gather element and the + fragments it lists from outdating each other forever (see the reverse edge). +* Cross-references in the content are hydrated in the fragment's file, then + re-hydrated by the gather element so that links lead from the gather + element's file. +* Relative images and URLs in the content aren't rewritten; as stated under + "Misc", they aren't supported when the gathering file lies in a different + directory. + +Unlike a source-file fragment, the content has no line-number gutter or indents, +since a Markdown document has none. + +### Keeping the cache current + +Because a Markdown fragment's extent depends on the document's structure, the +cache re-derives it each time the file is processed. A fragment's stored content +changes when any enclosed block changes, when the enclosing section gains or +loses blocks, or when a heading is added, removed, or changes level so that the +section ends elsewhere. As for any fragment, changed content outdates the files +containing gather elements which list it (`update_fragment_content`). + +### Errors + +A Markdown fragment produces an error message, as a source-file fragment does, +when: + +* it has no `id`, or its `id` isn't a valid CSS identifier; +* its `following` value isn't a whole number; +* its enclosed blocks contain a gather element, including one whose `id` is + missing or invalid (a fragment must not gather); +* its `id` is a duplicate. + +A gather element listing a Markdown fragment follows the existing rules: an +error message replaces the content for an id which is missing, duplicated, or +names a target rather than a fragment. + +### Edge cases + +* Two fragments in the same section both enclose the rest of the section, so + their contents overlap; this is allowed. +* A fragment tag in the last block of the document encloses only that block. +* A tag inside a code block or inline code is literal text, not a fragment. +* Nested block quotes and lists count as one top-level block. + +### Why this design + +Alternatives considered: + +1. **Everything in the current heading, ignoring the tag's position.** Simple, + but the author can't enclose less than a whole section, and content above + the tag within the same heading is always included. Starting at the block + holding the tag lets the author choose where a fragment begins by placing + the tag, while still ending at the section's end by default. +2. **Only the text inside the tag** (`...`). Markdown's HTML + block rules end an HTML block at the first blank line, so multi-paragraph + content wouldn't stay inside the tag. +3. **An explicit end tag.** Flexible, but easy to forget, and an unclosed tag + silently swallows the rest of the document. +4. **Block counting only.** Matches source files, but breaks when blocks are + added or removed; the section default adapts automatically. + +The chosen design keeps the existing `following` attribute, so source files and +Markdown behave alike, and adds a default which follows the document's own +structure. From c2189c3f51875ab295a7d6217867d255fd23c764 Mon Sep 17 00:00:00 2001 From: Azamat Ayapbergenov Date: Tue, 1 Dec 2026 23:44:30 +0500 Subject: [PATCH 3/8] Remove misplaced cache-spec.md from repo root --- cache-spec.md | 315 -------------------------------------------------- 1 file changed, 315 deletions(-) delete mode 100644 cache-spec.md diff --git a/cache-spec.md b/cache-spec.md deleted file mode 100644 index aec7c511..00000000 --- a/cache-spec.md +++ /dev/null @@ -1,315 +0,0 @@ -Cache specification -=================== - -**Status: DRAFT.** This document specifies the strategy used by `cache.rs` to -cache all targets and fragments in a CodeChat Editor project. It is written for -review; items marked *Open question* are unresolved. - -Purpose and scope ------------------ - -The CodeChat Editor renders a file by translating its source to HTML. Some of -that HTML depends on *other* files: a cross-reference (``) shows -text taken from its target, and a `` shows backlinks to the gather -elements (`data-gather`) which list it. The cache records, for every file in a -project, what each file defines and what it references, so that: - -1. An id can be resolved to its definition without reading the file defining it - (`resolve_id`). -2. A change to one file identifies exactly the other files whose rendered output - is now stale, so that only those are re-rendered. -3. The above stays correct as files are created, edited, renamed, and deleted - by any program, not only by the IDE connected to the Server. - -The cache does *not* store rendered pages, and does not (yet) index file -contents for search. - -Terminology ------------ - -* **Project**: a directory tree whose root contains `toc.md`. A file opened - without a `toc.md` is a single-file "project" whose cache has no consumer or - watcher. -* **Target**: any HTML element with an `id`, other than a ``. A - *gather element* is a target with a non-empty `data-gather` list. -* **Fragment**: a ``: a series of code/doc blocks starting with - a doc block. -* **Cross-reference**: an `` naming an id. -* **Dependent** (of an id): a file whose rendered output depends on that id, - because it cross-references it or lists it in a gather element. -* **Outdated**: a file whose cached facts are current, but whose *rendered* - output must be regenerated. -* **Connection**: one Client/IDE session. Its *current file* is the file it - shows; the connection, not the cache, owns that file's text. - -Data model ----------- - -A project's `Cache` holds: - -* `files`: a map from each file's normalized absolute path to a `FileEntry`. - The map is ordered by path component, so all files beneath a directory are - contiguous and can be found by a range query. -* `ids`: a map from id to an `IdEntry`. -* `root`, the project root. -* `connections`: the connections whose current file lies in this project. - -A `FileEntry` records: a **stamp** (see below), a **status** (`Unknown`, -`Outdated`, `UpToDate`), the file's **targets** and **fragments** (each keyed by -id), its **cross-references**, and an index of its **gather elements**. - -An `IdEntry` records the id's **state** and its **dependents**: - -| State | Meaning | -| ---------- | ----------------------------------------------------------------- | -| `Single` | Exactly one definition, in one file. | -| `Multiple` | More than one definition; maps each defining file to its count. | -| `Missing` | Referenced but not defined. | - -Targets and fragments share one id namespace. A duplicate id is an error which -is reported wherever the id is referenced. - -Invariants ----------- - -1. Every id in `ids` is either defined or has at least one dependent. An entry - which is neither is removed. -2. `IdEntry::dependents` contains file *F* if and only if *F*'s most recently - committed version references that id. -3. A file is never marked outdated by its own commit. -4. A cache is never evicted from the `CacheMap` while a connection is registered - in it. -5. The lock on a cache is never held during file system I/O or during a long - operation spanning many files. - -Committing a file (`commit_file`) ---------------------------------- - -The facts collected from translating one file (its targets, cross-references, -and fragments, in document order) are applied in one transaction, under one -lock acquisition: - -1. **Take the old version** out of the entry. -2. **Unlink** the file from the dependents of every id the old version - referenced. -3. **Build the new definitions.** If an id is defined several times in the file, - the first definition in document order is stored, but all definitions are - counted. A surviving fragment keeps its previous content until - `update_fragment_content` supplies the new content. -4. **Update id states.** For each id defined before or now, replace this file's - contribution to the id's definition map. If the resulting state differs from - the old state (id appeared, disappeared, moved, or became or ceased to be a - duplicate), every dependent of that id is outdated. -5. **Outdate dependents of modified definitions.** A change to a target's inner - HTML, or an id changing kind between target and fragment, leaves the state - unchanged but still outdates the id's dependents. -6. **Outdate the files defining regathered fragments** (the *reverse edge*, - below). -7. **Store** the new version, set the status to `UpToDate`, and **link** the - file as a dependent of every id it references (creating `Missing` entries as - needed). -8. **Forget unused ids**, then mark the outdated files, excluding the committed - file. - -### The reverse edge - -A `` renders a backlink to each gather element listing it, so a -fragment's file depends on those gather elements. Unlike cross-references, this -cannot be handled by unlinking and relinking, because the set of gather elements -is observable output. Instead the old and new gather lists are diffed before -being overwritten: - -* If a gather element's inner HTML changed (including being added or removed), - every id in the union of its old and new lists is affected, since that HTML is - the text of each backlink. -* Otherwise only the symmetric difference of the old and new lists is affected. - -The file defining each affected fragment is outdated. An affected id with no -definition needs nothing: when it is defined, its file renders its backlinks in -that same pass. This does not loop: outdating a -fragment's file re-renders it, which changes the fragment's content only if -doing so changes what gather elements display, and gather elements display -their own text, not the fragment's. - -*Open question*: this termination argument should be stated more rigorously; it -holds as long as a gather element's `inner_html` never includes rendered -fragment content. - -### Fragment content - -A fragment's rendered content is known only after its doc blocks are finalized, -after `commit_file`. `update_fragment_content` stores it; if it changed, every -dependent of the fragment's id other than the fragment's own file is marked -outdated. Gather elements in the fragment's own file are updated in the same -processing pass. - -### Removing a file - -`remove_file` commits an empty set of facts (which withdraws all definitions and -references, outdating dependents) and then drops the entry. - -Resolving ids -------------- - -`resolve_id` returns the target or fragment an id names along with its file, -`Missing`, or `Multiple`. `gathers_referencing` returns every gather element -listing a fragment id, sorted by (file, gather id) so that rendered backlinks -are deterministic. - -Auto-assignment of ids ----------------------- - -An element with `id="*"` is assigned a new id of the form `cc-` followed by 10 -characters from `A-Z a-z 0-9 - _` chosen at random, which collides with no id -in the cache and none assigned earlier in the same pass. The new id is -deliberately **not** recorded in the cache: it enters the cache only when the -file containing it is saved and read again. This way a failed or abandoned save -cannot leave the cache describing an id which no file contains. - -Cache population and maintenance --------------------------------- - -A project cache is kept current by three cooperating pieces. Each holds only a -weak reference to the cache, so none keeps a dropped cache alive. - -* The **watcher** reports changes to files and directories in the project - (debounced for 2 seconds). A rename is reported as a deletion plus a creation. - If the platform reports lost events, the whole project is re-walked. - Symlinks are not followed. If the watcher cannot start (for example, inotify - limits), a warning is logged; the cache remains usable but learns only of - files found by the initial walk. -* The **walker** filters reported paths and walks directories. It obeys the same - rules as ripgrep: hidden files and directories, `.ignore`, and (inside a Git - repository) `.gitignore` and Git's exclude rules are skipped. A change to an - ignore file triggers a re-walk of the directory it governs (the whole project - for `.git/info/exclude`). A directory reported as created is walked. -* The **consumer** applies the walker's results to the cache. - -The watcher is registered *before* the initial walk, so a file created during -the walk is reported by at least one of them. Registration may be slow, so it -occurs on its own thread rather than delaying the translation which created the -cache. - -### Messages to the consumer - -| Message | Meaning | -| ------------------------------ | ---------------------------------------------------------- | -| `CreatedOrModified(path)` | Scan this file. | -| `Deleted(path)` | The path may no longer exist. | -| `WalkStarted(dir)`, `WalkFinished` | Bracket the files found by walking `dir`. | -| `Rescan(path)` | Bring an already-cached file up to date; not evidence that the file isn't ignored. | - -### Scanning a file - -1. Read the file's metadata (without holding the lock). If the path is no longer - a file, forget it. -2. Skip the file if it is some connection's current file (that connection keeps - it current from the IDE's text). If it is also the TOC and has changed, - notify connections. -3. Skip the file if the cache has it, it is unmodified per its stamp, and its - status is `UpToDate`. A file not in the cache is scanned only if the walker - sent it. -4. Read the file as text. If the first 8 KB is not UTF-8 the file is binary and - is not translated; a file which cannot be read is left as-is. -5. Translate the file (converting `\r\n` to `\n`), which commits its facts. -6. Record the stamp taken *before* reading, not after: a write between reading - and stamping would otherwise make the cache describe the old text with the - new stamp, so the watcher's report of that write would be skipped. -7. A file with no lexer commits empty facts and its stamp, withdrawing anything - it previously defined. A failed translation discards the stamp so that the - next walk retries it. - -### Detecting changes: file stamps - -A stamp is a snapshot of length, modification time, and (on Unix) change time, -device, and inode. Modification times are compared only for equality, never -order. As in Git, a stamp is **racy**, and never matches, if the file was -modified within 3 seconds of the snapshot, if its modification time is in the -future, or if the platform reports none. On Windows the creation time is not -used: NTFS "tunneling" can give a newly-saved file the creation time of the -file it replaced. - -### Deletions and walks - -* A deleted path whose type is unknown is looked up as a file; if the cache has - no such file, every cached file beneath it is forgotten. A deletion for a - path which exists again (a VCS checkout, or an editor which saves by - renaming) is a scan, not a forget. -* A walk of directory *D* records the cached files beneath *D* before it starts. - Those not found by `WalkFinished` are forgotten, since they were deleted or - are now ignored. A `Rescan` never counts as "found". -* The lock is released between files while forgetting. - -### Forgetting a shown file - -A file shown by a connection (its current file, or the TOC when any connection -exists) is never removed from the cache by a deletion or an ignore change, since -the IDE may still hold its text. Instead the connection is told to re-translate -it, which keeps it cached; for the TOC every connection reloads it. - -Connections ------------ - -A `ConnectionRegistration` lists a connection and its current file in the cache -and removes the listing when dropped. Registering replaces any earlier -registration for the same connection id (the old one is dropped first). On drop, -if no other connection shows the file, a `Rescan` checks it against disk; if -unchanged, the content committed from the IDE remains. - -When files become outdated, `mark_outdated` sets their status and then: - -* sends `CurrentFileOutdated` to each connection whose current file is outdated; -* sends `TocOutdated` to every connection if the TOC is outdated; -* sends `Rescan` to the consumer for every outdated file *not* shown by a - connection. - -`TocChanged` is sent when the TOC's text changes on disk or the TOC is deleted. -Notification channels are unbounded because the cache lock is held while -sending; a failed send means the connection has exited and is ignored. - -Project cache map and eviction ------------------------------- - -The Server keeps a `CacheMap`: an LRU map from project root to cache. - -* Capacity is *n* × 10 + 1 for *n* connections. This balances memory against - the cost of reloading an evicted project. -* Insertion and resizing evict the least recently used caches **with no - connections** first. A cache with connections is never evicted; if all - entries have connections, the map is grown by one to make room. -* Lock order: the outer map lock before any single cache's lock. - -Shutdown --------- - -Only the `CacheMap` owns a cache strongly. When a cache is dropped, its watcher -is dropped (stopping the watch), the watcher's channel closes, the walker exits, -the consumer's sender closes, and the consumer exits. The consumer upgrades its -weak reference per message, so it never delays this. - -Error handling --------------- - -| Condition | Behavior | -| --------------------------------- | ----------------------------------------------------- | -| Watcher cannot start | Log a warning; continue without watching. | -| Watcher reports an error | Log only. | -| File unreadable (locked) | Leave cache unchanged; rely on a later watch event. | -| File not UTF-8 | Not translated; no definitions. | -| Translation fails | Log; discard stamp so it is retried. | -| Duplicate id | Reported at each reference; first definition stored. | -| Poisoned lock in `Drop` | Recover the inner value rather than panic. | - -Open questions and known gaps ------------------------------ - -* `IdResolution::Multiple` is not yet used by callers, so duplicates within a - single file are not yet reported distinctly. -* Line numbers in targets and fragments are always 0 until the markdown HTML - writer preserves them; the Client cannot yet scroll to an anchor. -* The `SaveOnScan` option (write auto-assigned ids back during a scan) is - unimplemented. -* Search indexing (id, contents, file name) is not yet designed. -* `notify` cannot yet filter event kinds at the source. -* On Windows, stamps lack change time and file index, so same-length edits - within the racy window depend on the 3-second rule. From 70ab13960ee6f904db540c542b2e4709ad7031df Mon Sep 17 00:00:00 2001 From: Azamat Ayapbergenov Date: Wed, 2 Dec 2026 00:25:12 +0500 Subject: [PATCH 4/8] Point cache-spec.md at the Markdown fragment specification --- server/src/processing/cache-spec.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/server/src/processing/cache-spec.md b/server/src/processing/cache-spec.md index 704d8cf5..2c73f0c5 100644 --- a/server/src/processing/cache-spec.md +++ b/server/src/processing/cache-spec.md @@ -142,11 +142,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; +of the following code/doc block; in a Markdown document, a fragment's content is +determined by the rules in [markdown-fragments-spec.md](markdown-fragments-spec.md). +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: From 3fc44f3a1da7434feb53d8137367c50ee5f726aa Mon Sep 17 00:00:00 2001 From: Azamat Ayapbergenov Date: Wed, 2 Dec 2026 00:41:12 +0500 Subject: [PATCH 5/8] Spec: only top-level headings bound a Markdown fragment --- server/src/processing/markdown-fragments-spec.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/server/src/processing/markdown-fragments-spec.md b/server/src/processing/markdown-fragments-spec.md index f8cf21f9..56b647b9 100644 --- a/server/src/processing/markdown-fragments-spec.md +++ b/server/src/processing/markdown-fragments-spec.md @@ -26,6 +26,9 @@ inside a list) belongs to its top-level block. inside a heading, that heading is the closest one, and it is included in the fragment. Skipped heading levels (a `###` directly under a `#`) make no difference: only the numeric levels are compared. +* **Only top-level headings count.** A heading nested inside another block (a + list item or block quote) is neither the "closest heading" nor a + section-ending heading; it is ordinary content of its top-level block. * **`following="N"`.** The fragment encloses the block containing the tag plus the next `N` top-level blocks, regardless of headings. `N` must be a whole number; `following="0"` encloses only the block containing the tag. A value @@ -107,6 +110,7 @@ names a target rather than a fragment. * A fragment tag in the last block of the document encloses only that block. * A tag inside a code block or inline code is literal text, not a fragment. * Nested block quotes and lists count as one top-level block. +* A heading inside a list item or block quote never starts or ends a section. ### Why this design From 41176ee27f32e538feef5198ffd7f4a31b7da3a9 Mon Sep 17 00:00:00 2001 From: Azamat Ayapbergenov Date: Wed, 2 Dec 2026 00:42:29 +0500 Subject: [PATCH 6/8] Point cache-spec.md at the Markdown fragment specification --- server/src/processing/cache-spec.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/server/src/processing/cache-spec.md b/server/src/processing/cache-spec.md index 2c73f0c5..48f510ff 100644 --- a/server/src/processing/cache-spec.md +++ b/server/src/processing/cache-spec.md @@ -143,11 +143,12 @@ contenteditable="false">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; in a Markdown document, a fragment's content is -determined by the rules in [markdown-fragments-spec.md](markdown-fragments-spec.md). -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; +determined by the rules in +[markdown-fragments-spec.md](markdown-fragments-spec.md) (in Markdown, +`following` counts top-level blocks rather than code/doc blocks). 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: From 56dd9846afecf0c39185e3402b4b947fd0c0bf63 Mon Sep 17 00:00:00 2001 From: Azamat Ayapbergenov Date: Wed, 2 Dec 2026 00:55:22 +0500 Subject: [PATCH 7/8] cache-spec: separate source-file and Markdown fragment behavior --- server/src/processing/cache-spec.md | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/server/src/processing/cache-spec.md b/server/src/processing/cache-spec.md index 48f510ff..c37e9154 100644 --- a/server/src/processing/cache-spec.md +++ b/server/src/processing/cache-spec.md @@ -140,16 +140,15 @@ things` is a `Target` with the `data-gather` attribute. It becomes a list of the content of fragments it refers to after hydration by the cache. An 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; in a Markdown document, a fragment's content is -determined by the rules in -[markdown-fragments-spec.md](markdown-fragments-spec.md) (in Markdown, -`following` counts top-level blocks rather than code/doc blocks). 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. +href="path/to/another/gather#zap">Zappy things`. In a source +file, a fragment's content by default includes the content of the current doc +block and the content of the following code/doc block. 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. In a Markdown document, a fragment instead encloses a section of +top-level blocks, and `following` counts top-level blocks; see +[markdown-fragments-spec.md](markdown-fragments-spec.md). Details: From 6106c9628df8f97a6ad96cc018abf59b1facbf9e Mon Sep 17 00:00:00 2001 From: Azamat Ayapbergenov Date: Wed, 2 Dec 2026 00:55:35 +0500 Subject: [PATCH 8/8] Add draft submission.md --- server/src/processing/submission.md | 111 ++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 server/src/processing/submission.md diff --git a/server/src/processing/submission.md b/server/src/processing/submission.md new file mode 100644 index 00000000..8c232662 --- /dev/null +++ b/server/src/processing/submission.md @@ -0,0 +1,111 @@ +Project 2 submission +==================== + +Team name: markdown-fragments-1 + +The specification consists of the file +[markdown-fragments-spec.md](markdown-fragments-spec.md), which defines what a +`` encloses in a Markdown document. + +Draft submission +---------------- + +### Azamat Ayapbergenov + +GitHub userid: azaayapbergenov + +#### Contributions + +Wrote the Markdown fragment specification (default extent, `following="N"`, +cached content, errors, edge cases, and the design alternatives) and prepared +this submission. + +#### Build and run test + +Prompting Copilot Fusion (standard effort) with "Verify that you can build and +run the project in the current git repo." gave a partial verification: + +* `cargo build --workspace` succeeded with warnings only. The documented build + then stopped at `cargo nextest run export_bindings` because `cargo-nextest` is + not installed; Node.js and pnpm are also missing, so the client and extension + builds could not run. +* The standalone server started and answered `/ping` with HTTP 200 `pong` when + given a temporary placeholder asset map. This verifies HTTP startup but not + the full UI, whose generated assets are missing. +* The worktree stayed clean; the smoke-test process and temporary files were + removed. + +Conclusion: the backend builds and the server starts; a complete build and UI +run are unverified until the missing tools are installed. + +#### Specification review rounds + +| Round | Findings | Main changes made | +| ----- | -------- | ----------------- | +| 1 | 2 | Replaced the `cache-spec.md` rule banning Markdown fragments with a link to `markdown-fragments-spec.md` | +| 2 | 2 | Only top-level headings count as section boundaries (new rule and edge case); `cache-spec.md` now says `following` counts top-level blocks in Markdown | +| 3 | 2 | `cache-spec.md` now describes source-file and Markdown fragment behavior (default extent and `following`) in separate sentences | +| 4 | **TODO** | **TODO** | + +#### Last specification review + +Prompting Copilot Fusion, standard effort, with +`Review the section named "Fragments in Markdown documents" in markdown-fragments-spec.md, writing findings to review.md` +produced the following output; strikethrough indicates LLM output that I deemed +incorrect or irrelevant. + +> **TODO: replace with the output of your final round once more rounds are +> done. The text below is round 3.** +> +> ### Findings +> +> #### High +> +> 1. ~~**The Markdown fragment rules are not implemented.** +> `server/src/processing.rs` (line 2711) explicitly replaces every fragment +> in a Markdown document with "fragments are not allowed in Markdown +> documents". The `server/src/processing/tests.rs` (line 2897) also asserts +> this obsolete behavior.~~ +> +> ~~This directly contradicts the section, which says Markdown fragments are +> valid and defines their default and `following` extents. The implementation +> also has no Markdown top-level-block walk or cleaned HTML cache storage for +> this feature.~~ +> +> #### Medium +> +> 2. **The cache specification still describes source-file fragment behavior as +> the general default.** `server/src/processing/cache-spec.md` (line 138) +> says that fragment content normally includes the current doc block and the +> next code/doc block, and that `following` counts code/doc blocks even +> though the following paragraph links Markdown readers to the new section. +> +> That wording is ambiguous for Markdown: the general default is +> section-based there, not current-doc-block-plus-next-block. It should +> explicitly separate source-file and Markdown behavior so the cache +> specification does not retain two incompatible `following` and default +> models. + +### (Team member 2 name) + +GitHub userid: Crazy24-x + +#### Contributions + +#### Build and run test + +#### Specification review rounds + +#### Last specification review + +### (Team member 3 name) + +GitHub userid: AlisherToxanbayev + +#### Contributions + +#### Build and run test + +#### Specification review rounds + +#### Last specification review