Skip to content

Live inbound sync for directory libraries (phase 2) - #738

Open
koppor wants to merge 31 commits into
open-directory-libraryfrom
directory-inbound-sync
Open

koppor wants to merge 31 commits into
open-directory-libraryfrom
directory-inbound-sync

Conversation

@koppor

@koppor koppor commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

📚 Directory-as-library stack — bottom → top, each builds on the one below:

  1. Programmatic Hayagriva writer (directory-as-library, phase 0) #736 · Hayagriva YAML writer
  2. Open folder as library (directory as library, phase 1) #737 · Open folder as library
  3. Live inbound sync for directory libraries (phase 2) #738 · Inbound file sync ← this PR
  4. Write-back to Hayagriva sidecars (directory as library, phase 3) #739 · Write-back to sidecars
  5. Groups panel mirrors the directory structure (phase 4, #10930) #740 · Directory-structure groups
  6. Pattern-driven pair renames for directory libraries (phase 5a) #741 · Pattern-driven pair renames
  7. Mirror directory libraries into a .bib with git-sync merge-back #743 · .bib mirror + merge-back
  8. Convert .bib libraries into directory libraries #744 · Convert .bib → directory
  9. Make directory libraries reachable through the REST API #745 · REST API support
  10. Split DirectoryLibrarySynchronizer into collaborators #760 · Split the synchronizer

Related issues and pull requests

Phase 2 of the "directory as library" plan (PLAN.md), stacked on #737 (this PR's base branch is open-directory-library; the diff shows only the sync commits). Related to JabRef#10930; no issue is closed by this PR.

PR Description

🤖 An open directory library now follows external file changes live: creating, editing, renaming, or deleting a sidecar or PDF on disk is reflected in the open library within about a second, while selection, undo history, and group membership survive. Renames are recognised as moves rather than as a delete plus an unrelated add. The library's own writes are ignored, so its changes are not re-imported.

jabref-contrib-policy:4.2:reviewed​:ok

Analogies

Like honey trickling back into the comb, external edits now find their way into the open library without anyone carrying them. Like chocolate that snaps along the same grooves no matter who breaks it, the same entry instances survive renames and edits — the pieces keep their shape. And like the moon steadying the tides, the one-second poll quietly keeps two worlds — disk and table — moving together.

Steps to test

  1. Open a folder as library (File > Open folder as library...) with a few sidecars.
  2. While the tab is open, from a terminal: add a new .yml, edit an existing one, rename one (mv a.yml b.yml), delete one, and add/remove a PDF next to a sidecar.
  3. Within about a second each change appears in the main table; the renamed file's entry stays selected if it was selected.

Row added live after creating a sidecar externally

Guarded by DirectoryLibrarySynchronizerTest (10 tests: create/change/delete, multi-entry diff, rename grace window, self-echo fingerprint, PDF link/stub handling, non-Hayagriva takeover).

AI usage

Claude Code (model claude-fable-5).

AI CHECKLIST.md walkthrough

1. Code self-review

Nullability and control flow
  • No == null / != null in new code except nullable JDK returns (Path.getParent(), map lookups) expressed via Optional.ofNullable where streamable.
  • No Objects.requireNonNull(...) — orElseThrow with message for the constructor contract.
  • New classes annotated with @NullMarked.
  • Optional consumed with ifPresent / map / orElseThrow.
  • [/] StringUtil.isBlank(...) — not needed.
Exceptions
  • Only IOException / NoSuchAlgorithmException caught specifically.
  • No RuntimeException/IllegalStateException thrown (IllegalArgumentException for a violated constructor precondition; AssertionError only for the impossible missing-SHA-256 case).
  • Logged exceptions passed as last logger argument.
Style and idioms
  • BibEntry withers used for new entries.
  • Modern Java: records, List.of(), SequencedMap, streams.
  • [/] Regexes — none added.
  • Long-running work on a dedicated daemon executor; UI marshalling injected (UiTaskExecutor::runInJavaFXThread), no new Thread() in application flow (the executor's thread factory names its worker).
  • No commented-out code, no trivial comments.
  • Markdown Javadoc (///).
User-facing text
  • [/] No new user-facing strings (sync is silent; warnings only in logs).
Security
  • [/] No HTML output.
Tests
  • DirectoryLibrarySynchronizerTest drives the handlers deterministically (injected clock for the grace window, direct-run marshaller); no sleeps, no polling.
  • Plain JUnit asserts, @TempDir, no @DisplayName, exceptions propagate.

2. Verification commands

  • ./gradlew :jablib:check (full suite; only the known environmental RemoteCommunicationTest port-conflict failures on this machine).
  • ./gradlew :jablib:checkstyleMain :jablib:checkstyleTest :jabgui:checkstyleMain.
  • ./gradlew :jablib:modernizer.
  • ./gradlew :rewriteRun left no diff.
  • ./gradlew :jablib:javadoc.
  • ./gradlew traceRequirements (req~directory-library.inbound-sync~1 covered).
  • npx markdownlint-cli2 on changed Markdown.
  • [/] IntelliJ-format docker image — not runnable here; CI format job is the backstop.

3. Documentation

  • CHANGELOG.md entry added (TODO replaced with this PR's link after creation).
  • Requirement added to docs/requirements/directory-library.md.
  • [/] ADR — covered by the existing ADR-0072 (this phase implements its sync section).

4. Pull request

  • PR body from the template, every section filled, HTML comments removed, all items marked.
  • Created from a body file via gh api (cross-repo head, stacked base open-directory-library).
  • CHANGELOG TODO replaced after creation, committed and pushed.

Checklist

  • I own the copyright of the code submitted and I license it under the MIT license
  • If AI tools were used, I disclosed them in the "AI usage" section and reviewed, understood, and take full ownership of all AI-generated code
  • I manually tested my changes in running JabRef (externally created/edited/renamed sidecars while the library tab was open on the X display; see screenshot)
  • I added JUnit tests for changes (if applicable)
  • I added screenshots in the PR description (if change is visible to the user)
  • [/] I added a screenshot in the PR description showing a library with a single entry with me as author and as title the issue number
  • I added one sentence (max 20 words) to CHANGELOG.md describing the change from the user's point of view (if the change is visible to the user)
  • I checked the user documentation for up to dateness and submitted a pull request to our user documentation repository — deferred until the feature stabilizes (write-back phase); tracked in PLAN.md phase 5

🤖 Generated with Claude Code

koppor and others added 10 commits July 14, 2026 00:07
A DirectoryLibrarySynchronizer registers with the Commons-IO
DirectoryMonitor (promoted from jabgui to jablib, per ADR-0030) and
applies external create/change/delete events for .yml/.pdf files to the
open library: changed sidecars update the existing BibEntry instances
field by field, renames are detected via a grace window over the
monitor's delete+create events and keep the affected entries, appearing
PDFs link to their sidecar entry or become stubs, and disappearing PDFs
unlink or remove their stub. All mutations carry
EntriesEventSource.SHARED, and recordWrittenFile lets the upcoming
write-back direction fingerprint its own writes so they are not
re-imported.

Late-joining observers are baselined with a silent first poll,
otherwise the running monitor reports every existing file as created
and duplicates the scanned entries.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
DirectoryMonitor and DirectoryLibrarySynchronizer expose commons-io
monitor types in exported-package signatures (flagged by
checkModuleDirectivesScope).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Adapts the synchronizer to the new PdfEntryFactory: externally appearing
PDFs without a sidecar now get metadata extracted from the PDF instead
of a filename-only stub, same as during the initial scan.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Externally appearing PDFs also get a generated citation key after
insertion, matching the scan behavior.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The enrichment task reuses the factory instance that also serves the
synchronizer; externally dropped PDFs keep the synchronous extraction
on the directory-sync thread.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
koppor and others added 2 commits July 17, 2026 01:45
External creation, modification, deletion, and renaming of .md files
with Hayagriva frontmatter now flows into the open directory library
like the plain .yml sidecars; the notes body maps to the entry's
comment fields.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q5Y5GTihE9rZxKrvPqnHV4
koppor and others added 8 commits September 3, 2026 03:19
Resync layer 3 of the stack (no conflicts).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DDcHNMt9fPWnpYaHheFvry
A deletion undone within the grace window no longer removes live entries, renames of sidecars with a paired PDF keep the entry instances, an editor polled mid-write only stages the entries instead of dropping them, and events arriving during shutdown are discarded instead of failing the shared monitor thread. Sidecar precedence is deterministic; the baseline snapshot runs off the caller's thread.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Vr3E1Gg5DRU4LQDDVnhPys
# Conflicts:
#	jabgui/src/main/java/org/jabref/gui/importer/actions/OpenDirectoryLibraryAction.java
#	jablib/src/main/java/org/jabref/model/database/BibDatabaseContext.java
Fixes the CI format check.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DDcHNMt9fPWnpYaHheFvry
Resync with upstream (no conflicts).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DDcHNMt9fPWnpYaHheFvry
Upstream added a 0071 ADR after this stack claimed the number, so the
MADR duplicate-ID check failed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (11)

Grey Divider


Action required

1. Citation-key edits replace selected entries 🐞 Bug
Description
applyChangedFile matches parsed and existing entries by citation key, so changing a sidecar's
top-level key queues removal of the existing entry and insertion of a new one. The replacement loses
the original entry identity and, unlike a new-file import, does not acquire the paired PDF link.
Code

jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[R319-325]

+        parsedByKey.forEach((key, parsedEntry) ->
+                Optional.ofNullable(knownByKey.get(key)).ifPresentOrElse(
+                        knownEntry -> fieldUpdates.add(() -> copyContent(parsedEntry, knownEntry)),
+                        () -> {
+                            catalog.register(parsedEntry, file, key);
+                            toInsert.add(parsedEntry);
+                        }));
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Changing a sidecar's citation key replaces its live entry and drops its paired PDF link.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[311-345]
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibraryCatalog.java[9-34]
## Recommended Fix
Reconcile a key rename against the existing file's stable entry identity, update the key in place with a SHARED event source, and update the catalog's stored Hayagriva key. Preserve the existing PDF link and test a key-only edit.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Linked folders can import outside files 🐞 Bug
Description
startWatching constructs a recursive observer whose directory filter accepts a symlink to a
directory and does not check whether reported files resolve beneath the chosen root. A linked
directory under an editable library can therefore lead the watcher to parse sidecars or extract PDF
metadata outside that root, although the initial scanner does not recurse through directory
symlinks.
Code

jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[R144-147]

+        FileAlterationObserver observer = FileAlterationObserver.builder()
+                                                                .setRootEntry(new FileEntry(root.toFile()))
+                                                                .setFileFilter(FileFilterUtils.and(notHidden, relevantFiles))
+                                                                .getUnchecked();
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The recursive watcher can follow a directory link and import files outside the selected library root.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[136-156]
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[210-219]
## Recommended Fix
Exclude symlinked directories from observer traversal and validate reported paths against the real library root before reading them. Test a linked directory pointing outside the selected root.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. External sidecar edits wipe group membership 🐞 Bug
Description
copyContent clears every field on the live entry that is missing from the freshly parsed sidecar,
except file, so JabRef-only fields such as groups (where explicit group membership is stored)
and special fields like ranking or read status are removed. Any external edit to a sidecar therefore
silently takes the entry out of its manual groups, which contradicts the Javadoc's claim that group
membership survives. The same comparison in sameContent also blocks rename detection for grouped
entries, so they are deleted and re-created instead of moved.
Code

jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[R358-362]

+        target.getFields().stream()
+              .filter(field -> StandardField.FILE != field)
+              .filter(field -> source.getField(field).isEmpty())
+              .toList()
+              .forEach(field -> target.clearField(field, EntriesEventSource.SHARED));
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`copyContent` clears every target field the sidecar does not contain except `file`, so `groups` and special fields are lost on each external edit. `sameContent` compares those same fields, so grouped entries are never recognised as moved.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[350-364]
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[437-441]
## Recommended Fix
Define one set of fields the synchronizer keeps (FILE, GROUPS, the SpecialField values, and any other JabRef-internal fields Hayagriva cannot hold). Leave those fields out of the clearing step in `copyContent` and out of `fieldsWithoutFile`. Add a test that assigns an entry to a group, edits its sidecar externally, and checks the group membership is still there.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

4. Rapid sidecar events leave duplicate rows 🐞 Bug
Description
insertNewEntries registers entries in the catalog before its JavaFX-marshalled database insertion,
while entriesOf resolves catalog IDs only against entries already in the database. A second event
before that insertion can import the file again; a delete in the same interval finds no entry to
remove and leaves a stale row instead.
Code

jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[R302-308]

+    private void insertNewEntries(Path file, List<BibEntry> newEntries) {
+        newEntries.forEach(entry -> catalog.register(entry, file, entry.getCitationKey().orElseThrow()));
+        // Safe without event source: the entry is not yet inserted, so no listeners see this
+        findPairedPdf(file).ifPresent(pdf -> newEntries.getFirst()
+                                                       .addFile(new LinkedFile("", root.relativize(pdf), StandardFileType.PDF.getName())));
+        modelUpdateMarshaller.accept(() ->
+                databaseContext.getDatabase().insertEntries(newEntries, EntriesEventSource.SHARED));
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Deferred database insertion lets subsequent sidecar events miss entries already registered in the catalog.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[245-255]
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[302-345]
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[411-419]
## Recommended Fix
Serialize catalog and database transitions together or track pending insertions in event reconciliation. Cover create/change/create and create/delete before queued JavaFX updates execute.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View medium (7)
5. Quickly deleted PDFs remain in the library 🐞 Bug
Description
handlePdfCreated defers insertion, but handlePdfDeleted searches the current database for links
before deciding whether to schedule a removal. If deletion is handled before the queued insertion
runs, it finds nothing and the earlier runnable subsequently inserts an entry linked to a
nonexistent PDF.
Code

jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[R384-390]

+    private void handlePdfDeleted(Path pdf) {
+        String relativeLink = root.relativize(pdf).toString();
+        List<BibEntry> linking = databaseContext.getDatabase().getEntries().stream()
+                                                .filter(entry -> entry.getFiles().stream()
+                                                                      .anyMatch(linked -> relativeLink.equals(linked.getLink())))
+                                                .toList();
+        for (BibEntry entry : linking) {
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A PDF delete can be lost while the preceding create's database insertion awaits JavaFX execution.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[366-403]
## Recommended Fix
Track pending PDF operations or apply create and delete in an ordered model-update sequence that resolves links when each update executes. Test a delete delivered before the create runnable executes.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Renamed PDFs lose their entry identity 🐞 Bug
Description
handlePdfDeleted removes a PDF-only entry immediately, and handlePdfCreated constructs a
separate entry for the new path rather than matching the two events as a move. Renaming a
sidecar-less PDF therefore replaces its entry and loses its selection and history even when its
contents are unchanged.
Code

jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[R391-395]

+            boolean isStub = catalog.sourceOf(entry).isEmpty();
+            modelUpdateMarshaller.accept(() -> {
+                if (isStub) {
+                    databaseContext.getDatabase().removeEntries(List.of(entry), EntriesEventSource.SHARED);
+                } else {
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A PDF-only rename removes its original entry and imports a replacement.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[366-403]
## Recommended Fix
Stage PDF deletions long enough to match a corresponding creation and update the existing entry's link on a confirmed move. Preserve the entry object and test PDF-only renames.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. Malformed Markdown removes live entries 🐞 Bug
Description
handleFileChanged stages deletion whenever looksLikeSidecar is false, but Markdown recognition
parses the frontmatter and also returns false for malformed YAML. An invalid edit to a previously
valid Markdown sidecar consequently expires into entry removal instead of reaching the branch that
preserves an unparseable sidecar's existing entries.
Code

jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[R232-237]

+        if (!looksLikeSidecar(file)) {
+            // The file stopped being a sidecar — or an editor that truncates and rewrites was
+            // polled mid-write, so the entries are only staged: a complete sidecar arriving
+            // within the grace window keeps them
+            stageDeletion(file, knownEntries);
+            return;
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Malformed frontmatter is treated as loss of sidecar status and eventually removes its entries.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[222-243]
- jablib/src/main/java/org/jabref/logic/directorylibrary/MarkdownSidecar.java[49-66]
## Recommended Fix
Distinguish disappearance of recognizable frontmatter from a parsing failure in an existing sidecar. Retain existing entries for invalid YAML and test a malformed Markdown edit beyond the type line.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


8. Edited moves replace existing entries 🐞 Bug
Description
importFile recognizes a staged deletion as a move only when the new sidecar matches every non-file
field and its entry order exactly. Editing a sidecar while moving it fails that test, causing a new
entry to be inserted and the original to be removed when the grace period expires.
Code

jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[R290-295]

+        // A staged deletion with equal content is this file being moved, not new content
+        stagedDeletions.entrySet().stream()
+                       .filter(staged -> entriesMatch(staged.getValue().entries(), newEntries))
+                       .map(Map.Entry::getKey)
+                       .findFirst()
+                       .ifPresentOrElse(movedFrom -> {
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Exact content matching loses identity when a sidecar is edited during its move.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[258-300]
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[427-440]
## Recommended Fix
Use a move-matching strategy that can identify an edited file without relying solely on complete field equality; after identifying the move, apply its parsed changes to the original entries. Test a rename combined with a field edit.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


9. Background thread iterates live entry list unsafely 🐞 Bug
Description
entriesOf and handlePdfDeleted iterate databaseContext.getDatabase().getEntries() on the
directory-sync thread without a synchronized snapshot, while queued insertions and removals mutate
the list on the JavaFX thread. When filesystem events overlap with those updates, reconciliation can
read inconsistent contents or throw ConcurrentModificationException, ending the executor task and
losing the event without a synchronizer log entry.
Code

jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[R416-418]

+        Map<String, BibEntry> byId = new HashMap<>();
+        databaseContext.getDatabase().getEntries().forEach(entry -> byId.put(entry.getId(), entry));
+        return ids.stream().flatMap(id -> Optional.ofNullable(byId.get(id)).stream()).toList();
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The directory-sync handlers iterate `BibDatabase.getEntries()` while JavaFX updates mutate the underlying list, allowing inconsistent reconciliation or `ConcurrentModificationException` and leaving a failed event unlogged.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[384-390]
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[411-419]
## Recommended Fix
In `entriesOf` and `handlePdfDeleted`, iterate `getEntriesSnapshot()` instead of `getEntries()`. Preserve reconciliation order when the JavaFX queue is backed up, and catch and log exceptions inside executor tasks so failed events are not silent.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


10. Adding a PDF with its sidecar creates duplicates 🐞 Bug
Description
handlePdfCreated creates a PDF-only stub when findSidecarEntry finds no entry in both the
catalog and database, and insertNewEntries later links that PDF to the sidecar entry without
removing the stub. When a paper.pdf and paper.yml pair is copied in together, the PDF event may
run first, or the sidecar may be registered but still awaiting asynchronous database insertion;
either way, the open library can retain two entries where an initial scan would create one.
Code

jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[R377-381]

+        BibEntry entry = pdfEntryFactory.createEntry(pdf, root, databaseContext);
+        modelUpdateMarshaller.accept(() -> {
+            databaseContext.getDatabase().insertEntries(List.of(entry), EntriesEventSource.SHARED);
+            pdfEntryFactory.generateCitationKeyIfMissing(entry, databaseContext);
+        });
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A PDF-only stub created before its sidecar is available to `findSidecarEntry` remains alongside the sidecar entry that later links the same PDF. This can happen whether the PDF event runs first or the sidecar is registered but its database insertion is still pending.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[274-309]
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[366-382]
## Recommended Fix
When importing a sidecar and finding its paired PDF, locate any PDF-only stub with no catalog source that links the same relative path. Merge or replace that stub, removing it in the same marshalled update that inserts the sidecar entry so the PDF has only one entry. Optionally, have `handlePdfCreated` check the catalog independently of the database for a sibling sidecar whose insertion is pending. Test both file-event orders, including sidecar creation while initial PDF enrichment is pending.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


11. Closing a tab quickly leaves a watcher polling forever 🐞 Bug
Description
startWatching queues a baseline snapshot followed by monitor.addObserver, but shutdown()
removes the observer only if it is already registered and then shuts down an executor that still
runs queued tasks. If a tab closes while the baseline walk is queued or running, the observer can be
added after removal, leaving the shared DirectoryMonitor walking the closed library every second
and discarding its events until JabRef exits, with another observer retained on each reopening.
Code

jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[R153-161]

+        syncExecutor.execute(() -> {
+            observer.checkAndNotify();
+            monitor.addObserver(observer, this);
+        });
+    }
+
+    public void shutdown() {
+        Optional.ofNullable(watch).ifPresent(active -> active.monitor().removeObserver(active.observer()));
+        syncExecutor.shutdown();
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Asynchronous observer registration can occur after tab shutdown has removed the observer, leaving the shared monitor polling a closed library.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/directorylibrary/DirectoryLibrarySynchronizer.java[136-162]
## Recommended Fix
Coordinate observer registration and removal with a `closed` flag guarded by `synchronized` or an `AtomicBoolean`. Have the baseline task skip `addObserver` when closed, and set the flag and remove the observer under the same lock in `shutdown()` so an in-flight baseline cannot attach after closure. Test closing while baseline work is queued and while it is running. Consider `shutdownNow()` and `setExecuteExistingDelayedTasksAfterShutdownPolicy(false)` so scheduled staged-deletion commits do not touch the closed library.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can reply 'qodo' on any finding to push back, ask questions, or dig deeper

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant