Initial import of LogDarioSeq baseline

Establishes version control for the personal Logseq DB fork before
starting the server-client architecture migration and domain features
described in docs/agent-guide and the approved implementation plan.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5 committed 2026-08-25 15:32:15 +02:00
commit 40631362b3
2016 files changed
+543898

No files matched your search

@@ -0,0 +1,35 @@
# Building Logseq Desktop app for Windows on Ubuntu
## Intro
My Logseq dev machine is on Ubuntu 18.x and my production machine is running Windows 10, I needed a way to compile the Logseq desktop APP for Windows.
I tried & failed to make the "build" run on my windows machine but I did, however, succeed in letting my Ubuntu machine make Windows x64 files
## Pre-requisites
These are the steps I took to make it work on my Ubuntu machine, sharing them hoping it helps someone else. I assume you have all the basic pre-requisites for Logseq, if not you can find them at https://github.com/logseq/logseq#1-requirements
1. clone Logseq repo if you haven't already
`git clone https://github.com/logseq/logseq/`
1. Install wine
```shell
sudo dpkg --add-architecture i386
sudo apt update
sudo apt install wine64 wine32
```
1. Install winetricks & install dotnet using winetricks
```shell
sudo apt install winetricks
winetricks dotnet46
```
1. Install nuget and mono (N.B. I had to install mono-complete for it to work)
```shell
sudo apt install nuget
sudo apt-get install mono-complete
```
1. in `~/logseq/resources/package.json` line 10 `"electron:make": "electron-forge make --platform=win32 --arch=x64 --asar",`
1. Compile using
```shell
cd logseq
pnpm install
pnpm release
pnpm release-electron
```
the executable should be in the `static/out/make/squirrel.windows/x64/` folder
+29
View File
@@ -0,0 +1,29 @@
- Accessibility is a vague term, which is why it is usually misunderstood. It is not just about people with specific disabilities. You can read more about [what is accessibility](https://developer.mozilla.org/en-US/docs/Learn/Accessibility/What_is_accessibility#so_what_is_accessibility) and [diverse abilities and barriers](https://www.w3.org/WAI/people-use-web/abilities-barriers/).
- ## Web Content Accessibility Guidelines
- [WCAG](https://www.w3.org/WAI/standards-guidelines/wcag/) (Web Content Accessibility Guidelines) is the international standard for web content accessibility, developed by [W3C](https://www.w3.org/). Logseq is a web application, so conforming with WCAG should be our first priority. In general, there is no simple way to determine if a website is accessible or not, but WCAG can help us make the tool usable by as many people as possible.
- ## Levels of conformance
- There are three levels of conformance defined by WCAG
- Level **A** is the minimum level.
- Level **AA** includes all Level A and AA requirements.
- Level **AAA** includes all Level A, AA, and AAA requirements.
- Many organizations strive to meet Level AA. The reason behind this decision, is that in some cases AAA standard is too strict. That doesn't mean that triple-A issues should be disregarded. On the contrary, all of them should be handled if possible.
- We can also provide alternative options in order to conform with AAA standards. For instance, our default themes can aim for AA, but we can provide a high-contrast theme that aims for AAA. Providing [alternative versions](https://www.w3.org/WAI/GL/2007/05/alternate-versions.html) with different levels of conformance is permitted according to WCAG, if there is an accessible way to reach those alternatives.
- ## Simple development guidelines
- Use semantically correct markup whenever possible. Every time you are about to decide which html tag you are going to use, choose the one that behaves the way you want it. For example, let's say you want to create an element that looks like plain text, but triggers an action on click. Usually, the best approach would be to create a `<button>` and make it look like a `<span>` using css. If you use a `span`, you will also have to override other html attributes like `tabindex` and `role` to make the element behave like a button. This is almost always a bad sign, and should be avoided. If you use the appropriate html element, the browser will be able to properly handle it.
- Do not skip headings. People who use screen readers and a keyboard to navigate through the app, use the headings structure to quickly jump to areas of interest. Skipping headings to visually conform with the design, makes this hard for them. If you want to create a heading that looks like an `<h4>` but is in terms of document structure an `<h2>`, use the latter and make it look like an `<h4>`.
- A more [in-depth guide about HTML and accessibility](https://developer.mozilla.org/en-US/docs/Learn/Accessibility/HTML).
- ## Advanced concepts
- Focus management is extremely important for [keyboard navigation](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Keyboard). Focusable elements can help people with motor disabilities navigate. [Focus Order](https://www.w3.org/TR/UNDERSTANDING-WCAG20/navigation-mechanisms-focus-order.html) plays an important role in this.
- ## Automated testing
- There is a [huge list of tools](https://www.w3.org/WAI/ER/tools/) that can help us test our application. Most of them use [axe-core](https://github.com/dequelabs/axe-core) internally. There are [browser extensions](https://www.deque.com/axe/browser-extensions/) based on axe, a [VSCode Linter Plugin](https://marketplace.visualstudio.com/items?itemName=deque-systems.vscode-axe-linter) and also [multiple community projects](https://github.com/dequelabs/axe-core/blob/develop/doc/projects.md#community-projects).
- Basic accessibility testing could be integrated into our CI by adding a dedicated browser-based accessibility test line, for example with a Playwright-compatible axe adapter such as [@axe-core/playwright](https://github.com/dequelabs/axe-core-npm/blob/develop/packages/playwright/README.md). The current repository does not maintain that test line today, so it would need to be added explicitly instead of assumed to exist.
- ## Manual testing
- In theory, all of the cases described by WCAG should be testable. In practice, there are issues that can't be replicated by code. Also, manual accessibility testing would help us have a better understanding of the difficulties that certain people might encounter. Even if all the individual cases pass the tests, the overall navigation might be nonsensical.
- ### Manual accessibility testing musts
- Keyboard-only navigation
- Screen reader testing and compatibility
- Zooming up to 200%
- Manually testing contrast issues that can't be automated
- ### Screen readers
- Apple and Android mobile devices have build-in screen readers.
- For desktop, [NVDA](https://help.gnome.org/users/orca/stable/index.html.en) is the most popular choice. For linux, [Orca](https://help.gnome.org/users/orca/stable/index.html.en) is a good option.
@@ -0,0 +1,43 @@
# ADR 0001: Node.js DB Sync Server Adapter for Self-Hosting
Date: 2026-01-30
Status: Proposed
## Context
Logseq's DB sync currently assumes a hosted environment for the sync server. This limits users who want to self-host the server on their own infrastructure and avoid reliance on Cloudflare-specific services.
We need a portable server adapter that can run on standard Node.js runtimes (Docker, bare metal, VPS, or on-prem) while preserving the existing DB sync protocol and client behavior.
## Decision
Create a Node.js server adapter for DB sync that:
- Runs on a standard Node.js runtime (LTS) without Cloudflare dependencies.
- Implements the existing DB sync protocol and endpoints without breaking client compatibility.
- Supports self-hosting via a documented configuration (env vars, ports, storage backends).
- Allows pluggable storage and auth providers to match the current hosted behavior.
The adapter will be a peer implementation of the existing server entrypoint, sharing protocol definitions and core logic where possible.
## Options Considered
1) Continue Cloudflare-only hosting
- Pros: no new maintenance
- Cons: blocks self-hosting; vendor lock-in
2) Rewrite the sync server in a new standalone service
- Pros: full control, clean slate
- Cons: high risk, larger scope, protocol divergence risk
3) Add a Node.js adapter around the existing sync server logic (chosen)
- Pros: minimizes protocol drift; faster to ship; leverages existing logic
- Cons: requires adapter layer and some refactoring for portability
## Consequences
- Additional maintenance surface for Node.js runtime compatibility.
- Requires careful separation of platform-specific code from shared sync logic.
- Enables self-hosting and reduces dependence on Cloudflare.
- May require new CI coverage for Node.js adapter builds and basic integration tests.
## Follow-up Work
- Identify Cloudflare-specific APIs and replace with portable interfaces.
- Define storage and auth provider interfaces for the adapter.
- Add documentation for self-hosting setup and deployment examples.
- Add minimal integration tests to validate protocol compatibility.
+113
View File
@@ -0,0 +1,113 @@
# ADR 0002: Undo/Redo scoped to local changes in worker sync
Date: 2026-01-28
Status: Accepted
## Context
The worker-based db-sync flow applies remote updates directly to the local DB.
Undo/redo must remain usable for the current user without replaying or reverting
server changes. The system already supports tx-meta flags (e.g., :local-tx?,
:gen-undo-ops?, :undo?, :redo?) and has conflict checks in undo logic.
We must ensure undo/redo never attempts a transaction that would result in
invalid client or server data. We also want a simple, sane model that avoids
tracking per-remote update history.
Constraints and goals:
- No server echo of the user's own txs back to the same client.
- Best effort undo: if conflicts make an undo unsafe, skip it and keep data
valid (never force invalid data).
- Remote updates must not create undo history.
- Local updates must create undo history as before.
## Decision
1) Only local txs may generate undo/redo ops. A tx is local if and only if
tx-meta contains :local-tx? true.
2) All remote/apply/rebase/import paths must set :local-tx? false and
:gen-undo-ops? false.
3) Undo/redo will be "best effort": if reversing a tx would violate invariants
(e.g., moved block, deleted parent, remaining children), the undo op is
dropped and history is cleared for that repo to prevent invalid data.
This keeps undo/redo stable and ensures remote updates never appear in the
user's undo stack.
## Architecture
### Source of truth for origin
- :local-tx? is the sole origin flag.
- Local changes (UI/outliner ops) attach :local-tx? true at the time of
submission to the worker.
- Remote changes (db-sync apply-remote, rtc remote update, snapshot import) set
:local-tx? false and :gen-undo-ops? false.
### Undo/redo recording
- Undo history is recorded only when tx-meta has :local-tx? true.
- Additional existing gates remain: :outliner-op is present, :gen-undo-ops?
is not false, and :create-today-journal? is not true.
- Redo stack is cleared on any new local undo-recorded op (existing behavior).
### Undo/redo execution safety
- Reverse datoms are computed from original tx-data.
- Conflict detection remains in place (moved blocks, deleted parents, children
still exist). These are treated as safe failures for best-effort undo.
- If a conflict is detected or reverse-tx is empty, the undo op is dropped and
history cleared for that repo to avoid invalid transacts.
- Undo/redo execution uses tx-meta flags :undo?/:redo? and :gen-undo-ops? false
to avoid recursive undo generation.
## Consequences
- Undo/redo only affects user-originated changes, never server updates.
- In rare cases, undo may be skipped after a remote conflict, but the database
remains valid.
- The model stays simple: no remote history tracking or per-entity versioning.
## Plan
1) Confirm the origin flag path
- Verify all local transact entry points set :local-tx? true
(e.g., frontend.db.transact/transact, apply-outliner-ops).
- Verify all remote/apply/rebase/import paths set :local-tx? false and
:gen-undo-ops? false (db-sync apply-remote, rtc remote updates,
snapshot import, db restore).
2) Gate undo generation on :local-tx?
- Update frontend.undo-redo/gen-undo-ops! to require :local-tx? true in
tx-meta in addition to existing checks.
3) Enforce best-effort safety
- On conflict (moved block, deleted parent, remaining children) or on
missing reverse tx data, drop the undo op and clear history for repo.
4) Documentation
- Update relevant internal docs or comments near undo/redo about the origin
flag and best-effort semantics.
## Test Scenarios (Manual)
1) Local change only
- Create a block, undo, redo.
- Expected: undo/redo works and affects only local changes.
2) Remote change only
- Receive a server update that modifies a block.
- Expected: undo stack is unchanged; undo does not revert remote update.
3) Local change after remote update
- Remote updates a block; user edits same block; undo.
- Expected: undo reverts only the user's edit; remote update remains.
4) Remote delete of parent before undo
- User creates child; remote deletes parent; user tries undo.
- Expected: undo is skipped safely; history cleared; no invalid data.
5) Remote move before undo
- User moves block; remote moves or deletes target; user tries undo.
- Expected: undo is skipped safely; history cleared; no invalid data.
6) Mixed local ops and remote tx batch
- Interleave local edits and remote sync.
- Expected: only local edits appear in undo stack; undo never produces
invalid data.
## Open Questions
- Do we need a user-visible notification when undo is skipped due to conflicts,
or is silent failure acceptable?
Silent failure acceptable.
@@ -0,0 +1,87 @@
# ADR 0003: Optional Encryption When Creating a Sync Graph
Date: 2026-02-11
Status: Proposed
## Context
Sync graph creation currently assumes encrypted graph data. This is a good default
for privacy, but it is not always the right choice:
- Self-hosted users may run trusted infrastructure and prefer plaintext storage.
- Some users need easier integration with external tools that read graph data
directly from storage or APIs.
- Encryption/decryption adds CPU and complexity during sync operations.
We need to support both privacy-first and integration-first workflows without
breaking compatibility for existing encrypted graphs.
## Decision
Add an explicit graph-level option when creating a sync graph:
- `Encrypt graph data` (boolean)
Behavior:
1) Default remains encrypted for safety.
2) Users can disable encryption at graph creation time.
3) The selected mode is stored as graph metadata and treated as immutable for
that graph after creation.
There's already `:logseq.kv/graph-rtc-e2ee?`.
4) Existing encrypted graphs remain unchanged.
When encryption is disabled:
- Client does not generate/import graph encryption keys for sync payloads.
- Sync payloads and assets are sent as plaintext over TLS transport.
- Client skips encrypt/decrypt steps in DB and asset sync pipelines.
When encryption is enabled:
- Current E2EE behavior remains unchanged.
## Options Considered
1) Keep encryption mandatory
- Pros: strongest default privacy, simpler policy
- Cons: blocks valid self-hosted and interoperability use cases
2) Disable encryption by default
- Pros: easier integrations out of the box
- Cons: unsafe default for most users
3) Make encryption selectable at graph creation (chosen)
- Pros: keeps secure default while enabling self-hosted/integration scenarios
- Cons: introduces dual execution paths and UI/UX complexity
## Consequences
- Positive:
- Better support for self-hosted deployments.
- Easier interoperability with external tooling.
- Lower client CPU overhead for non-encrypted graphs.
- Negative:
- More branching in sync and asset code paths.
- Higher test matrix (encrypted vs non-encrypted).
- Users must understand security tradeoffs.
## Follow-up Work
1) API and protocol
- Add graph creation flag for encryption mode.
- Persist encryption mode in graph metadata and return it in graph info.
2) Client graph creation UI
- Add `Encrypt graph data` option with warning/help text.
- Default ON, with clear explanation of tradeoff.
3) DB sync and asset sync behavior
- Gate encryption and key-management logic on graph mode.
- Ensure non-encrypted graphs do not call key generation/import paths.
4) Migration and compatibility
- Keep existing graph behavior unchanged.
- Do not auto-migrate graph encryption mode.
5) Testing
- Add/create-path tests for both modes.
- Add sync + asset upload/download tests for encrypted and non-encrypted graphs.
- Add regression tests for mixed environments (desktop/web/self-hosted).
## Open Questions
- Should self-hosted servers be able to enforce a default or only allow one mode?
Defaults to encryption mode.
- Do we need a future migration flow to move a graph between encrypted and
non-encrypted modes?
Probably, let's leave it for future.
@@ -0,0 +1,66 @@
# ADR 0004: Sync batches are ordered tx entries with persisted `:outliner-op`
Date: 2026-03-16
Status: Accepted
## Context
DB sync previously treated a client upload batch as one transit-encoded tx blob
and the client pull path could flatten remote tx entries into one local apply.
That made sync failures hard to debug because:
- a failed sync apply did not clearly identify which tx entry failed
- the server did not persist the original `:outliner-op`
- the client carried cross-batch tempid repair logic to make split txs work
We want sync errors to point to one specific tx entry and one specific
operation intent.
We also want the server and client to follow the same mental model:
- a batch is an ordered list of tx entries
- each tx entry is applied one by one
- each tx entry may carry its own `:outliner-op`
## Decision
1) `tx/batch` now sends a list of tx entries instead of one encoded tx blob.
2) Each tx entry contains:
- `:tx`
- optional `:outliner-op`
3) The server applies tx entries one by one, in order.
4) The server persists `:outliner-op` in `tx_log` and returns it in `pull/ok`.
5) The client applies pulled tx entries one by one and includes the returned
`:outliner-op` in tx-meta for remote apply.
6) Cross-batch tempid reuse is unsupported by contract. A tempid must be fully
resolved within a single tx entry.
## Storage and Protocol Notes
- The persisted sync tx log is the per-graph SQLite store initialized in
`logseq.db-sync.storage`, not the Cloudflare D1 graph index schema.
- Because of that, `outliner_op` is added via runtime SQLite schema setup for
the per-graph store, not a D1 migration under `worker/migrations/`.
- `pull/ok` entries now have shape:
- `{:t ... :tx ... :outliner-op ...}`
- `tx/batch` entries now have shape:
- `{:tx ... :outliner-op ...}`
## Consequences
- Positive:
- Sync failures can be traced to one tx entry and its `:outliner-op`.
- Client and server now share the same ordered per-entry apply model.
- The protocol is simpler than carrying cross-batch tempid repair logic.
- Negative:
- Older assumptions that tempids can be reused across tx entries are no
longer valid.
- The wire format changed for `tx/batch` and `pull/ok`.
## Follow-up Constraints
- New sync producers must keep each tx entry self-contained.
- If a future feature needs cross-entry references again, it must be introduced
explicitly as protocol behavior rather than repaired implicitly by the
client.
## Verification
- Updated frontend worker db-sync tests.
- Updated `deps/db-sync` storage, handler, and node-adapter tests.
- Passed:
- `bb dev:test -v frontend.worker.db-sync-test`
- `pnpm test` in `deps/db-sync`
- `bb dev:lint-and-test`
@@ -0,0 +1,49 @@
# ADR 0005: Atomic Outliner Batches via Temp Conn
Date: 2026-03-16
Status: Accepted
## Context
Outliner batch operations previously used a "batch-tx mode" that wrote each
inner transaction to the real conn immediately, then reconstructed one logical
batch in the db listener by collecting tx reports and emitting a synthetic
batch exit event.
That approach had two problems:
- it was not truly atomic because intermediate writes were visible on the real
conn before the batch finished
- batch flattening in `transact-with-temp-conn!` did not normalize logical
entity identity the same way sync already does, which made some multi-step
batches generate invalid final tx data
The failing db-sync sim showed this clearly: multi-step outliner batches could
leave the final merged tx with conflicting entity ids for the same block uuid.
## Decision
1. Outliner batch execution now uses `logseq.db/transact-with-temp-conn!`.
2. A batch writes to a temp conn for the full duration of the batch and commits
once to the real conn at the end.
3. Nested outliner batches reuse the current temp conn instead of opening a
second batch.
4. The final tx emitted from `transact-with-temp-conn!` is normalized with the
existing `logseq.db.common.normalize/normalize-tx-data` helper before it is
committed to the real conn.
5. Worker db listeners no longer reconstruct batch tx reports from
`:batch-tx/*` metadata, because the real conn now receives one final tx.
## Consequences
- Positive:
- Outliner batches are actually atomic from the real conn's perspective.
- Listener code is simpler because it no longer has to stitch together a
logical batch from multiple intermediate tx reports.
- Temp-id and lookup-id conflicts are handled by the existing tx
normalization path instead of a batch-specific merge.
- Negative:
- Batch execution now depends on temp-conn context instead of tx-meta flags,
so any future code that expects `:batch-tx/*` metadata must not be readded.
## Verification
- Passed targeted regression:
- `bb dev:test -v frontend.worker.db-sync-sim-test/three-clients-single-repo-sim-test`
- Passed focused batch helper coverage:
- `bb dev:test -v logseq.db-test/test-transact-with-temp-conn!`
+73
View File
@@ -0,0 +1,73 @@
# ADR 0006: Sync Entity Checksum for Server/Client Parity
Date: 2026-03-16
Status: Accepted
## Context
DB sync currently treats matching `t` values as the main convergence signal.
That is necessary, but it is not sufficient to guarantee that the client and
server represent the same block graph.
We have seen cases where temp-id handling and rebase bugs produced logically
divergent entities while `t` still advanced normally. In those cases, the
server and client could believe they were in sync even though some entities had
different content or references.
We need a cheap parity check that works on both the frontend worker and the
Cloudflare Worker, and the server must stay within a 128 MB memory limit.
## Decision
1. Add a shared DB sync checksum over block entities only.
2. The compared attrs depend on whether the graph is E2EE:
- Unencrypted graphs compare:
- `:block/uuid`
- `:block/title`
- `:block/name`
- `:block/parent`
- `:block/page`
- E2EE graphs compare:
- `:block/uuid`
- `:block/parent`
- `:block/page`
3. Reference attrs are normalized to referenced block UUID strings before
hashing, so client/server entity ids do not affect the result.
4. Runtime checksum is maintained incrementally from changed entities in tx
reports and persisted locally:
- client stores it in client-op metadata
- server stores it in `sync_meta`
5. A full recompute checksum path is kept for simulation and test verification.
6. The server includes the checksum in state-bearing sync responses:
- `hello`
- `pull/ok`
- `tx/batch/ok`
7. The client compares the remote checksum against its local checksum only when
sync is expected to have converged:
- local `t` equals remote `t`
- no pending local txs
- no inflight upload txs
8. On mismatch, the client fails fast with `:db-sync/checksum-mismatch` instead
of silently continuing with a divergent graph.
## Consequences
- Positive:
- Matching `t` is now backed by entity-level parity over the core sync attrs.
- Runtime checksum is fast and memory-light on both client and server because
it does not rescan the whole graph on each compare.
- Divergence is detected immediately at the sync boundary instead of surfacing
later as harder-to-debug invalid entities.
- Negative:
- The checksum is a fast additive hash, not a cryptographic digest.
- E2EE graphs intentionally do not compare encrypted title/name fields.
- It intentionally ignores attrs outside the sync-invariant set above.
- Mismatch handling is fail-fast in this change; it does not automatically
repair a divergent graph.
## Verification
- Frontend worker coverage:
- `bb dev:test -v frontend.worker.db-sync-test/hello-checksum-mismatch-fails-fast-test`
- `bb dev:test -v frontend.worker.db-sync-test/pull-ok-out-of-order-stale-response-is-ignored-test`
- Sim parity coverage:
- `bb dev:test -v frontend.worker.db-sync-sim-test/two-clients-cut-paste-random-sim-test`
- Sync compatibility coverage:
- `bb dev:test -v frontend.worker.db-sync-test/pending-txs-rewrite-old-string-tempids-test`
- `bb dev:test -v frontend.worker.db-sync-test/rebase-order-fix-for-new-blocks-does-not-keep-string-tempids-test`
@@ -0,0 +1,58 @@
# ADR 0007: Simplify Client DB-Sync for Recycle Semantics
Date: 2026-03-17
Status: Accepted
## Context
Client DB sync still contains logic shaped around hard delete.
That logic tracks deleted UUIDs, computes deleted subtrees, and runs a second
cleanup pass in temp connections to remove nodes after remote apply and local
rebase.
The recycle refactor changed deletion semantics.
Deleted pages and blocks now remain in the graph with stable UUIDs and are
hidden by placement and metadata instead of disappearing.
That means the deleted-context and delete-nodes cleanup flow is no longer the
right model for client sync.
It adds complexity, creates stale test assumptions around `db/retractEntity`,
and makes the rebase path harder to reason about.
## Decision
1. Client DB sync will stop treating deletion as entity disappearance.
2. The rebase/apply pipeline will operate on ordinary tx streams plus current DB
state.
3. `sanitize-tx-data` will no longer accept or derive deleted subtree state.
4. The extra temp-conn cleanup pass that deletes locally or remotely deleted
nodes will be removed.
5. Sync sanitization will keep only the behaviors that still matter:
- broken temp-id cleanup
- missing/ref-invalid datom cleanup
- remote/local conflict dropping
- page consistency fixes
- duplicate order fixes
6. Recycled targets are treated as invalid active refs by current DB state,
rather than through a separate deleted-context channel.
## Consequences
- Positive:
- The client sync implementation becomes shorter and easier to reason about.
- Delete and restore semantics stay consistent across local UI, undo/redo,
sync, and rebase.
- Tests can assert recycle behavior directly instead of hard-delete
side-effects.
- Negative:
- Old tests and assumptions built on `db/retractEntity` delete behavior must
be updated.
- Minimal stripped-down test DBs need recycle-aware helpers so they do not
count recycled nodes as active graph nodes.
## Verification
- DB sync unit coverage:
- `bb dev:test -v frontend.worker.db-sync-test`
- DB sync simulation coverage:
- `bb dev:test -v frontend.worker.db-sync-sim-test`
- Undo/redo compatibility coverage:
- `bb dev:test -v frontend.undo-redo-test`
- Recycle-aware long outliner helper coverage:
- `bb dev:test -e long -v frontend.modules.outliner.core-test/test-batch-transact`
@@ -0,0 +1,73 @@
# ADR 0008: Strengthen DB-Sync Simulation and Replay Coverage
Date: 2026-03-17
Status: Accepted
## Context
Recent DB-sync bugs have repeatedly escaped existing unit and simulation tests.
The failures were only exposed by real user sessions and browser logs, usually
after long offline editing, undo/redo, delete/recreate, recycle, and
sequential reconnect flows.
The current test suite has good focused coverage for many individual sync
helpers, but it still misses several classes of real-world behavior:
- editor-style multi-step writes such as `insert empty block -> save title`
- long-lived pending local tx queues
- undo/redo stacks that survive many sync rounds
- sequential reconnect flows where one client uploads first and another
reconnects later
- replay of real bad `local-txs` and `remote-txs` captured from logs
That gap makes DB-sync regressions too dependent on manual reproduction and
post-hoc log analysis.
## Decision
1. Treat DB-sync simulation as a first-class regression surface, not just a
long-running smoke test.
2. Keep adding deterministic repro tests for every real sync bug that reaches
logs or manual QA.
3. Expand offline multi-client sims to cover:
- both reconnect orders
- repeated offline/online cycles
- long undo/redo stacks
- heavier weighting for `delete-blocks`, `move-blocks`,
`cut-paste-block-with-child`, `undo`, and `redo`
4. Add invariant checks during simulation, not only after final convergence:
- no malformed pending tx items
- no malformed reversed tx items
- no invalid lookup-only reverse txs
- no DB structural issues such as missing parent/page or page mismatch
5. Introduce replay-oriented tests that can execute compact fixtures extracted
from real logs:
- persisted `local-txs`
- remote tx batches
- reconnect order
6. Prefer editor-faithful simulation helpers over simplified synthetic ops for
block creation and editing.
7. Keep a small corpus of fixed seeds and exact repro flows in the repository,
so future regressions are rerun automatically in CI and local test runs.
## Consequences
- Positive:
- Real sync bugs can be captured once and kept as permanent regressions.
- Multi-client offline behavior gets closer to real user workflows.
- Broken pending/reverse tx shapes fail earlier and closer to the source.
- Investigation time drops because logs can be turned into executable tests.
- Negative:
- Long-running DB-sync tests become more expensive.
- Some simulations may still approximate, rather than exactly match, UI
timing and browser worker behavior.
- The test suite will need ongoing curation so fixed seeds and replay
fixtures stay useful instead of becoming noisy.
## Verification
- Exact repro simulation coverage:
- `bb dev:test -v frontend.worker.db-sync-sim-test/two-clients-offline-delete-vs-children-undo-redo-repro-test`
- Aggressive offline random coverage:
- `bb dev:test -v frontend.worker.db-sync-sim-test/two-clients-both-offline-random-undo-redo-sequential-reconnect-sim-test`
- Reverse/pending tx shape coverage:
- `bb dev:test -v frontend.worker.db-sync-test/reverse-local-txs-skips-invalid-reverse-step-test`
- `bb dev:test -v frontend.worker.db-sync-test/reverse-local-txs-skips-missing-lookup-entity-step-test`
- `bb dev:test -v frontend.worker.db-sync-test/replace-string-block-tempids-rewrites-retract-entity-string-uuid-test`
- Undo/redo validity coverage:
- `bb dev:test -v frontend.undo-redo-test/undo-validation-rejects-invalid-recycle-restore-tx-test`
+69
View File
@@ -0,0 +1,69 @@
# ADR 0009: Hybrid Delete Semantics for Schema Entities
Date: 2026-03-18
Status: Accepted
## Context
`delete-blocks` and page deletion now recycle entities instead of hard deleting
them.
That works well for ordinary content because users can restore deleted blocks
and pages from Recycle, and active UI/search can treat recycled content as
hidden state.
It does not work as well for DB-schema entities.
Tag pages, property pages, and closed-value blocks continue to exist after
deletion and can leak into active semantics such as:
- class/property enumeration
- closed-value lookup and scoped choices
- bidirectional/property-derived views
- sync repair logic when schema roots disappear but dependents still reference
them
At the same time, sync still needs to remain robust when `:db/retractEntity`
appears again for this subset of entities and for their descendants.
## Decision
1. Adopt hybrid delete semantics:
- recycle ordinary blocks and ordinary content pages
- hard retract tag/class pages, property pages, and closed-value blocks
2. When deleting a schema root page, retract the schema page tree rather than
moving it to Recycle.
3. When deleting a closed-value block, retract the choice entity directly.
4. Keep raw entity access unchanged; deleted schema entities should disappear by
DB state, not by UI-only filtering.
5. Keep recycle-aware behavior for content entities:
- deleted-state page route for recycled content
- deleted styling for recycled references/embeds
- search/index filtering for recycled content and descendants
6. Make sync robust for missing content locations:
- if a content node loses `:block/parent` or `:block/page` during sync
application, move it to Recycle rather than leaving it structurally
invalid
7. Preserve valid `:db/retractEntity` handling in sync sanitize/rebase/apply for
schema deletions.
## Consequences
- Positive:
- Schema entities return to true disappearance semantics, which matches how
most schema helpers already reason about deletion.
- Content keeps recycle/restore UX.
- Sync has a deterministic repair rule for orphaned content blocks.
- Negative:
- Delete semantics are now mixed by entity kind, so the rule must remain
centralized in the outliner/domain layer.
- Some old recycled schema entities may still need active-use filtering until
users delete them under the new semantics.
- Sync logic is slightly more complex because it must accept both recycle and
hard-retract flows.
## Verification
- Model/helper coverage:
- `bb dev:test -v frontend.db.db-based-model-test/get-all-classes-filters-recycled-test`
- `bb dev:test -v frontend.db.db-based-model-test/get-all-properties-filters-recycled-test`
- Sync repair coverage:
- `bb dev:test -v frontend.worker.db-sync-test/missing-parent-after-remote-retract-moves-child-to-recycle-test`
- Additional targeted coverage to keep or extend:
- page/property/closed-value delete semantics
- bidirectional helper behavior with deleted or recycled entities
- search index invalidation for recycled content
+147
View File
@@ -0,0 +1,147 @@
# ADR 0010: Canonical Op-Driven Client Rebase With Legacy Tx Surgery Isolation
Date: 2026-03-19
Status: Accepted
## Context
Client sync rebase currently relies on custom tx-data surgery to keep pending
local changes alive after remote txs are applied.
That approach has several problems:
- the logic is hard to reason about because it edits datoms instead of replaying
user intent
- it does not preserve intent well when a local change originated from a higher
level outliner action
- the helper set keeps growing with special cases for missing refs, structural
conflicts, and deleted entities
- the outliner-op surface is too large to replay directly without first
reducing it
At the same time, not every outliner op needs to remain a first-class replay
operation.
Many ops can be safely represented by `:transact` when their tx-data is already
self-contained and does not depend on rerunning outliner logic.
We also have existing persisted pending rows that only store tx-data and reverse
tx-data.
Those rows still need a compatibility path, but that path should not define the
new rebase architecture.
## Decision
1. New pending local tx rows will persist semantic `:outliner-ops` in addition
to their existing tx-data payload.
2. Client rebase will become op-driven for all new pending rows:
- reverse local txs
- apply remote txs
- transform or drop stored local ops against the post-remote temp db
- replay the surviving ops to regenerate rebased tx-data
3. Reduce the replay-visible outliner-op surface to a small canonical set:
- `:insert-blocks`
- `:save-block`
- `:move-blocks`
- `:delete-blocks`
- `:transact`
4. Normalize higher-level ops into that canonical set before persistence.
Examples:
- `:indent-outdent-blocks` becomes `:move-blocks`
- `:move-blocks-up-down` becomes `:move-blocks`
- `:rename-page` becomes `:save-block`
5. Introduce an explicit safe-`:transact` classifier:
- if replaying tx-data directly is sufficient and does not require rerunning
outliner logic, persist the op as canonical `:transact`
- otherwise keep it as one of the canonical outliner replay ops
- expected canonical `:transact` cases include direct tx replay actions such
as undo, redo, import replay, reaction toggles, and property-value updates
6. Treat undo/redo as canonical `:transact` actions.
- persist the exact tx-data that the successful undo or redo applied
- keep the action atomic as one pending tx row
- do not reconstruct the original higher-level outliner ops that were
undone or redone
7. Treat `:batch-import-edn` as canonical `:transact` after successful local
execution.
- persist the exact tx-data that the import applied
- do not rerun import expansion during rebase
8. Keep the following op kinds as replay-visible semantic ops because they must
be reevaluated against current DB state:
- `:save-block`
- `:insert-blocks`
- `:move-blocks`
- `:delete-blocks`
- `:create-page`
- `:delete-page`
- `:upsert-property`
9. Stop using raw tx-data surgery in the normal rebase path for new rows.
10. Move the current tx-data surgery helpers into a dedicated legacy namespace.
That legacy namespace is only for compatibility handling of old persisted
pending rows that do not have stored `:outliner-ops`.
11. Add explicit owned-block filtering in the new op-driven rebase path.
Initially cover:
- reaction blocks owned by `:logseq.property.reaction/target`
- property history blocks owned by `:logseq.property.history/block`
- property history blocks whose effective owner disappears through deleted
`:logseq.property.history/ref-value`
12. If a local op creates or updates one of those owned blocks and the owning
block was deleted remotely, drop that op.
13. Treat each pending tx row as one user action and keep it atomic during
rebase.
14. If any op in a pending tx becomes invalid during rebase, drop the whole
pending tx rather than keeping a partial replay of that user action.
15. Keep this refactor client-only for now.
The sync wire format and server tx log remain unchanged.
## Consequences
- Positive:
- Rebase reasons about user intent instead of datom accidents.
- The number of op kinds that rebase must understand becomes much smaller.
- Safe direct tx replay remains available through canonical `:transact`
without forcing every operation through outliner code.
- Undo/redo stays aligned with its real intent: replay the exact applied tx,
not rerun a reconstructed higher-level command.
- Import replay stays aligned with its real intent: preserve the exact local
import result rather than recomputing import expansion later.
- Legacy compatibility is isolated instead of contaminating the new design.
- Owned-block cleanup becomes an explicit semantic rule rather than another
tx-data patch.
- Rebase behavior stays aligned with the mental model that one pending tx is
one user action that either survives or is discarded as a whole.
- Negative:
- We must maintain a canonicalization layer from original outliner ops to the
reduced replay set.
- Some existing ops need careful classification to decide whether they are
safe `:transact` or must stay true outliner replays.
- For a transition period, the codebase will contain both the new rebase path
and the isolated legacy compatibility path.
- If one invalid op is grouped together with otherwise valid work in the same
pending tx, the whole user action will be lost during rebase.
## Follow-up Constraints
- New pending tx producers must persist canonical `:outliner-ops`.
- New pending tx producers must preserve user-action boundaries because rebase
will treat each persisted tx row atomically.
- Canonicalization should happen when persisting local pending txs, not lazily
during rebase.
- Undo/redo producers should persist canonical `:transact` actions using the
exact tx-data they applied.
- Import producers should persist canonical `:transact` actions using the exact
tx-data they applied.
- The main sync apply namespace should not call legacy tx-surgery helpers for
new pending rows.
- The legacy namespace should be clearly named and easy to delete once old
pending-row compatibility is no longer needed.
## Verification
- Add or update frontend worker db-sync coverage for:
- persistence of canonical `:outliner-ops`
- canonical reduction of `:indent-outdent-blocks` and
`:move-blocks-up-down` into `:move-blocks`
- safe `:transact` replay versus true outliner replay classification
- undo/redo persistence as atomic canonical `:transact` actions
- `:batch-import-edn` persistence as atomic canonical `:transact`
- `:rename-page` canonicalization to `:save-block`
- op-driven rebase preserving pending tx boundaries
- dropping owned reaction/history ops when their owner was deleted remotely
- dropping the whole pending tx when any op in that user action becomes
invalid
- routing legacy pending rows without stored ops through the legacy namespace
- Expected targeted command:
- `bb dev:test -v frontend.worker.db-sync-test`
@@ -0,0 +1,378 @@
# ADR 0011: Undo/Redo Semantic Inverse-Op Persistence and Local-Op Referenced UI History
Date: 2026-03-21
Status: Proposed
## Context
ADR 0010 deliberately classified undo and redo as canonical `:transact` actions.
That choice kept pending-row persistence simple, but it also preserved undo and redo as raw datom replay rather than preserving their intent.
That tradeoff is now the main weakness in the sync rebase model.
During client rebase, pending local actions are reversed, remote txs are applied, and then pending local actions are replayed.
That architecture works well when the persisted action is a semantic op such as `:save-block`, `:insert-blocks`, or `:move-blocks`.
It works poorly when the persisted action is a raw undo or redo tx payload because the replay logic can no longer distinguish commutative remote updates from true semantic conflicts.
The current undo/redo design also duplicates DB history across two places.
The main thread owns the undo and redo stacks because it stores UI state such as route state, editor cursor, and focus context.
At the same time, the worker already persists local DB actions in client-ops storage with a stable `tx-id`.
Those two histories are related but not unified.
As a result, sync rebase, undo/redo, and pending local action persistence can drift apart.
The user action identity is already represented in the worker by `:db-sync/tx-id`, but the UI undo stack still stores the DB tx payload itself instead of referencing that persisted action.
This ADR defines a plan to make the client-op row the source of truth for DB history while keeping the main thread as the source of truth for UI state.
Constraints:
- The main thread must continue to own UI-only undo state.
- The sync wire protocol should remain unchanged.
- Existing persisted pending rows without semantic metadata are intentionally out of scope for this change.
- Rebase should continue to preserve one logical pending row as one user action.
- The design must preserve redo, not just undo.
Related ADRs:
- Builds on ADR 0002.
- Builds on ADR 0010.
- Supersedes ADR 0010 decision 6, which treated undo/redo as canonical `:transact`.
## Problem Summary
The current model has three tightly coupled problems.
First, undo and redo are persisted as raw tx replay.
That makes rebase unable to reason about their semantics.
Second, the undo stack on the main thread stores DB payloads directly instead of referencing the persisted local action row in worker storage.
That means the UI history and worker history are not guaranteed to stay aligned.
Third, the current worker pending-row schema persists forward tx data and reverse tx data, but it does not persist both semantic forward ops and semantic inverse ops as first-class action metadata.
That prevents robust rebase and robust redo from using the same action identity.
The result is that a benign remote update such as a title edit can still force undo/redo to fall back to raw replay, which is unnecessarily lossy and much harder to classify correctly.
## Decision
1. The worker client-op row identified by `:db-sync/tx-id` becomes the source of truth for DB undo/redo history.
2. The main-thread undo/redo stacks will store UI state plus a reference to that worker action row, not the DB tx payload itself.
3. New client-op rows will persist both forward semantic outliner ops and inverse semantic outliner ops.
4. Redo will replay the persisted forward semantic ops for the referenced action row.
5. Undo will replay the persisted inverse semantic ops for the referenced action row.
6. New rebase logic will use semantic forward or inverse ops for new undo/redo-backed action rows instead of raw datom replay.
7. Existing `normalized-tx-data` and `reversed-tx-data` fields remain temporarily for debugging, validation, and controlled cleanup, but they will not define replay behavior for the new undo/redo architecture.
8. The logical `tx-id` remains stable across rebase rewrites so that main-thread stack entries do not break when the worker rewrites the row contents.
9. Undo/redo rows that cannot be represented with semantic inverse ops are unsupported until a semantic representation is added explicitly.
## Target Architecture
The architecture separates UI history from DB history while keeping both linked through one stable action identifier.
```text
+-------------------+ tx-id +----------------------------+
| Main thread | -----------------------> | Worker client-ops storage |
| undo/redo stack | | one row per logical action |
| | <----------------------- | stable tx-id |
| UI state | action result | forward semantic ops |
| editor cursor | | inverse semantic ops |
| route/sidebar | | normalized tx data |
+-------------------+ | reverse tx data (legacy) |
+----------------------------+
|
v
+----------------------------+
| Sync rebase + upload |
| replay by semantic ops |
+----------------------------+
```
The main thread continues to own UI-only history because the worker should not become responsible for route or editor selection state.
The worker becomes responsible for DB action identity and replay semantics because that is the same place that already owns pending local action persistence, sync upload, and rebase.
## Data Model Changes
The client-op row needs to distinguish between the identity of a logical action and the concrete tx-data that happened to be generated on the current device revision.
The row should keep the existing logical `tx-id`.
The row should add explicit semantic operation fields for both directions.
Recommended schema additions:
| Field | Purpose |
| --- | --- |
| `:db-sync/forward-outliner-ops` | Canonical semantic ops that reapply the action. |
| `:db-sync/inverse-outliner-ops` | Canonical semantic ops that undo the action. |
| `:db-sync/history-kind` | Distinguishes regular action rows from specialized worker history rows if needed. |
| `:db-sync/source-tx-id` | Optional link from an undo/redo execution row back to the original action row during migration. |
| `:db-sync/semantic-persistence-version` | Marks rows that are safe for semantic replay. |
The existing fields should remain during migration:
| Existing field | Migration role |
| --- | --- |
| `:db-sync/normalized-tx-data` | Validation reference and emergency cleanup aid. |
| `:db-sync/reversed-tx-data` | Local safety checks and controlled cleanup aid. |
| `:db-sync/outliner-op` | Existing summary/debug field. |
| `:db-sync/outliner-ops` | Can be folded into `forward-outliner-ops` once migration is complete. |
The main-thread undo stack entry shape should change accordingly.
The DB portion of a stack entry should become a small reference object instead of an embedded tx payload.
Recommended main-thread DB history payload:
| Field | Purpose |
| --- | --- |
| `:local-op-tx-id` | Stable reference to worker client-op row. |
| `:history-direction` | `:forward` in undo stack and `:inverse` in redo stack if needed for UI bookkeeping. |
| `:history-version` | Allows invalidating stale stack entries across releases. |
The main-thread stack entry should continue to store editor cursor and UI route state as it does today.
## Semantic Persistence Rules
The plan depends on persisting semantic inverse ops instead of reconstructing them later from raw datoms.
That means the inverse ops must be created at the time a local action is first recorded into undo history.
The worker should never have to guess the inverse of an already-lost user intent from only tx-data if the action was produced by a known canonical outliner op.
The persistence rules are:
1. A regular local action row persists canonical forward ops.
2. The undo stack entry points at that action row by `tx-id`.
3. Undo execution uses the inverse semantic ops stored on the referenced row.
4. Redo execution uses the forward semantic ops stored on the referenced row.
5. If a row does not have semantic inverse ops, it must not enter the semantic rebase path.
## Canonical Op Surface
This ADR does not require every outliner op to become replay-visible immediately.
It does require the canonical replay-visible surface for undo/redo to be explicit and versioned.
Recommended canonical surface for forward and inverse persistence:
- `:save-block`
- `:insert-blocks`
- `:move-blocks`
- `:delete-blocks`
- `:set-block-property`
- `:remove-block-property`
- `:batch-set-property`
- `:batch-remove-property`
- `:delete-property-value`
- `:batch-delete-property-value`
- `:create-property-text-block`
- `:upsert-closed-value`
- `:delete-closed-value`
- `:add-existing-values-to-closed-values`
- `:create-page`
- `:delete-page`
- `:rename-page`
If an action cannot be expressed in that surface with a safe inverse, it should remain unsupported until a semantic representation is added deliberately.
That is preferable to reclassifying it as safe raw replay by accident.
## Inverse Op Generation Strategy
Inverse semantic ops should be created from the original action metadata and the pre-action DB state, not by reverse-engineering datoms after the fact.
The current main-thread undo history already retains the original tx meta, which includes `:outliner-ops` for many actions.
That existing signal should be preserved and extended rather than discarded.
The generation strategy should be:
1. Start from the original canonical forward ops attached to the local action.
2. Resolve all entity references to stable ids at persistence time.
3. Build inverse canonical ops while the pre-action DB state is still available.
4. Persist both directions on the action row under the same `tx-id`.
Representative inverse mappings:
| Forward op | Inverse op strategy |
| --- | --- |
| `:save-block` | Persist a `:save-block` payload built from pre-action block content and relevant pre-action refs. |
| `:insert-blocks` | Persist `:delete-blocks` for the created roots, or a more specific inverse if a safer canonical form exists. |
| `:move-blocks` | Persist `:move-blocks` back to the pre-action target with stable target id and structural opts. |
| `:delete-blocks` | Persist a hard-delete inverse only if block recreation is represented explicitly. Recycle-based restoration is no longer part of block deletion semantics. |
| `:set-block-property` | Persist `:set-block-property` or `:remove-block-property` depending on whether the property existed before the action. |
| `:batch-set-property` | Persist a batch inverse that restores prior values per block rather than a single blind batch overwrite. |
| `:create-page` | Persist `:delete-page` or a page retract inverse depending on page type. |
| `:delete-page` | Persist `:create-page` plus restoration of prior page content and relationships, or represent page restoration as a dedicated canonical op. |
The plan does not require every mapping to be implemented in one patch.
It does require the migration plan to make unsupported actions explicit so that they cannot silently flow into the new architecture.
## Why `tx-id` Must Be the Main-Thread DB History Reference
The UI stack needs a stable identifier for the DB action because that action may be:
- pending locally and not yet synced
- rebased by the worker
- acknowledged by the server
- rewritten during local compaction
- invalidated because the worker dropped it as unreplayable
If the main thread stores raw tx-data instead of `tx-id`, the UI stack and worker pending history can diverge.
If the main thread stores `tx-id`, the worker can rewrite the row contents while preserving logical action identity.
That makes the worker free to update the concrete replay payload during rebase without breaking the main-thread history pointer.
The worker must therefore treat `tx-id` as logical action identity rather than as a disposable row key.
## Cutover Plan
This change intentionally uses a strict cutover instead of a backward-compatible migration for old pending rows.
Cutover rules:
1. Existing pending rows without semantic persistence fields are cleared or dropped at startup.
2. Existing main-thread stack entries without `tx-id` are invalid after the cutover.
3. Old-format in-memory history is not preserved across the change.
4. New rows must always be written with the new semantic fields once the feature flag is enabled.
## Implementation Plan
### Phase 1. Add action-identity and semantic fields to client-op storage.
- Update `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/worker/sync/client_op.cljs` schema for forward and inverse semantic ops plus version metadata.
- Keep existing fields intact.
- Ensure `tx-id` remains stable when a pending row is rewritten after rebase.
### Phase 2. Make the worker action row the source of truth for DB history.
- Update `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/worker/sync/apply_txs.cljs` so local action persistence writes both directions when available.
- Split the meaning of existing `:db-sync/outliner-ops` from the new explicit forward and inverse fields rather than overloading one field for two roles.
- Preserve current `normalized-tx-data` and `reversed-tx-data` during migration.
### Phase 3. Change main-thread undo stack payloads from embedded tx data to `tx-id` references.
- Update `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/undo_redo.cljs` so stack entries keep UI state and worker action references instead of DB tx payloads.
- Keep cursor and route state on the main thread.
- Remove the assumption that main-thread history owns the DB replay payload.
### Phase 4. Add a worker API for undo and redo execution by `tx-id`.
- Introduce a worker-facing command that resolves the client-op row by `tx-id`.
- Undo execution should replay `inverse-outliner-ops`.
- Redo execution should replay `forward-outliner-ops`.
- The command should return enough result metadata for the main thread to restore cursor and UI state after the worker confirms DB success.
### Phase 5. Replace raw undo/redo sync persistence with semantic persistence.
- Stop classifying new undo/redo executions as canonical raw `:transact` in `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/worker/sync/apply_txs.cljs`.
- Instead, persist their semantic forward and inverse operations under the same logical action identity.
- Remove the old undo/redo raw replay path for pending-row persistence instead of keeping a compatibility branch.
### Phase 6. Extend rebase to use semantic inverse and forward ops for undo/redo rows.
- In `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/worker/sync/apply_txs.cljs`, route undo/redo rows through semantic replay only.
- Preserve one-row-per-user-action atomicity.
- If any op in a row becomes invalid, drop or quarantine the whole row rather than partially replaying it.
### Phase 7. Add explicit invalidation rules for main-thread stack entries.
- If the worker drops or quarantines a referenced action row, the main-thread stack entry that points at that `tx-id` must be invalidated.
- Add a worker-to-main-thread signal so the UI can clear stale history references without guessing.
- Avoid silent dangling `tx-id` references in the UI stack.
### Phase 8. Add compaction and cleanup rules.
- Decide when an acknowledged action row can be compacted while still remaining undoable.
- If compaction rewrites stored payloads, preserve `tx-id`.
- If compaction removes a row, invalidate any stack references to it first.
## Required Code Areas
The following files are expected to change.
| File | Responsibility |
| --- | --- |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/undo_redo.cljs` | Change stack payloads to `tx-id` references and route DB replay to worker by action id. |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/handler/history.cljs` | Keep UI restore flow but consume worker-driven undo/redo result metadata. |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/worker/sync/client_op.cljs` | Extend client-op schema with semantic forward and inverse fields plus version metadata. |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/worker/sync/apply_txs.cljs` | Persist semantic undo/redo ops, keep stable `tx-id`, and use semantic replay in rebase. |
| `/Users/tiensonqin/Codes/projects/logseq/web/deps/outliner/src/logseq/outliner/op.cljs` | Reuse canonical op shapes and extend replay-visible surface if new canonical ops are introduced. |
| `/Users/tiensonqin/Codes/projects/logseq/web/deps/outliner/src/logseq/outliner/recycle.cljs` | Provide a replay-safe restoration entrypoint if `:restore-recycled` becomes canonical. |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/test/frontend/undo_redo_test.cljs` | Cover `tx-id`-referenced history behavior and main-thread invalidation. |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/test/frontend/worker/db_sync_test.cljs` | Cover semantic persistence and rebase of undo/redo action rows. |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/test/frontend/worker/db_sync_sim_test.cljs` | Cover multi-client rebase scenarios where remote txs commute or conflict with undo/redo. |
## Edge Cases That Must Be Designed Explicitly
### Remote non-conflicting updates.
A remote title update on an unrelated block should not invalidate a local undo stack entry.
### Remote updates on the same entity but different attrs.
The design should allow semantic replay when the attrs commute and reject it when they do not.
### Structural conflicts.
Parent, page, order, delete, recycle, and missing-ref conflicts must invalidate the whole action row, not a subset of its ops.
### Undo of a batch action.
One logical batch action should remain one `tx-id` and should not split into multiple undoable rows during persistence or rebase.
### Redo after rebase.
Redo must continue to point at the same action identity even if the worker rewrote the row payloads during remote rebase.
### Session boundary.
Main-thread stacks are in-memory only today.
That remains acceptable, but the new `tx-id` reference model must not assume the stack survives app restart unless a later ADR decides to persist it.
### Unsupported inverse mappings.
An unsupported op must be explicit and traceable.
It must not silently fall back to safe-looking semantic replay if it is actually raw replay.
### Old pending rows.
Existing rows without semantic fields are intentionally not supported after the cutover.
They should be cleared rather than replayed.
## Risks
The largest risk is trying to migrate everything at once.
Undo/redo touches the main thread, the worker, client-op persistence, and rebase logic.
The plan therefore intentionally stages the work so that logical action identity and schema changes land before the main-thread stack rewrite and before the semantic rebase cutover.
Another risk is under-specifying inverse mappings for high-level actions such as delete-page.
Those mappings should be treated as explicit product decisions, not left to raw tx fallback by accident.
Another risk is user-visible loss of old pending rows during the cutover.
That tradeoff is accepted because preserving old raw replay rows would preserve the exact failure mode this ADR is intended to remove.
## Verification Plan
Verification must cover both behavior and migration safety.
Required coverage:
- main-thread undo stack entry stores `tx-id` plus UI state, not raw DB tx payload
- worker persists semantic forward and inverse ops on new local action rows
- undo executes by `tx-id` and replays inverse semantic ops
- redo executes by `tx-id` and replays forward semantic ops
- new undo/redo rows no longer persist as canonical raw `:transact`
- rebase preserves logical `tx-id` while rewriting row payloads
- benign remote updates continue to allow undo/redo replay
- structural conflicts invalidate the whole referenced action row
- dropped or quarantined worker rows invalidate corresponding UI history entries
- old rows without semantic fields are cleared and do not replay
Targeted commands once implementation begins:
- `bb dev:test -v frontend.undo-redo-test`
- `bb dev:test -v frontend.worker.db-sync-test`
- `bb dev:test -v frontend.worker.db-sync-sim-test`
## Consequences
Positive consequences:
- Undo/redo DB history and sync pending history converge on one logical action model.
- Rebase can reason about intent instead of replaying raw datoms for new undo/redo rows.
- The main thread keeps ownership of UI-only state without also becoming the long-term store of DB replay payloads.
- `tx-id` becomes a durable action identity that can survive rebase rewrites.
Negative consequences:
- The worker schema and the main-thread undo model both change at the same time.
- Several inverse-op mappings require explicit product and implementation decisions.
- The cutover is intentionally strict and may discard old pending rows that cannot satisfy the new semantic contract.
## Follow-up Notes
This ADR intentionally does not specify the final retention policy for acknowledged action rows.
It only requires that action-row lifetime be compatible with undo/redo stack references.
If future work decides to persist the UI stack across restarts, that should be handled in a separate ADR after this action-identity model is in place.
+308
View File
@@ -0,0 +1,308 @@
# ADR 0012: Move Undo/Redo Recording and Replay to the DB Worker
Date: 2026-03-21
Status: Proposed
## Context
`frontend.undo-redo` currently runs on the main thread.
That means undo and redo recording depends on main-thread listeners observing DB
tx reports after they have already crossed the worker boundary.
This split has become a recurring source of drift:
- the worker is the source of truth for the browser Datascript DB
- the worker already persists local actions in client-op storage
- the worker already owns rebase and semantic replay
- the main thread still owns undo/redo stack mutation for DB history
That architecture forces the main thread to reconstruct DB history from a
worker-synchronized tx report instead of observing the DB change at the place
where it actually happens.
The result is fragile metadata flow.
We have already seen bugs caused by:
- `:outliner-ops` being stripped or reshaped during worker-to-main-thread sync
- undo/redo-generated tx rows overwriting the original client-op row
- semantic forward and inverse ops diverging between worker persistence and
main-thread undo stack payloads
- special cases such as `:replace-empty-target?`, block concat, and
`:set-block-property` depending on worker-local replay behavior anyway
The one main-thread-only input that `frontend.undo-redo` still needs is
`@state/*editor-info`.
Today that atom is read and reset on the main thread inside
`frontend.undo-redo/gen-undo-ops!`.
If undo/redo recording moves to the worker, the worker can no longer deref the
main-thread atom directly.
## Decision
1. DB undo/redo recording and replay move to the DB worker.
2. The worker becomes the only place that listens to DB tx reports for DB
history generation.
3. The main thread remains responsible for UI-derived history inputs only:
editor cursor/focus metadata and UI-state snapshots.
4. `@state/*editor-info` will not be read from the worker directly.
It will be replaced by an explicit main-thread-to-worker handoff protocol.
5. The worker owns the undo stack and redo stack for DB actions and UI-adjacent
metadata attached to those actions.
6. The main thread will invoke worker APIs for:
- recording pending editor info
- recording UI-only state history entries
- undo
- redo
- clear history
7. The main thread will stop generating DB undo history from `:db/sync-changes`
events.
8. The worker-owned history row should not keep a separate persisted
`:db-sync/outliner-ops` field.
`:db-sync/forward-outliner-ops` is the only canonical persisted forward
semantic field.
## Rationale
The worker is already the place where all browser DB facts become real:
- local outliner ops are applied there
- remote sync txs are applied there
- pending local rows are persisted there
- semantic forward and inverse ops are canonicalized there
- rebase happens there
Undo/redo recording should therefore observe worker DB tx reports directly
instead of reconstructing them after the worker has serialized, sanitized, and
rebroadcast them.
That removes an entire class of metadata transport bugs.
It also matches ADR 0011 more closely: the worker action row is supposed to be
the source of truth for DB history. Recording DB history on the main thread is
in tension with that decision.
## Target Architecture
```text
+------------------------------+ thread-api +---------------------------+
| Main thread | ----------------------------> | DB worker |
| | | |
| editor lifecycle | push pending editor-info | pending editor-info store |
| route/sidebar state | push ui-state entries | undo stack |
| history handler | undo / redo / clear | redo stack |
| restore cursor + route | <---------------------------- | DB replay + result meta |
+------------------------------+ +---------------------------+
```
The worker stack entry becomes the single logical history item for both:
- DB replay metadata
- UI-adjacent metadata needed after replay
Representative worker stack item:
```clojure
{:tx-id #uuid "..."
:kind :db-action ; or :ui-state-only
:editor-info {:block-uuid ...
:container-id ...
:start-pos ...
:end-pos ...}
:ui-state-str "...optional transit..."
:forward-outliner-ops [...]
:inverse-outliner-ops [...]
:outliner-op :save-block}
```
The target row schema is therefore:
- `:db-sync/tx-id`
- `:db-sync/outliner-op`
- `:db-sync/forward-outliner-ops`
- `:db-sync/inverse-outliner-ops`
- worker-owned cursor/UI metadata as needed
It intentionally does not include a separate persisted
`:db-sync/outliner-ops`.
## `*editor-info` Handoff
The worker must not read `@state/*editor-info` directly.
That atom lives on the main thread and represents ephemeral UI state.
Instead, we will replace the implicit shared-state read with an explicit
handoff.
### Rule
The main thread owns editor-info production.
The worker owns editor-info consumption.
### Mechanism
Add a worker-side pending editor-info slot keyed by repo.
Suggested API:
- `:thread-api/undo-redo-set-pending-editor-info`
- args: `repo`, `editor-info-or-nil`
- `:thread-api/undo-redo-record-ui-state`
- args: `repo`, `ui-state-str`
- `:thread-api/undo-redo-undo`
- args: `repo`
- `:thread-api/undo-redo-redo`
- args: `repo`
- `:thread-api/undo-redo-clear-history`
- args: `repo`
### Consumption and reset semantics
When the worker records a new local DB action into undo history:
1. read pending editor-info for the repo
2. attach it to the new stack item if present
3. clear the pending editor-info slot immediately after the stack item is
created
This preserves the current one-shot semantics of `@state/*editor-info` without
requiring the worker to deref or mutate main-thread state directly.
### Main-thread responsibilities
The main thread should:
- capture editor-info at the same points it does today
- send the current snapshot to the worker before the local DB action is
submitted or immediately when editor focus/cursor changes, whichever path is
simpler and consistent
- stop relying on worker `:db/sync-changes` to retroactively capture cursor
state
The main thread may still keep a local `*editor-info` atom for editor UI code,
but it is no longer the undo recorder’s source of truth.
## UI-State History
UI-state-only undo entries such as route/sidebar snapshots cannot be generated
by the worker from DB tx reports.
Those entries should be pushed explicitly from the main thread into the worker
history stack.
Two entry classes will therefore exist in the worker stack:
1. `:db-action`
2. `:ui-state-only`
Undo/redo execution will return enough metadata for the main thread to restore:
- route
- sidebar state
- editor cursor
The worker should not attempt to perform UI restoration itself.
## Consequences
### Positive
- DB undo/redo history is recorded at the actual DB source of truth.
- No more dependence on `:db/sync-changes` preserving semantic metadata exactly.
- Worker persistence, worker replay, and worker history all use the same action
identity.
- Main-thread history bugs caused by tx-meta sanitization disappear.
- Undo/redo debugging becomes simpler because the worker owns the full DB
history lifecycle.
### Negative
- The worker history stack now stores UI-adjacent metadata that originates on
the main thread.
- New thread APIs are required.
- Main-thread editor lifecycle code must actively synchronize pending
`editor-info`.
- The migration touches both undo/redo and worker message flow at once.
## Implementation Plan
### Phase 1. Introduce worker-owned undo/redo module
- Create a worker namespace, e.g.
`/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/worker/undo_redo.cljs`
- Move stack storage and DB history generation there.
- Register worker DB listener(s) against the worker Datascript conn.
- Remove persisted `:db-sync/outliner-ops` from the target worker history row
shape instead of carrying it forward as a parallel field.
### Phase 2. Replace main-thread DB history generation
- Remove DB-history recording from
`/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/undo_redo.cljs`
- Keep only main-thread coordination helpers if still needed.
- Route history handler calls through worker thread APIs.
### Phase 3. Add pending editor-info handoff
- Add worker API to set pending editor-info.
- Update
`/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/modules/outliner/ui.cljc`
and any direct local transact paths to send editor-info to the worker.
- Consume and clear the pending editor-info slot when a local history item is
recorded.
### Phase 4. Move UI-state history writes to worker
- Replace `record-ui-state!` main-thread stack mutation with worker API calls.
- Keep route/sidebar serialization on the main thread.
### Phase 5. Return worker-owned undo/redo result metadata
- Worker undo/redo APIs should return:
- `:undo?`
- `:editor-info`
- `:ui-state-str`
- optional block content or replay diagnostics
- Main-thread history handler restores cursor and route from that result.
## Files Expected to Change
| File | Change |
| --- | --- |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/undo_redo.cljs` | Remove main-thread DB listener ownership, keep only coordinator logic if still needed. |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/handler/history.cljs` | Call worker undo/redo APIs and restore UI from returned metadata. |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/modules/outliner/ui.cljc` | Send editor-info snapshots to the worker before local action submission. |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/handler/editor/lifecycle.cljs` | Stop recording editor-info directly into main-thread undo stack; feed worker pending editor-info instead. |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/worker/db_worker.cljs` | Expose worker thread APIs for pending editor-info, UI-state history, undo, redo, and clear-history. |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/worker/db_listener.cljs` | Attach worker undo/redo recording directly to worker DB tx reports. |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/worker/sync/client_op.cljs` | Remove `:db-sync/outliner-ops` from the target worker-owned undo/redo row model and use `:db-sync/forward-outliner-ops` instead. |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/main/frontend/worker/sync/apply_txs.cljs` | Keep worker replay aligned with worker-owned history rows. |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/test/frontend/undo_redo_test.cljs` | Replace main-thread DB-history expectations with coordinator/result expectations. |
| `/Users/tiensonqin/Codes/projects/logseq/web/src/test/frontend/worker/db_sync_test.cljs` | Add worker-owned history recording and replay coverage. |
## Alternatives Considered
### 1. Keep `frontend.undo-redo` on the main thread and preserve more tx-meta
Rejected.
This keeps the wrong ownership boundary.
It reduces one transport bug at a time but does not remove the architectural
duplication between main-thread history and worker DB history.
### 2. Let the worker call back into the main thread to read `@state/*editor-info`
Rejected.
That would create an implicit cross-thread read dependency around ephemeral UI
state.
It is harder to reason about than explicit handoff, and reset semantics become
ambiguous.
### 3. Keep DB history in the worker and UI history in a separate main-thread stack
Possible, but inferior to a single worker-owned stack item keyed by `tx-id`.
It still splits one logical action across two structures and reintroduces
alignment problems.
## Open Questions
1. Should pending editor-info be pushed:
- only at transact boundaries
- or eagerly on every cursor change with last-write-wins semantics?
Recommendation:
push at transact boundaries first.
It matches current one-shot behavior and avoids unnecessary worker chatter.
2. Should `:ui-state-only` entries live in the same stack as DB actions?
Recommendation:
yes.
One logical undo/redo stream is simpler than coordinating two stacks.
3. Do we still need `@state/*editor-info` after the migration?
Recommendation:
keep it as a UI helper until the move is complete, but stop using it as undo
history source of truth.
@@ -0,0 +1,187 @@
# ADR 0013: Worker-Owned Undo/Redo Test Ownership
Date: 2026-03-21
Status: Proposed
## Context
ADR 0012 moves DB undo/redo ownership from the main thread to the db worker.
That architectural move is not complete if the test suite still treats
`src/test/frontend/undo_redo_test.cljs` as the primary place to assert DB
history behavior.
Today the old main-thread file still contains most undo/redo tests, including:
- local tx recording
- semantic forward and inverse metadata
- insert/save/delete replay sequences
- replay conflict and skip behavior
- validation behavior tied to DB replay
Those tests were correct for the old design, but they now encourage the wrong
ownership boundary.
The worker already owns:
- worker datascript DB mutation
- client-op persistence
- semantic replay
- pending action identity
- replay safety decisions
The main thread now mainly owns:
- route/sidebar UI restoration
- cursor restoration from worker result metadata
- thin browser-facing proxy calls
The test suite should reflect that split directly.
## Decision
1. `src/test/frontend/worker/undo_redo_test.cljs` becomes the primary home for
DB-history-focused undo/redo tests.
2. `src/test/frontend/undo_redo_test.cljs` is reduced to main-thread-only
coordination tests.
3. Replay, conflict, and rebase-heavy assertions that are really worker replay
behavior belong in `src/test/frontend/worker/db_sync_test.cljs`, not in
either undo-redo namespace test file.
4. No new DB-history behavior test should be added to
`src/test/frontend/undo_redo_test.cljs`.
## Test Ownership Rules
### Keep in `src/test/frontend/worker/undo_redo_test.cljs`
- local tx recording gates
- semantic metadata persistence
- worker-owned undo stack and redo stack mutation
- canonical action-id and semantic op persistence
- worker-owned DB-history entries that include pending editor-info and UI-state
metadata
### Keep in `src/test/frontend/worker/db_sync_test.cljs`
- `apply-history-action!` replay behavior
- semantic replay correctness
- conflict and skip behavior caused by worker replay safety
- rebase interactions
- client-op row persistence and rewrite behavior
### Keep in `src/test/frontend/undo_redo_test.cljs`
- route/sidebar UI-state restoration on the main thread
- cursor restoration from worker result metadata
- browser-facing proxy semantics in `frontend.undo-redo` and
`frontend.handler.history`
- any pure coordination helper that still lives only on the main thread
## Migration Buckets
### Bucket 1. Recording and metadata tests.
Move these first:
- `undo-records-only-local-txs-test`
- `undo-history-records-semantic-action-metadata-test`
- `undo-history-records-forward-ops-for-editor-save-block-test`
- `undo-history-canonicalizes-insert-block-uuids-test`
These tests map directly to worker history ownership and do not require route or
cursor restoration.
### Bucket 2. Basic local replay tests.
Move next, but only after the worker fixture persists matching client-op rows:
- `undo-works-for-local-graph-test`
- `repeated-save-block-content-undo-redo-test`
- `repeated-editor-save-block-content-undo-redo-test`
- `editor-save-two-blocks-undo-targets-latest-block-test`
- `new-local-save-clears-redo-stack-test`
If a test still depends on browser-only helpers, rewrite it to assert worker DB
behavior directly or leave it temporarily unmoved.
### Bucket 3. Delete/recycle sequence tests.
Reclassify before moving:
- `insert-save-delete-sequence-undo-redo-test`
- `undo-redo-works-for-recycle-delete-test`
If the real behavior under test is semantic replay, keep or move it to
`src/test/frontend/worker/db_sync_test.cljs`.
### Bucket 4. Conflict and skip tests.
Reclassify these into worker replay coverage unless they are truly worker stack
mutation tests:
- `undo-conflict-clears-history-test`
- `undo-works-with-remote-updates-test`
- `undo-skips-when-parent-missing-test`
- `undo-skips-when-block-deleted-remote-test`
- `undo-skips-when-undo-would-create-cycle-test`
- `undo-skips-conflicted-move-and-keeps-earlier-history-test`
- `redo-builds-reversed-tx-when-target-parent-is-recycled-test`
- `undo-skips-move-when-original-parent-is-recycled-test`
### Bucket 5. Main-thread leftovers.
After Buckets 1-4:
- keep only route restoration
- keep only cursor restoration
- keep only proxy/coordination tests
- add a namespace comment in `src/test/frontend/undo_redo_test.cljs` that it is
no longer the DB-history source-of-truth test file
## Implementation Rules
1. Every moved worker test must use a fixture that owns both:
- worker datascript conn
- worker client-ops conn
2. That fixture must route tx reports through both:
- `frontend.worker.sync/enqueue-local-tx!`
- `frontend.worker.undo-redo/gen-undo-ops!`
3. Tests that expect persisted action lookup must attach a stable
`:db-sync/tx-id`.
4. Do not duplicate replay tests between `worker/undo_redo_test.cljs` and
`worker/db_sync_test.cljs`.
5. Delete the original test only after the worker version passes.
## Consequences
### Positive
- The test suite matches the actual runtime ownership boundary.
- Worker replay regressions are caught where they actually happen.
- The old main-thread test file becomes much easier to reason about.
### Negative
- Some existing tests need adaptation rather than straight copy because they
implicitly relied on old main-thread stack storage.
- The migration requires explicit decisions about whether a test is about
worker history ownership or worker replay behavior.
## Verification
Representative focused commands during migration:
```bash
bb dev:test -v frontend.worker.undo-redo-test/undo-records-only-local-txs-test
bb dev:test -v frontend.worker.undo-redo-test/undo-history-records-semantic-action-metadata-test
bb dev:test -v frontend.worker.undo-redo-test/undo-history-canonicalizes-insert-block-uuids-test
bb dev:test -v frontend.worker.db-sync-test/apply-history-action-redo-replays-save-block-test
bb dev:test -v frontend.worker.db-sync-test/apply-history-action-redo-replays-block-concat-test
bb dev:test -v frontend.worker.db-sync-test/apply-history-action-redo-replays-paste-into-empty-target-test
```
## Exit Criteria
- `src/test/frontend/worker/undo_redo_test.cljs` owns the DB-history recording
tests.
- `src/test/frontend/undo_redo_test.cljs` contains only main-thread coordination
tests.
- No worker-owned DB-history scenario is tested only in the main-thread file.
@@ -0,0 +1,58 @@
# ADR 0014: KV-Row R2 Snapshot Download With Worker-Owned Low-Memory Import
Date: 2026-04-01
Status: Proposed
## Context
Snapshot download previously exported Datascript datoms as gzip NDJSON from the
server and parsed/transacted datoms on the client main-thread handler path.
That design had two issues:
1. Server snapshot export walked full datoms and spent avoidable CPU/memory.
2. Client download logic lived in handler code and was not aligned with worker
ownership for large-graph import.
We already use framed Transit `kvs` rows for snapshot upload. Download should
converge on the same wire format.
## Decision
1. `GET /sync/:graph-id/snapshot/download` and `/snapshot/stream` export framed
Transit `kvs` rows (`[addr content addresses]`) instead of datom NDJSON.
2. Snapshot download payload content-type is `application/transit+json`
(gzip-compressed when available).
3. Server snapshot export reads directly from sqlite `kvs` rows in ascending
`addr` batches and streams framed payloads to response/R2.
4. Graph snapshot download orchestration is moved to
`frontend.worker.sync.download` and invoked from db-worker thread API.
5. Handler code delegates graph download to worker API instead of parsing
snapshot payloads directly.
6. Client import adds row-chunk API (`:thread-api/db-sync-import-rows-chunk`).
Row batches are staged in temp sqlite, then replayed into target conn in
schema-first order.
7. Replay order must transact schema-critical datoms before regular data:
- `:logseq.kv/schema-version` entity datoms
- attribute-definition datoms (`:db/ident` and `:db/*` metadata such as
`:db/valueType`, `:db/cardinality`, `:db/unique`, `:db/isComponent`)
- all remaining datoms
## Consequences
### Positive
- Lower server CPU/memory for snapshot export (no datom NDJSON generation).
- Download/upload snapshot format is unified around framed `kvs` rows.
- Download pipeline ownership moves to worker sync module.
- Schema-first replay protects index/schema correctness for large imports.
### Tradeoffs
- Client still performs datom replay during finalize to rebuild a consistent
target store, so import cost shifts to worker finalize phase.
- Adds temp sqlite staging and one additional import path (`rows` alongside
legacy datom chunk path).
## Verification
- Server tests assert snapshot download/stream return framed kv rows with
transit content-type and sorted addresses.
- Handler tests assert graph download delegates to worker API and maintains
download-state lifecycle.
- Worker tests assert rows-chunk API wiring and schema-first import ordering.
@@ -0,0 +1,123 @@
# ADR 0015: Store Client Ops in SQLite `client_ops` and Metadata in `sync_meta`
Date: 2026-04-10
Status: Accepted
## Context
Client sync state is currently persisted via a DataScript-backed store in the
dedicated `client-ops-*` sqlite database (`kvs` + DataScript entities).
This design has become a bottleneck for local sync hot paths:
1. DataScript entity/datoms read-write patterns add avoidable CPU overhead for
client op persistence and lookup.
2. Persisting client ops as DataScript entities consumes more space than
purpose-built relational rows for the same data.
3. Metadata (`local-tx`, checksum, graph uuid) and operation payloads are mixed
in DataScript entity shape, which complicates low-level sqlite debugging and
parity with server-side sync storage.
Server sync storage already uses explicit sqlite tables (`tx_log`,
`sync_meta`) over the same sqlite runtime. Client storage should follow the
same direction.
## Decision
1. Keep the existing dedicated `client-ops-*` sqlite database file.
Do not merge this storage into the main graph sqlite DB in this change.
2. Replace DataScript persistence for client ops/metadata with direct sqlite
tables:
- `sync_meta` for key/value metadata rows
- `client_ops` for operation rows
3. `sync_meta` schema:
- `key TEXT PRIMARY KEY`
- `value TEXT`
4. `sync_meta` keys for this ADR:
- `local-tx`
- `checksum`
- `graph-uuid`
5. `client_ops` stores both local tx ops and asset ops (single table,
discriminated by row kind).
6. `client_ops` minimum columns:
- identity and ordering:
- `id INTEGER PRIMARY KEY AUTOINCREMENT`
- `kind TEXT NOT NULL` (`'tx'` or `'asset'`)
- `created_at INTEGER NOT NULL`
- local tx fields:
- `tx_id TEXT` (uuid string)
- `pending INTEGER NOT NULL DEFAULT 0`
- `failed INTEGER NOT NULL DEFAULT 0`
- `outliner_op TEXT`
- `undo_redo TEXT` (`undo`/`redo`/`none`)
- `forward_outliner_ops TEXT` (Transit string)
- `inverse_outliner_ops TEXT` (Transit string)
- `inferred_outliner_ops INTEGER`
- `normalized_tx_data TEXT` (Transit string)
- `reversed_tx_data TEXT` (Transit string)
- asset fields:
- `asset_uuid TEXT`
- `asset_op TEXT` (`update-asset`/`remove-asset`)
- `asset_t INTEGER`
- `asset_value TEXT` (Transit or JSON string payload)
7. Required indexes/constraints:
- unique tx identity for undo/redo lookup:
- `UNIQUE(tx_id)` where `kind='tx'` and `tx_id IS NOT NULL`
- pending tx scan in stable order:
- index on `(kind, pending, created_at, id)`
- asset op lookup by uuid:
- index on `(kind, asset_uuid)`
8. `asset ops` must be stored in `client_ops` (not separate DataScript
entities).
9. Client code must access this data via SQL adapter functions (insert/select/
update/delete), not `d/datoms`/`d/entity` over client-op storage.
10. Keep payload encoding compatible with existing sync payload handling by
storing complex fields as Transit strings.
## Consequences
### Positive
- Hot path operations (enqueue local tx, pending scan, tx-id lookup, asset-op
mutation) become cheaper and more predictable.
- Storage is denser than DataScript entity persistence for client ops.
- Debugging and inspection are easier with explicit sqlite rows.
- Client layout aligns with server-style metadata table (`sync_meta`).
### Tradeoffs
- Introduces SQL adapter code replacing generic DataScript entity APIs.
- Requires new client-op table schema bootstrap and index management.
- Existing client-op DataScript rows are no longer read by new code.
## Safety and Integrity Rules
1. All mutating operations on `client_ops`/`sync_meta` use sqlite transactions.
2. Ordering guarantees for pending tx upload rely on `(created_at, id)` order.
3. Undo/redo lookup remains keyed by `tx_id` and must continue to read forward/
inverse semantic ops from persisted local tx rows.
4. `pending` and `failed` flags are explicit row state and must not be inferred
from absence.
5. This change does not alter checksum semantics; it only changes where client
checksum metadata is stored.
## Migration
Chosen policy: no migration from old DataScript client-op entities.
On first open with this schema:
- initialize `sync_meta` + `client_ops` tables and indexes.
- start client-op state empty.
Rationale:
- client-op state is derived/operational, not authoritative graph content.
- normal sync flows (pull/upload/asset requeue) reconstruct operational state.
- avoids fragile one-time conversion logic across old entity layouts.
## Verification
Focused verification after implementation:
```bash
bb dev:test -v frontend.worker.db-sync-test/handle-local-tx-persists-pending-local-tx-test
bb dev:test -v frontend.worker.db-sync-test/flush-pending-clears-pending-local-tx-count-test
bb dev:test -v frontend.worker.undo-redo-test/undo-history-records-semantic-action-metadata-test
bb dev:test -v frontend.worker.db-sync-test/asset-ops-queue-coalesces-update-and-remove-test
```
Additional checks:
- pending tx query returns rows in deterministic `(created_at, id)` order.
- undo/redo can still resolve tx history by `tx_id`.
- `local-tx`, `checksum`, and `graph-uuid` read/write through `sync_meta`.
+291
View File
@@ -0,0 +1,291 @@
# ADR 0016: Electron Markdown Mirror
Date: 2026-05-05
Status: Accepted
## Context
Logseq DB graphs do not expose one editable Markdown file per page in the graph
directory. Some desktop workflows still need a Markdown representation that can
be read by external tools, backed up, indexed, or inspected outside Logseq.
The mirror must not become another graph source of truth. Editing should remain
fast, and saving a block must not wait for Markdown rendering or filesystem
writes on the renderer main thread.
The first supported runtime is the Electron desktop app. Browser and mobile
builds do not have the same graph-directory filesystem guarantees.
## Decision
1. Add an Electron-only Settings toggle for Markdown Mirror.
2. Persist the toggle in Electron user settings as
`:feature/markdown-mirror?`.
3. When the setting is enabled for the Electron app, Logseq writes derived
Markdown files under the current graph directory:
- journals:
`mirror/markdown/journals/<journal-file-name>.md`
- other pages:
`mirror/markdown/pages/<page-file-name>.md`
4. For a graph at `~/logseq/graphs/graph-xxx`, mirror files are written under:
- `~/logseq/graphs/graph-xxx/mirror/markdown/journals/`
- `~/logseq/graphs/graph-xxx/mirror/markdown/pages/`
5. Markdown Mirror is derived output. The DB remains the source of truth.
6. Files under `mirror/markdown/**` must be ignored by graph import, file
watchers, and graph parsing so the mirror never feeds back into the graph.
7. The feature is not available in browser or mobile builds, even if a stale
setting value exists.
8. Settings exposes an explicit "Regenerate full mirror" action that asks the
DB worker to rewrite the complete mirror for the current graph.
9. Built-in pages and property pages, including user-created properties, are not
exported to the mirror. User Tag/Class pages are normal user content and are
exported.
## Runtime Ownership
1. The renderer owns only:
- the Settings row
- reading and updating `:feature/markdown-mirror?`
- pushing the enabled state to the DB worker when it changes
2. The DB worker owns:
- detecting affected page ids from successful local transactions
- rendering page Markdown from the worker DB snapshot
- scheduling and coalescing mirror jobs
- running explicit full-mirror regeneration jobs
- invoking platform filesystem writes
3. The Electron main process must not render Markdown. It may provide filesystem
primitives if needed, but content generation stays with the worker.
4. Editor save paths enqueue mirror work and return immediately. They must not
wait for rendering, directory creation, stat, write, rename, or delete.
## Reusable Core and CLI Path
1. Markdown Mirror path planning, filename normalization, page rendering, write
deduplication, atomic writes, rename cleanup, and delete cleanup live in a
worker/core namespace that does not depend on Electron UI state.
2. The Electron app only owns feature activation through Settings.
3. The CLI should be able to reuse the same core by passing an explicit graph,
DB snapshot, and node filesystem platform context.
4. Future CLI support should not introduce a second Markdown serializer or a
different filename normalization policy.
5. Future CLI support should reuse the same mirror-path allocation index so the
Electron app and CLI do not produce different file names for the same graph.
## Output Layout and Naming
1. Journal pages are written below `mirror/markdown/journals/`.
2. Non-journal pages are written below `mirror/markdown/pages/`.
3. Journal file names use the existing Logseq journal file-name rules for the
graph configuration.
4. Non-journal page file names use the normalized page title:
`<page-file-name>.md`.
5. Page file names must stay friendly to external Markdown tools such as Emacs,
VS Code, and Obsidian. Do not include page uuid in normal mirror file names.
6. Page title is not page identity. The page uuid is still the internal mirror
identity, but it is stored in the mirror index rather than exposed in the
file name.
7. Duplicate non-journal page titles are handled by stable title suffix
allocation:
- first allocated page: `pages/Foo.md`
- second allocated page: `pages/Foo (2).md`
- third allocated page: `pages/Foo (3).md`
8. Once a page uuid is assigned a mirror path, keep that path stable until the
page is renamed or deleted. Do not renumber existing duplicate-title mirror
paths when another duplicate is created or removed.
9. The implementation keeps a per-graph mirror index under
`mirror/markdown/.index.edn`.
10. The mirror index stores at least:
- page uuid -> relative mirror path
- relative mirror path -> page uuid
- page uuid -> last known normalized title stem
11. The mirror index is implementation metadata for path stability. It is not
graph content and must be ignored by graph import and watchers along with the
rest of `mirror/markdown/**`.
12. All mirror file names pass through a single cross-platform filename
normalizer before joining paths.
13. Duplicate journal-day entities indicate invalid graph state for the mirror.
The implementation must fail those journal mirror jobs and surface a
diagnostic instead of choosing a winner.
14. If two entities still map to the same mirror path, the implementation must
fail the mirror job for that path and surface a diagnostic instead of
overwriting an unrelated page.
15. Page rename moves the mirror by writing the new path, updating the mirror
index, and deleting the old path after the new file has been written.
16. Page deletion deletes the corresponding mirror file and removes the page uuid
from the mirror index.
17. The write guard must reject any computed path outside the graph's
`mirror/markdown/` directory.
18. Built-in pages and property pages are excluded from path allocation and
mirror writes. User Tag/Class pages are not excluded by this rule. If a
previously mirrored page becomes excluded, the old mirror file is removed.
## Duplicate Page Title Allocation
1. For non-journal pages, compute the normalized title stem first.
2. If the page uuid already exists in the mirror index and the normalized title
stem did not change, reuse the indexed path.
3. If the page uuid is new for that title, allocate the first unused path in this
sequence:
- `pages/<stem>.md`
- `pages/<stem> (2).md`
- `pages/<stem> (3).md`
4. A path is considered unavailable when the mirror index maps it to a different
live page uuid.
5. Deleted page paths become available for future allocation only after the
deleted page uuid is removed from the index.
6. Rename is treated as a new allocation for the new title stem. Existing pages
with the old title keep their already allocated paths.
7. If the mirror index is missing or unreadable, rebuild it from the current DB
in deterministic page order before writing. Deterministic order should use a
stable key such as page title plus page uuid.
8. The rebuilt index is allowed to choose paths for pages that had no previous
allocation. It must not overwrite a live existing path that is already mapped
to another page uuid.
## Rename and Delete
1. Page rename moves the mirror by writing the new path and deleting the old
path after the new file has been written.
2. Page deletion deletes the corresponding mirror file.
3. The implementation keeps a small per-graph mirror index keyed by page uuid so
rename and delete handling does not require scanning the mirror directory on
every transaction.
## Filename Normalization
1. Mirror file names must be portable across macOS, Windows, and Linux.
2. Use one shared normalizer for journal and page mirror file names.
3. The normalizer must:
- reject or replace path separators (`/`, `\`)
- reject or replace Windows-invalid characters (`<`, `>`, `:`, `"`, `|`,
`?`, `*`) and ASCII control characters
- reject or rewrite reserved Windows device names such as `CON`, `PRN`,
`AUX`, `NUL`, `COM1` through `COM9`, and `LPT1` through `LPT9`
- trim trailing spaces and dots because Windows does not preserve them
- reject empty names after normalization
- bound each file-name component to a safe byte length before appending
`.md`
4. Normalize Unicode to one canonical form before sanitizing so the same page
title produces the same mirror path across filesystems with different Unicode
normalization behavior.
5. The normalizer must be deterministic and must not depend on the current
operating system. A graph mirrored on macOS should choose the same logical
file name as the same graph mirrored on Windows.
6. If normalization changes the display title segment, the mirror index and
duplicate-title suffix allocation still preserve identity for non-journal
pages.
7. If a journal title normalizes to an unsafe or colliding file name, fail the
journal mirror job and surface diagnostics instead of inventing a fallback
name.
8. Path construction must join only validated path components. It must never
concatenate unchecked page titles into filesystem paths.
## Scheduling and Performance
1. Mirror rendering is incremental. A transaction schedules only pages affected
by that transaction.
2. Jobs are coalesced by page uuid. If a page is edited repeatedly before its
job runs, only the latest worker DB state is rendered.
3. Scheduling uses a short debounce window per graph to reduce write churn while
preserving near-real-time output.
4. Mirror writes are serialized per graph to avoid path races during rename and
delete.
5. Before writing, compare the generated Markdown with the current file content
or with the last written content hash. Skip the write when content is
unchanged.
6. Write files atomically:
- ensure the target directory exists
- write to a temporary file in the same directory
- rename the temporary file over the target
7. Heavy work is forbidden on the renderer main thread:
- no full-graph export
- no Markdown rendering
- no filesystem reads or writes
- no synchronous IPC waiting for mirror completion
8. Full regeneration is an explicit Settings action. The renderer only sends a
worker request; page selection, rendering, and filesystem writes stay in the
DB worker.
9. Enabling the setting starts incremental mirroring for subsequent page edits.
It does not implicitly run full regeneration.
## Markdown Content
1. Reuse the existing page-to-Markdown export pipeline used by worker export
APIs instead of introducing a separate renderer-side serializer.
2. The mirror output uses the Logseq Markdown syntax described in
`docs/logseq-markdown-syntax.md`.
3. Mirror files always include a page `id:: <uuid>` line so the file can be
associated with its DB page without encoding the uuid in the file name.
4. Blocks are Markdown list items that use `-`.
5. User-visible page and block properties are Markdown list items that use `*`
and keep the Logseq property marker, for example `* owner:: [[Alice]]`.
6. Open default property values are exported as nested value blocks below the
property key. Closed values remain inline with the property key.
7. Node property values are exported as Logseq page references, for example
`[[Node title]]`, rather than block reference syntax.
8. Task status is encoded on the block line, for example `- TODO ship`, and is
not exported as a separate property list item.
9. Assets are referenced as normal exported Markdown references. This ADR does
not copy assets into `mirror/markdown/`.
10. Page references remain in Logseq wiki-link form, for example `[[Foo]]`.
11. Ambiguous page references caused by duplicate page titles are an accepted
limitation of Markdown Mirror. Do not rewrite page references to uuid-based
links or relative Markdown links in this ADR.
## Failure Handling
1. Filesystem and path errors fail the mirror job for the affected page.
2. Failures are logged with graph, page uuid, target path, and error details.
3. Repeated failures should be visible from Settings or diagnostics; do not show
a toast on every keystroke.
4. The feature must not silently fall back to browser storage, OPFS, or another
output directory.
5. If the graph directory is not available, the worker rejects mirror jobs for
that graph until the graph is reopened with a valid directory.
## Non-goals
1. Markdown Mirror is not bidirectional sync.
2. Editing files in `mirror/markdown/` does not update the graph.
3. The mirror is not a backup format with guaranteed import fidelity.
4. The mirror does not replace existing graph export features.
5. The mirror does not support browser or mobile runtimes in this ADR.
## Consequences
### Positive
- Desktop users get a readable Markdown projection inside the graph directory.
- Editor latency is protected because rendering and disk I/O are worker-owned
and asynchronous.
- The output layout is predictable for tools that watch journals and pages
separately.
- Page file names remain readable and practical in external Markdown tools.
- Ignoring `mirror/markdown/**` prevents mirror-generated files from becoming
graph input.
### Tradeoffs
- The mirror can lag slightly behind the latest edit because writes are
debounced and serialized.
- A per-graph mirror index is needed for reliable rename and delete cleanup.
- Duplicate page references such as `[[Foo]]` remain ambiguous in mirror output.
- The first version does not backfill every existing page automatically when the
setting is enabled; users run full regeneration explicitly.
- External edits to mirror files are overwritten by later Logseq edits.
- Property pages are intentionally absent from the mirror, so the output is not
a complete DB export even though page and block property drawers are included.
## Verification
Implementation should add focused coverage for:
```bash
bb dev:test -v frontend.worker.markdown-mirror-test/enabled-electron-edit-writes-page-mirror-test
bb dev:test -v frontend.worker.markdown-mirror-test/enabled-electron-edit-writes-journal-mirror-test
bb dev:test -v frontend.worker.markdown-mirror-test/disabled-setting-does-not-write-mirror-test
bb dev:test -v frontend.worker.markdown-mirror-test/repeated-edits-coalesce-to-latest-content-test
bb dev:test -v frontend.worker.markdown-mirror-test/rename-removes-old-mirror-path-test
bb dev:test -v frontend.worker.markdown-mirror-test/delete-removes-mirror-file-test
bb dev:test -v frontend.worker.markdown-mirror-test/same-title-pages-write-distinct-stable-friendly-paths-test
bb dev:test -v frontend.worker.markdown-mirror-test/page-references-remain-wiki-links-test
bb dev:test -v frontend.worker.markdown-mirror-test/page-mirror-exports-property-values-test
bb dev:test -v frontend.worker.markdown-mirror-test/page-mirror-exports-page-property-values-test
bb dev:test -v frontend.worker.markdown-mirror-test/page-mirror-exports-node-property-values-as-page-refs-test
bb dev:test -v frontend.worker.markdown-mirror-test/full-regeneration-writes-existing-non-built-in-non-property-pages-test
bb dev:test -v frontend.worker.markdown-mirror-test/invalid-filename-characters-are-normalized-test
bb dev:test -v frontend.worker.markdown-mirror-test/windows-reserved-filename-fails-with-diagnostic-test
bb dev:test -v frontend.worker.markdown-mirror-test/mirror-path-collision-fails-without-overwrite-test
```
Additional checks:
- `mirror/markdown/**` is excluded from graph parsing and file watchers.
- Editor save does not await mirror completion.
- Browser and mobile builds do not expose the setting and do not schedule mirror
jobs.
- Atomic write failures do not leave partial target files.
@@ -0,0 +1,195 @@
# ADR 0017: URL Target Graph Resolution
Date: 2026-05-20
Status: Accepted
## Context
Logseq URLs can point at a graph, page, block, or file. Today the graph target is
not carried through one coherent flow.
The custom protocol path is handled in Electron main:
- `logseq://graph/<graph>` and `logseq://new-window/<graph>` are parsed in
`electron.url/local-url-handler`.
- Electron resolves `<graph>` through `electron.handler/get-graph-name`.
- If no window is already associated with that graph, Electron asks the current
renderer to run `openNewWindowOfGraph`.
- The renderer then opens a new Electron window with `#/?graph=<repo>`.
This depends on renderer IPC timing and renderer-local storage. On first app
launch, the initial deeplink is handled soon after the main window is created,
while the renderer listener can still be unavailable. When the message is lost,
the newly opened app falls back to the stored `:git/current-repo`, so the URL
appears to always open the current graph.
The web app has a related weakness. `frontend.state` only reads `:graph` from
`frontend.util/parse-params` during initial state creation, and that parser only
understands hash fragments shaped like `#/?graph=...`. Page/block web URLs and
later hash changes can route inside the currently opened graph instead of first
switching to the graph named by the URL.
Graph names are not stable identifiers. Users can rename graphs, and two linked
graphs can share the same short basename. URLs that are meant to survive
renames, browser sessions, and device handoffs need to identify the graph by id.
## Decision
Make URL graph selection an explicit target object and process it before route
navigation in the renderer, with a small persisted graph registry used to turn
stable graph ids into local repos.
1. Introduce a shared URL target model for Electron protocol URLs, web URLs, and
mobile URLs:
- `:graph-id` - canonical graph id from the URL.
- `:graph-identifier` - compatibility alias, such as a short graph name or
full DB repo name.
- `:repo` - resolved full local repo name, for example `logseq_db_work`.
- `:route` - one of graph home, page, block, or file.
- `:open-mode` - current window or new window.
- `:source` - protocol URL, web URL, startup argv, or second instance.
2. Use `:graph-id` as the canonical URL identity. For remote graphs,
`:graph-id` is the remote graph UUID. For local-only graphs, `:graph-id` is
the local graph UUID. Generated URLs should include `graph-id` whenever the
graph id is known.
3. Resolve URL graph targets through one graph resolver that accepts, in order:
- graph ids from the local graph registry;
- full DB repo names, such as `logseq_db_work`;
- short local graph names, such as `work`;
- existing canonicalized DB repo names.
4. Treat an unresolved graph id as an unresolved URL target, not as a successful
match for the current graph. Mobile reports this to the user. Web startup
currently logs the unresolved target and continues with the tab-local or
stored graph so the app can still boot.
5. For Electron custom protocol URLs, the main process owns URL intake and
graph-name/graph-id resolution. This branch keeps the existing
renderer-mediated window creation path for custom protocol URLs and teaches
it to resolve graph ids through the registry.
6. For web and mobile URLs, the renderer owns URL intake and graph resolution.
It must switch to the target graph before applying the route target.
7. Once the target graph is loaded, apply the route target exactly once.
8. Do not store URL graph targets in `:git/current-repo` until the graph switch
succeeds.
9. Use `sessionStorage` for tab-local graph identity on web reloads that do not
carry a URL graph target. This preserves each browser tab's graph without
appending `graph-id` to every internal route.
## Supported URL Shapes
Canonical generated web URLs use graph ids:
- `https://logseq.com/?graph-id=<graph-uuid>`
- `https://logseq.com/page/<page-uuid>?graph-id=<graph-uuid>`
- `https://logseq.com/block/<block-uuid>?graph-id=<graph-uuid>`
Electron protocol URLs accept graph ids through the same graph identifier slot:
- `logseq://graph/<graph-uuid>`
- `logseq://graph/<graph-uuid>?page=<page-name-or-uuid>`
- `logseq://graph/<graph-uuid>?block-id=<block-uuid>`
- `logseq://new-window/<graph-uuid>?page=<page-name-or-uuid>`
Compatibility URLs remain accepted:
- `logseq://graph/<graph-name>`
- `logseq://graph/<graph-name>?page=<page-name>`
- `logseq://graph/<graph-name>?block-id=<uuid>`
- `logseq://graph/<graph-name>?file=<file>`
- `https://logseq.com/#/?graph=<graph-name>`
- `https://logseq.com/#/page/<page-name>?graph=<graph-name>`
Generated web URLs should use path routes instead of hash routes. The app may
continue accepting hash-routed URLs during migration, but new share/copy-link
helpers should emit path URLs with `graph-id`.
## Graph Registry
URL graph-id resolution must not open every graph database during startup. Keep a
small graph registry outside each graph DB.
1. Web and mobile store the graph registry in IndexedDB.
2. Electron stores the graph registry in
`(.getPath app "home")/.logseq/graphs.edn`.
3. Registry entries include at least:
- `:graph-id`
- `:repo`
- `:graph-name`
- `:local-graph-id`
- `:updated-at`
4. Do not persist a separate `:rtc-graph-id` in the registry. For remote graphs,
`:graph-id` is the remote graph UUID. For local-only graphs, `:graph-id` is
the local graph UUID.
5. Update the registry whenever a graph is created, opened, imported,
downloaded, uploaded to RTC, renamed, unlinked, or deleted.
6. If a registry lookup fails for a graph id, the app may run an explicit repair
path that enumerates local graph storage and opens graph DBs to rebuild the
registry. This repair path must not be the normal URL-open path.
## Electron Runtime Design
1. Store the registry at `(.getPath app "home")/.logseq/graphs.edn`.
2. Resolve Electron protocol graph identifiers through that registry before
falling back to existing repo/name lookup.
3. For shift-click in the graph list, open a new Electron window through the
existing `openNewWindow` IPC using the resolved repo. Electron windows still
use repo identity for window creation.
4. Keep a per-window pending target in Electron state only for work that cannot
be represented safely in the URL, such as a file redirect that requires graph
readiness. Avoid a single global `:window/once-graph-ready` callback because
concurrent windows can overwrite each other.
5. When the renderer reports `graphReady`, Electron should look up and consume
the pending target for that specific window id.
6. Existing error notifications for missing or unknown graphs remain, but they
should be sent to the selected/fallback window after graph resolution fails.
7. Direct main-process creation of route-aware graph windows remains follow-up
work; it should replace the renderer-mediated `openNewWindowOfGraph` path.
## Web Runtime Design
1. Add a parser that can read graph targets from path URLs and compatibility
hash URLs.
2. During frontend startup:
- parse the URL target;
- resolve `:graph-id` through the IndexedDB graph registry;
- resolve compatibility `:graph-identifier` against the known graph list when
no `:graph-id` is present;
- initialize from the resolved URL target when it resolves;
- otherwise use the tab-local `sessionStorage` graph target, then the stored
`:git/current-repo`, then the first linked repo.
3. During startup, apply resolved page/block URL targets after the target graph
is restored. Later in-app route changes with graph targets are follow-up
work.
4. During route generation:
- generated page routes include `graph-id` when the current graph id is
available, but startup/render-phase redirects tolerate a temporarily
unavailable graph id instead of crashing.
5. Generated web links from `frontend.util.url` should include `graph-id` on the
actual route.
6. Web "open in another tab" and shift-click from All graphs open `#/?graph-id=`
URLs for existing local graphs.
## Mobile Runtime Design
1. Use the same URL target parser and resolver as the web runtime.
2. Store and resolve the graph registry from IndexedDB.
3. Treat mobile app intents and universal links as URL sources that produce the
same target model.
## Consequences
- Resolvable graph-id URLs open the requested graph instead of silently using the
last current graph.
- Electron protocol URLs can resolve graph ids via the registry, but route-aware
direct window creation remains follow-up work.
- Web graph URLs become route-aware, so page and block links can switch graph
before navigating during startup and mobile deeplink handling.
- Web and mobile graph-id resolution is fast because it reads the graph registry
instead of scanning OPFS graph directories and opening graph databases.
- Electron graph-id resolution is fast because it reads
`(.getPath app "home")/.logseq/graphs.edn` instead of opening each graph
database.
- Bare web reloads preserve the tab's graph through `sessionStorage`, so two
tabs can remain on different graphs even when one tab changes the global
current graph.
- The implementation needs focused tests around URL parsing, graph resolution,
first-launch Electron deeplinks, second-instance deeplinks, and web/mobile
route changes.
## Follow-up Work
1. Add Electron main tests for first-launch and second-instance deeplinks.
2. Add renderer tests proving that web URLs switch graph before page/block
navigation after graph switches triggered by later route changes, not only
startup URLs.
3. Add graph registry read/write tests for IndexedDB and the Electron
`(.getPath app "home")/.logseq/graphs.edn` registry.
4. Replace `:window/once-graph-ready` with per-window pending targets.
5. Replace Electron custom protocol's renderer-mediated `openNewWindowOfGraph`
path with direct main-process route-aware window creation.
+274
View File
@@ -0,0 +1,274 @@
# ADR 0018: Complete Rum Hooks Refactor
Date: 2026-05-29
Status: Proposed
## Context
Logseq frontend, mobile, and shui UI code still relies on Rum mixins and old
Rum lifecycle maps for state, subscriptions, query registration, event
listeners, memoization, DOM effects, and cleanup.
The current `master` tree has broad usage:
- 542 `rum/defc` components and 120 `rum/defcs` components under `src/main`
and `deps/shui/src`.
- 100 `rum/local` usages.
- Heavy use of `rum/reactive`, `rum/static`, `db-mixins/query`,
`mixins/container-id`, custom lifecycle maps, and `:should-update`.
- Shared mixin definitions in `src/main/frontend/mixins.cljs` and
`src/main/frontend/db_mixins.cljs`.
- Existing hook wrappers in `deps/shui/src/logseq/shui/hooks.cljs`, with
selected atom hooks re-exported from `src/main/frontend/rum.cljs`.
Mixins hide side effects and make component behavior harder to reason about.
The most sensitive cases are editor focus and cursor handling, block tree
rendering, reactive query refresh, plugin rendering, PDF/code integrations, and
mobile mount/unmount effects.
## Decision
Replace all existing Rum mixins and Rum lifecycle maps with hook-based component
code as a complete refactor.
The migration uses one explicit hook path for state, effects, subscriptions,
event listeners, query registration, memoization, and cleanup. The old mixin
namespaces must be removed by the end of the refactor, not left as wrappers or
compatibility shims.
The migration applies to:
- `src/main/frontend/`
- `src/main/mobile/`
- `deps/shui/src/`
The refactor is not complete until there is no behavior regression and no
performance regression on the affected UI paths. Any replacement hook must match
the old lifecycle timing, subscription semantics, cleanup behavior, and
memoization characteristics where those characteristics were observable.
Replacement code must use public React/Rum hook APIs only. It must not depend on
Rum internals such as `rum/*reactions*`, private dynamic bindings, or
reimplementations of `rum/reactive` under another name.
## Hook Foundation
Add hook APIs before migrating broad component areas. These hooks are the new
implementation path, not an adapter layer over the old mixin namespaces.
1. Add subscription hooks for render-time `rum/react`, `util/react`, and
`state/sub` usage:
- `frontend.state/use-sub`
- `frontend.state/use-sub-config`
- `frontend.state/use-sub-editing?`
- keep `frontend.rum/use-atom` and `frontend.rum/use-atom-in` as the
atom-level APIs.
2. Replace `db-mixins/query` with an explicit hook-backed query scope.
`db-mixins/query` currently binds `frontend.db.react/*query-component*` and
`*reactive-queries*` during render, then removes the component token on
unmount. The replacement should create a stable component token with
`use-ref`, register cleanup with `use-effect!`, and bind query tracking
while rendering the body.
3. Replace `rum/local` with:
- `rum/use-state` for values that affect rendering;
- `rum/use-ref` for mutable values that should not trigger rendering;
- `frontend.rum/use-atom` only where the state is intentionally atom-shaped
and shared with existing functions.
4. Replace event mixins with hook APIs:
- `use-event-listener`
- `use-window-keydown`
- `use-window-keyup`
- `use-hide-on-esc-or-outside`
- `use-modal-state`
5. Replace `mixins/container-id` with an explicit `use-container-id` hook that
derives from the same stable key currently built in the mixin.
## Lifecycle Mapping
Rum lifecycle maps are migrated directly to hooks:
- `:init`: use lazy `use-state`, `use-ref`, or pure `let` bindings. Do not move
side effects here.
- `:will-mount`: use `use-effect!` or `use-layout-effect!` with an empty
dependency vector.
- `:did-mount`: use `use-effect! []` for subscriptions, timers, and network
work; use `use-layout-effect! []` for focus, sizing, and DOM measurement.
- `:did-update`: use `use-effect!` with explicit dependencies. Use a first-render
guard only when old behavior intentionally skipped mount.
- `:will-update`: derive values during render, or use a previous-value ref plus
effect when side effects are required.
- `:will-unmount`: return cleanup from the effect that created the resource.
- `:wrap-render`: replace with explicit wrapper functions, macros, profiling
calls, or error-boundary components.
- `:should-update` and `rum/static`: replace with smaller memoized child
components, `React.memo`, or no memoization if the old optimization is not
meaningful.
- `:did-catch`: keep explicit class-based error boundaries where needed. React
hooks cannot replace render error boundaries.
## Migration Order
### Phase 1: Hook Foundation
1. Add state subscription, event listener, container id, and query-scope hooks.
2. Add focused tests for subscription cleanup and query cleanup.
3. Add a lint/search check that blocks new Rum mixin usage.
4. Migrate one small component from each behavior category:
- one `rum/local` component;
- one lifecycle component;
- one `db-mixins/query` component;
- one `rum/reactive` component.
### Phase 2: Low-Risk Leaf Components
Migrate components without editor focus, query refresh, plugin rendering, or PDF
behavior.
Good first targets:
- `src/main/frontend/components/avatar.cljs`
- `src/main/frontend/components/window_controls.cljs`
- `src/main/frontend/components/find_in_page.cljs`
- `src/main/frontend/components/selection.cljs`
- simple `src/main/mobile/components/*` components
- simple `deps/shui/src/logseq/shui/*` components
For each file, remove mixins, convert `rum/defcs` to `rum/defc` when the `state`
parameter is gone, and use hooks for subscriptions and effects.
### Phase 3: Shared Query Components
Migrate components that combine `rum/reactive` and `db-mixins/query`.
Targets include:
- page and block references;
- property values;
- query result views;
- journal and all-pages views;
- right sidebar block/page renderers.
Every `react/q` consumer should move from `util/react` or `rum/react` to a hook
subscription. Query cleanup must be verified by checking
`frontend.db.react` component maps after mount/unmount.
### Phase 4: Editor, Block Tree, and Navigation
Migrate the high-risk rendering core in small PRs by behavior:
1. Editor search and autocomplete lifecycles.
2. Editor input event listeners and cursor restoration.
3. Block content/edit switching.
4. Asset rendering and upload/download state.
5. Block container query scope and sidebar state.
6. Page mount/update side effects.
7. Header/sidebar collaboration and recent-highlight behavior.
Primary files:
- `src/main/frontend/components/editor.cljs`
- `src/main/frontend/components/block.cljs`
- `src/main/frontend/components/page.cljs`
- `src/main/frontend/components/header.cljs`
- `src/main/frontend/components/container.cljs`
Use `use-layout-effect!` for focus, selection, size, and scroll effects that
depend on mount/update ordering.
### Phase 5: Extensions and Heavy Integrations
Migrate extension components after core hooks are stable:
- `src/main/frontend/extensions/code.cljs`
- `src/main/frontend/extensions/fsrs.cljs`
- `src/main/frontend/extensions/latex.cljs`
- `src/main/frontend/extensions/pdf/core.cljs`
- `src/main/frontend/extensions/video/youtube.cljs`
These contain third-party DOM integrations, delayed rendering, timers, and
external cleanup. Prefer one integration per PR.
### Phase 6: Remove Old Mixin API
After all usage is gone:
1. Delete `src/main/frontend/mixins.cljs`; move any still-needed non-mixin
helper logic into hook-focused namespaces before deletion.
2. Delete `src/main/frontend/db_mixins.cljs`.
3. Remove unused `rum/reactive`, `rum/static`, `rum/local`, and lifecycle map
imports/usages.
4. Keep a permanent lint or CI search check blocking:
- `rum/reactive`
- `rum/static`
- `rum/local`
- `rum/defcs`
- lifecycle keys in Rum component declarations
- `frontend.mixins`
- `frontend.db-mixins`
## Consequences
- Component side effects become explicit and locally inspectable through hooks.
- Query refresh cleanup must preserve stable component identity, or query state
can leak.
- Subscription hooks need explicit dependency handling to avoid stale renders.
- Editor focus and cursor behavior can regress if layout-sensitive work moves to
normal effects.
- Removing `rum/static` and `:should-update` may change render frequency. Hot
paths need smaller memoized children or measured `React.memo` usage.
- Error boundaries remain a class-component concern and must be represented as
explicit boundary components.
- The refactor has a hard cleanup boundary: `frontend.mixins` and
`frontend.db-mixins` must not remain in the final tree.
- Performance-sensitive paths need before/after evidence when their
memoization, subscription, or render frequency changes.
## Verification
Each migration batch should run the narrowest relevant checks first, then broader
checks for shared behavior:
- focused hook tests for subscription and query cleanup;
- namespace-level unit tests where present;
- smoke compile for frontend and mobile targets;
- manual smoke checks for page load, block edit, slash command, page search,
block search, toggle block, drag block, right sidebar, asset block, query
blocks, PDF, code block rendering, flashcards, and YouTube embeds;
- app E2E tests for affected UI flows must pass. Run `bb test` from
`clj-e2e/`, or `bb -f clj-e2e/bb.edn test` from the repo root;
- CLI E2E tests must pass when a migration batch touches CLI-facing behavior,
command rendering, graph import/export behavior, or shared code used by the
CLI. Run `bb -f cli-e2e/bb.edn test --skip-build` from the repo root after
building when needed;
- render-count or profiling checks for hot paths whose `rum/static`,
`:should-update`, query subscription, or editor/block rendering behavior
changes;
- `bb dev:lint-and-test` before merging broad shared changes.
## Completion Criteria
- No `rum/reactive`, `rum/static`, `rum/local`, `rum/defcs`,
`frontend.mixins`, or `frontend.db-mixins` usage remains in application
component code.
- `src/main/frontend/mixins.cljs` and `src/main/frontend/db_mixins.cljs` are
removed from the repository.
- No Rum lifecycle maps remain in component declarations.
- Query subscriptions mount, refresh, and unmount without leaking entries.
- Editor, block tree, page navigation, right sidebar, properties, query results,
PDF, code, and mobile surfaces pass focused smoke checks.
- No known behavior regressions remain open against the affected UI paths.
- No known performance regressions remain open against the affected hot paths.
- Relevant app E2E tests pass for every affected UI flow.
- CLI E2E tests pass for batches that affect CLI-facing shared behavior.
- `bb dev:lint-and-test` passes.
## Follow-up Work
1. Implement the hook foundation and tests.
2. Add the lint/search guard for new mixin usage.
3. Migrate low-risk leaf components first.
4. Migrate query-scope components outside the editor/block tree.
5. Migrate the editor, block tree, page, header, and container components.
6. Migrate extension integrations.
7. Delete old mixin namespaces and enforce the permanent ban.
8. Capture before/after performance evidence for editor, block tree, page load,
right sidebar, query result, and PDF/code surfaces before declaring the
refactor complete.
+147
View File
@@ -0,0 +1,147 @@
# ADR 0019: Replace Rum With HSX
Date: 2026-06-01
Status: Accepted
## Context
ADR 0018 defined the goal of removing Rum mixins, Rum lifecycle maps, and
`rum/reactive` from Logseq's frontend component tree. During implementation we
also need to replace Rum component definitions themselves, because keeping Rum as
the component runtime leaves old lifecycle behavior, implicit reactivity, and
Rum-specific memoization in the rendering path.
Logseq now targets React 19. The old Rum runtime and the old React UMD asset
layout are a poor fit for that target:
- Rum lifecycle maps and mixins hide effect ordering and cleanup.
- `rum/reactive` depends on Rum's render-time reaction tracking.
- `db-mixins/query` relies on an implicit render scope to know which components
need to refresh after worker DB transactions.
- Rum-style Hiccup allowed several shapes that plain React element creation does
not accept directly.
- React 19 no longer provides the same browser UMD files that existing desktop
packaging expected.
The migration must keep behavior stable for editor input, block trees, right
sidebar rendering, properties, query results, settings, import, plugin surfaces,
PDF/code extensions, and mobile UI. It must also preserve hot-path render
performance that previously depended on Rum `:should-update` and `rum/static`.
## Decision
Replace Rum components with HSX components and use Logseq's fork of HSX as the
frontend component runtime.
All application component definitions should use `hsx/defc` instead of
`rum/defc`, `rum/defcs`, or plain `defn` replacements for component code. The
goal is a mechanical runtime migration with the smallest semantic change:
component names remain callable from ClojureScript, Hiccup remains the view
syntax, and hook-based state/effect/query APIs replace Rum mixins.
The runtime dependency is pinned to `https://github.com/logseq/hsx` from all
Logseq dependency roots that compile UI code. The fork is intentional and should
remain visible until its Logseq-specific compatibility changes are accepted
upstream or no longer needed.
## Query Reactivity
Rum `db-mixins/query`, `rum/reactive`, and `util/react` are replaced by explicit
query hooks.
The new query path is:
1. Build a query atom with `frontend.db.react/q`.
2. Subscribe to it from a component with `frontend.db.hooks/use-query`.
3. Let `use-query` register a stable component token with
`frontend.db.react/add-query-component!`.
4. Let worker DB refresh call `frontend.db.react/refresh!`, recompute affected
query atoms, and request re-render only for registered components.
5. Remove the component token on unmount so unused query cache entries can be
removed.
`use-query` must be called at a stable hook position. Components must not call
`db/sub-block`, `model/sub-block`, or `use-query` inside data-dependent loops,
conditionals, helper functions that run a variable number of times, or render
branches that can appear after the first render. If each list item needs its own
subscription, move that subscription into a keyed child component. If a parent
needs many entities, use one query hook that returns the collection.
This makes query reactivity explicit and keeps React hook order independent of
database result size.
## Logseq HSX Fork
The Logseq HSX fork exists to support the migration without broad application
rewrites. Its compatibility surface differs from upstream HSX in these ways:
- `hsx/defc` supports Logseq component metadata such as `^:private` and
`^:large-vars/*`.
- HSX components can be called as functions from ClojureScript component code,
matching the common Rum call style used throughout Logseq.
- Function-call component invocation preserves React component identity instead
of treating the component result as an arbitrary higher-order component.
- Legacy Hiccup child shapes used by Rum-era code are normalized so nested
vectors of children are treated as children instead of invalid React element
types.
- React keys and Clojure metadata on Hiccup forms are preserved for React list
reconciliation.
- Hook-backed memoization uses Clojure data equality where Logseq depends on it,
avoiding a separate adapter layer for immutable CLJS values.
- React 19 element creation is supported without depending on removed React
internals or old UMD asset paths.
- Known higher-order component values can be marked explicitly with `^:hoc`;
ordinary render-time anonymous functions should not be treated as HOCs.
These differences are compatibility requirements, not a license to preserve Rum
internals in application code. New component code should use direct HSX, React
hooks, and Logseq hook wrappers instead of adding more compatibility behavior to
the fork.
## Hook Rules
The migration follows normal React hook rules:
- Hooks are only called in `hsx/defc` component bodies or custom hooks.
- Hooks are called unconditionally and in the same order on every render.
- Data-dependent subscriptions are moved to keyed child components or combined
into one collection query.
- Render-time getters are used only outside component reactivity or when the
caller intentionally does not need re-rendering.
- Component views that need reactive app state use `state/use-sub`; non-view
helpers use getters.
- Component views that need reactive DB query results use `db.hooks/use-query`.
This replaces the old implicit Rum rule where `rum/reactive` could be introduced
inside helpers and still be attached to the current Rum component.
## Consequences
- Rum mixin namespaces and lifecycle maps can be removed instead of wrapped.
- Query refresh behavior becomes inspectable through
`frontend.db.react/*query-state`, `component->query-key`, and
`query-key->components`.
- Components that previously relied on `rum/static` or `:should-update` need
explicit smaller memoized children, stable keys, or collection-level queries.
- Code that used component functions as plain render helpers can keep doing so
through the Logseq HSX fork, but new code should prefer clear component
boundaries.
- Packaging must bundle React browser globals instead of copying old React UMD
files.
- Runtime compatibility issues should be fixed in HSX only when they represent
valid Logseq Hiccup/component semantics; application bugs should be fixed in
application code.
## Verification
Before merging the migration, verify:
- no `rum/defc`, `rum/defcs`, `rum/reactive`, `rum/static`, `rum/local`,
`frontend.mixins`, or `frontend.db-mixins` usage remains in application UI
code;
- no `db/sub-block`, `model/sub-block`, `state/use-sub`, or `use-query` calls
violate React hook ordering;
- query subscriptions clean up after unmount and refresh affected components
after worker DB transactions;
- block edit, split, merge, undo, redo, sidebar, page graph, properties, scoped
tags, settings, import, code blocks, PDF, plugin UI, and mobile surfaces keep
prior behavior;
- hot block-tree operations do not re-render unrelated sibling blocks;
- React console output has no hook-order, invalid element, invalid nesting, or
missing-key warnings for covered flows;
- `bb dev:lint-and-test` passes;
- app E2E tests pass, excluding only explicitly skipped RTC-related tests when
the test run is configured that way.
+85
View File
@@ -0,0 +1,85 @@
# ADR 0020: Journals UI Stability
Date: 2026-06-02
Status: Accepted
## Context
The journals page renders one virtualized item per journal page. Each item can
contain a full page body, long block trees, embeds, today queries, scheduled and
deadline sections, and linked references.
Chrome verification showed the outer journals Virtuoso height and the main
scroll height changing while scrolling long journals. The same journal item also
changed height repeatedly after it was measured. Three concrete sources were
confirmed:
- `.journal-item` used bottom margin, which is outside the box measured by
ResizeObserver.
- Long journals could render a nested block-level Virtuoso inside the outer
journals Virtuoso, so two virtualizers measured the same scroll surface.
- After a long journal item was unmounted and remounted by the outer
virtualizer, dynamic content such as PDF embeds and linked references could
report a temporarily low height. That made the same measured journal shrink
and grow while scrolling back up.
Linked references must remain visible in journals. The fix cannot hide them or
rely on default collapse as a workaround.
## Decision
Use the journals Virtuoso as the only virtualized measurement owner for journal
items.
Journal item spacing is measured inside the item box. The previous
`pb-[64px] mb-[38px]` visual spacing is represented as `pb-[102px]`, removing
the margin from the measured boundary.
The outer journals Virtuoso uses `skipAnimationFrameInResizeObserver true` so
ResizeObserver updates are applied synchronously with the measurement source.
Block-level virtualization is disabled when rendering page blocks under
`:journals?`. For long journal pages, root blocks are still rendered
progressively so the initial paint remains bounded without nesting another
Virtuoso under the journal item.
Each journal item remembers its last measured height by repo and page id. When
the outer virtualizer remounts that item, the remembered height is used as a
temporary `min-height` reserve while dynamic content settles. The reserve is
released when the inner page content reaches the remembered height, when the
item receives editing input, or after a five-second fallback so real content
shrink can still be measured.
Linked references continue to render normally. Existing view logic already
disables linked-reference view virtualization under `:journals?`; this decision
keeps that behavior and verifies that linked-reference result bodies remain
visible.
## Consequences
The journals page has one scroll measurement owner for journal items, which
removes the feedback loop between nested virtualizers.
Long visible journal pages can eventually render all their visible root blocks,
but they do so progressively. This trades inner virtualization for stable outer
scroll geometry while preserving initial editing responsiveness.
Remounting a long journal no longer lets transiently low dynamic-content height
collapse a previously measured journal item during scroll restoration.
Dynamic sections such as linked references, today queries, scheduled/deadline
sections, embeds, and images can still change the measured journal item height.
Those changes are now handled by the outer journals Virtuoso without competing
with an inner block virtualizer or unmeasured margins.
## Verification
Focused clj-e2e coverage verifies:
- journal items have no bottom margin;
- long journals keep a single `#journals` Virtuoso scroller;
- long journals do not restart from a low measured height after remount;
- linked references remain visible in journals;
- the existing journals scroll-select-copy workflow still works.
Manual Chrome investigation on the affected page shape informed the decision.
+260
View File
@@ -0,0 +1,260 @@
# ADR 0021: RFX-managed Frontend State
Date: 2026-06-03
Status: Accepted
## Context
ADR 0019 replaced Rum with HSX and moved the UI runtime onto React 19. The
frontend now has a React-compatible component runtime, but application state is
still managed by `frontend.state` through a large global atom plus many nested
atoms.
The current state layer has several responsibilities mixed together:
- `frontend.state/state` stores the main application map.
- Many values inside that map are themselves atoms, for example editor,
selection, RTC, PDF, command palette, scroll, and other high-churn UI refs.
- `frontend.state/use-sub` provides React subscriptions by wrapping the global
atom or a nested atom with `logseq.shui.hooks/use-atom`.
- `frontend.state/get-state`, `set-state!`, and `update-state!` are used across
handlers, components, workers, plugins, mobile code, and Electron integration.
- `frontend.state/pub-event!` publishes vectors to a `core.async` channel stored
at `:system/events`.
- `frontend.handler.events` consumes that channel and routes events through a
`defmulti`.
- Worker DB queries and component subscriptions use a separate reactive layer in
`frontend.db.react` and `frontend.db.hooks`.
- Several subsystems use Missionary flows or direct atom watches for runtime
state that is not just component state.
This makes UI reactivity explicit enough for React hooks, but the ownership is
still split between path cursors, nested atoms, a global event channel, and a
large set of imperative helpers. A code scan showed the size of the migration
surface:
- about 178 `state/use-sub` call sites under `src/main/frontend`;
- about 310 `set-state!` or `update-state!` call sites under
`src/main/frontend`;
- about 190 `pub-event!` call sites under `src/main/frontend`;
- about 102 `frontend.handler.events/handle` methods.
RFX is a better fit for the next step because it keeps the re-frame style
architecture while using React Context and hooks instead of Reagent. It provides
scoped app instances, `use-sub`, `dispatch`, `reg-sub`, `reg-event-db`,
`reg-event-fx`, effects, coeffects, snapshots, and a queue. Logseq has already
forked RFX and added root `deps.edn` support on `logseq/rfx` branch
`logseq/fork`, commit `d37aaceb37fcaf969c5cd04646dfdb985d65d3c2`.
The migration must not destabilize editor input, block trees, DB worker
transactions, RTC, plugin APIs, Electron IPC, mobile native flows, or
DataScript query subscriptions.
## Decision
Adopt RFX as the frontend application state and event runtime.
Add RFX to the main frontend dependency root from the Logseq fork:
```clojure
io.github.logseq/rfx
{:git/url "https://github.com/logseq/rfx.git"
:git/sha "d37aaceb37fcaf969c5cd04646dfdb985d65d3c2"}
```
Create a Logseq-owned RFX context, store, and registry. The context should be
provided near the root render in `frontend.core`, around `page/current-page`.
The RFX instance must be initialized during frontend startup before event
handling starts.
Replace `frontend.state` as the state owner in one coordinated migration.
Existing non-hook public entry points may remain as thin call-through APIs only
when they preserve caller compatibility without keeping state outside RFX:
- `get-state`
- `set-state!`
- `update-state!`
- `pub-event!`
- focused helpers such as `get-current-repo`, `set-current-repo!`,
`get-config`, editor helpers, selection helpers, and RTC helpers
Replace all `frontend.state/use-sub` and focused hook call sites with
`rfx/use-sub` or Logseq-owned domain hooks backed by RFX subscriptions. Do not
keep `frontend.state/use-sub` as a compatibility wrapper. `get-state`,
`set-state!`, `update-state!`, and focused non-hook helpers should read
snapshots or dispatch RFX events instead of mutating the old global atom.
Use one source of truth:
- Frontend application state is plain data in the RFX app db and is updated
through RFX events.
- Nested atoms must not remain as the representation for application state.
Convert nested atom state to plain values and path updates during the
migration.
- Missionary flows and direct atom watches must not remain as state propagation
paths for frontend application state. Replace them with RFX subscriptions,
events, effects, and coeffects.
- Imperative resources such as DOM nodes, editor handles, timers, external
worker objects, Electron handles, and plugin runtime handles stay outside the
RFX app db. They may be held in refs only when they are not renderable
application state and do not drive UI subscriptions directly.
Migrate every frontend state domain and its event handlers in the same change.
Do not land partial domain migrations. State-only migrations that still rely on
`frontend.handler.events/handle` for writes are rejected, and event-only
migrations whose render state still lives behind legacy path cursors are also
rejected.
`pub-event!` may remain as the public promise-returning compatibility API for
callers, but it should dispatch into RFX instead of writing to `:system/events`.
It must route to explicit `rfx/reg-event-db` or `rfx/reg-event-fx`
registrations and resolve or reject the deferred promise from the RFX event
result. Do not keep a bridge that invokes the existing
`frontend.handler.events/handle` multimethod.
Use RFX to replace flow-based frontend state propagation. DataScript execution
and worker-owned invalidation can remain worker responsibilities, but
UI-facing query result state and refresh orchestration should be exposed through
RFX subscriptions and events instead of Missionary flows or atom watches.
## Migration Shape
The migration should be one coordinated replacement of the frontend state and
event runtime.
1. Add the RFX dependency and create a small `frontend.rfx` namespace that owns
the app context, registry, initialization, dispatch helpers, and root
provider.
2. Move the initial plain app state map construction out of the `defonce state`
expression into a reusable function.
3. Move all frontend application state domains to plain RFX app-db values,
including route state, graph/current repo state, search, modals, sidebars,
theme flags, auth tokens, import/loading state, editor state, selection,
command palette, PDF, RTC UI state, plugin UI state, Electron UI state, and
mobile UI state.
4. Replace all `frontend.handler.events/handle` methods with explicit
`rfx/reg-event-db` or `rfx/reg-event-fx` registrations. Keep event ids
domain-scoped and register effects/coeffects for DB worker calls, RTC,
plugins, Electron IPC, mobile native calls, and async error capture.
5. Replace `:system/events` with RFX dispatch behind `pub-event!` and remove the
`core.async` event channel.
6. Replace Missionary flows and direct atom watches that propagate frontend
application state with RFX subscriptions, events, effects, and coeffects.
7. Replace all `frontend.state/use-sub` and focused state hook call sites with
`rfx/use-sub` or domain hooks backed by `rfx/reg-sub`.
8. Remove nested atoms, path cursors, and legacy hook paths for application
state. Keep refs only for imperative resources that do not represent
renderable state.
9. Update tests in the same change so every moved domain has coverage for state
reads, event-driven writes, async effects, and promise resolution.
Each domain should have a clear owner namespace, subscription ids, event ids,
effects, coeffects, and test coverage.
## Consequences
State ownership becomes explicit. Components subscribe through React-safe RFX
hooks, while non-view code can use RFX snapshots and dispatch against the same
instance.
Tests and isolated UI surfaces can create scoped RFX contexts instead of
mutating the global `frontend.state/state` atom. This matches the context model
introduced by the HSX migration.
The event system gains a uniform event/effect/coeffect shape and immediately
replaces the `core.async` channel plus `defmulti` dispatch path.
The migration cannot be a mechanical atom swap. Nested atom mutation does not
automatically notify RFX subscriptions. State must move to plain values, and
writes must move to RFX events.
Compatibility wrappers may remain only as public API aliases that call into RFX.
They must not retain separate storage, separate event dispatch, Missionary flow
state propagation, or direct atom-watch state propagation.
RFX effects that run async work must preserve existing error reporting behavior,
including `:capture-error` and promise rejection paths used by callers of
`pub-event!`.
## Rejected Alternatives
### Keep `frontend.state` As-is
This avoids migration cost but leaves Logseq with a custom subscription system
after the React 19 and HSX migration. It also keeps event routing separate from
state updates and does not give isolated RFX contexts for tests or component
development.
### Replace Only `pub-event!`
Moving events to RFX while leaving render state on path cursors would improve
event structure, but components would still subscribe through the custom atom
layer. It would not solve the state ownership problem.
### Migrate Domain-by-Domain
An incremental domain migration would leave two state and event runtimes active
for too long. That would preserve the current split ownership across RFX,
legacy path cursors, Missionary flows, atom watches, the `core.async` event
channel, and `defmulti` handlers. The migration should replace all frontend
application state domains and handlers together.
### Migrate State Without Event Handlers
Moving state keys to RFX while keeping their writes in
`frontend.handler.events/handle` would preserve the current split ownership in a
new form. RFX-managed state must be written through RFX events, so state and
event handlers should move together.
### Keep `frontend.state/use-sub` As A Wrapper
Keeping `frontend.state/use-sub` as a compatibility hook would preserve the old
subscription boundary and make it harder to see which code is using RFX
subscriptions directly. All hook call sites should move to `rfx/use-sub` or
domain hooks backed by RFX.
### Keep Missionary Flows For Frontend State
Keeping Missionary flows or atom watches as frontend state propagation would
leave RFX as only a partial store. Worker internals can still use their own
runtime mechanisms, but UI-facing state should be expressed through RFX
subscriptions and events.
### Keep DataScript Query Reactivity Outside RFX
Keeping `frontend.db.react` and `frontend.db.hooks/use-query` as a separate
UI-facing subscription layer would leave another flow-like state runtime beside
RFX. Query execution and worker invalidation may stay in the DB worker, but the
frontend-facing subscription and refresh contract should be mediated through
RFX.
## Verification
Before accepting the migration, verify:
- root rendering is wrapped in the Logseq RFX context;
- no `frontend.state/use-sub` call sites remain;
- direct `rfx/use-sub` and domain hook call sites obey React hook ordering;
- RFX-managed keys re-render components after `set-state!`, `update-state!`,
and event handlers update them;
- all frontend application state domains update through RFX events, with no
remaining legacy `defmethod handle` write path;
- no Missionary flow or direct atom watch remains as a frontend application
state propagation path;
- non-managed refs are limited to imperative resources and do not drive UI
subscriptions directly;
- `pub-event!` still returns a promise that resolves or rejects with the event
result;
- event errors are logged and reported through the existing capture path;
- graph switching, route changes, theme toggles, sidebars, modals, settings,
search, import progress, login state, plugin UI, Electron IPC, mobile tabs,
RTC indicator, editor editing, and block selection keep prior behavior;
- UI-facing DB query result subscriptions and refresh orchestration go through
RFX, while worker-owned query execution and invalidation keep prior behavior;
- no React hook-order warnings, invalid element warnings, or missed subscription
updates appear in Chrome;
- focused unit tests cover every state domain, event registration, effect,
coeffect, non-hook compatibility wrapper, and replaced flow path;
- `bb dev:lint-and-test` passes;
- relevant app or CLI E2E tests pass for graph switch, editor input, selection,
sidebar, settings, plugin, and sync surfaces touched by the migrated keys.
@@ -0,0 +1,117 @@
# ADR 0022: Remove the UI DataScript DB and Refactor Editor First
Date: 2026-07-08
Status: Accepted
## Context
The db worker is the durable owner of graph data, but the renderer has still
kept a second DataScript connection as a UI read model. That split makes graph
reads harder to reason about because UI code can read stale renderer entities,
perform reverse lookups locally, or depend on lazy entity navigation that does
not exist when the worker database is the only graph database.
The renderer has used this UI DB through several shapes:
- direct `d/entity`, `d/pull`, `d/q`, `db/entity`, `db/pull`, and
`db-model/*` calls;
- reverse lookup attributes such as `:block/_alias` and `:block/_refs`;
- nested entity or pull-map reads such as reading fields from
`(:block/parent block)`;
- handler code that performs graph-backed editor calculations before
dispatching worker transactions.
The editor is the highest-risk migration surface because it combines block
tree reads, sibling and parent selection, paste, delete, merge, quick-add,
navigation, undo metadata, DOM focus, and outliner transactions. Removing the
UI DB without simplifying editor ownership would preserve the same complexity
behind async worker calls.
## Decision
Remove the renderer-owned DataScript database as a graph read model.
The db worker is the only owner of graph facts. UI code must not depend on
DataScript entities, lazy entity navigation, reverse lookup attributes, or
renderer-side pull maps for graph computation.
Refactor editor ownership first:
1. Move graph-backed editor calculations to worker APIs.
2. Add worker editor namespaces where editor-specific graph operations need a
clear home.
3. Keep UI editor handlers thin: they dispatch user intent, coordinate DOM and
focus state, and consume explicit worker payloads.
4. Return plain data from worker APIs with explicit fields needed by the UI.
Do not rely on entity identity, lazy nested refs, or reverse attributes.
5. Keep components focused on rendering and event dispatch. Component
migration comes after handler/editor contracts are explicit.
Do not add a renderer cache to replace the UI DB. If a cache becomes necessary,
it must have a narrowly documented owner, invalidation rule, and test case.
The default design is no cache.
Do not keep a compatibility layer that lets UI code continue to call
renderer-style DB helpers. Compatibility wrappers may remain only while their
call sites are being removed, and they must not hide a second graph database.
## Migration Shape
1. Add guard tests that count and reject direct UI DB reads, reverse lookups,
and nested entity or pull-map assumptions in frontend UI code.
2. Remove direct `d/entity`, `d/pull`, `d/q`, `db/entity`, `db/pull`,
`db-model/*`, and renderer `conn/get-db` reads from handlers and events.
3. Move editor calculations to worker APIs before converting component-heavy
surfaces.
4. Replace reverse lookup usage with worker-owned queries that return explicit
result fields.
5. Replace nested entity reads with explicit worker payloads, for example
parent ids, page ids, children, aliases, refs, or sibling blocks.
6. Keep outliner writes on worker-backed transaction paths and keep UI code
out of DB transaction assembly when the worker can own the calculation.
7. Convert components last so they render worker-shaped data and dispatch UI
events without graph reads.
8. Run focused tests after each migration batch, then run the broader test and
e2e suites when the UI DB removal is complete.
## Consequences
UI code becomes more explicit. It must ask the worker for the graph data or
editor decision it needs instead of navigating a local entity graph.
Worker APIs increase during the migration, especially around editor behavior.
That is intentional when the API represents a real graph-backed editor
operation. APIs should stay narrow and return plain data.
Editor behavior needs stronger focused coverage because many previously local
reads become async worker calls. Tests should cover insert, delete, merge,
paste, quick-add, sibling navigation, focused-root behavior, and reverse lookup
replacement paths.
Component migration is delayed until handler and editor worker contracts are
stable. This keeps rendering code simpler and avoids moving complex graph
calculation into components.
The removal may temporarily leave old helper namespaces in place while call
sites are drained, but the target architecture has no renderer-owned graph DB.
## Rejected Alternatives
### Keep a Renderer Read Cache
A renderer cache would preserve much of the old split-brain behavior and would
need invalidation logic for every worker transaction, sync update, import,
undo, redo, and rebase path. That adds complexity without solving ownership.
### Convert Components Before Editor
Component-first migration would move the easiest render reads first while
leaving the most complex graph-backed behavior in handlers. Editor behavior
would continue to depend on old assumptions, and later changes would force a
second pass through component contracts.
### Preserve Entity-shaped Worker Results
Returning entity-like maps with nested refs would keep the renderer coupled to
DataScript navigation semantics. Explicit worker payloads are easier to test,
serialize, and reason about across thread boundaries.
@@ -0,0 +1,134 @@
# Remove Legacy CLJS CLI
## Problem
Logseq has one shipped CLI implementation under `cli/`, built from OCaml with
Dune, Melange, and Vite, but it still retains most of the superseded Shadow
ClojureScript implementation under `src/main/logseq/cli/` and its tests under
`src/test/logseq/cli/`.
The release migration deliberately removed the `:logseq-cli` Shadow build and
made `cli/_build/default/dist/logseq-cli.js` the only producer of the staged
`static/logseq-cli.js` artifact. `package.json`, CLI E2E preflight, npm package
preparation, and Desktop runtime staging all use that OCaml/Melange artifact.
`scripts/test-cli-release-config.mjs` rejects any active Shadow CLI build path.
The remaining legacy command tree has no production entry point. Repository-wide
namespace searches find no production consumer outside its own implementation.
It contains 31 production files and about 14,800 lines, while 26 dedicated test
files add about 16,800 more lines. Keeping this parallel implementation makes
search results, tests, and maintenance work describe a binary that users cannot
build or run.
Not every namespace under `src/main/logseq/cli/` is obsolete. Electron,
db-worker-node, and worker handlers still import shared daemon and transport
helpers. Those imports are part of the active runtime and must remain.
## Proposal
Delete only the legacy CLJS CLI closure that is unreachable from active
production builds:
- `src/main/logseq/cli/command/`;
- `src/main/logseq/cli/auth.cljs`;
- `src/main/logseq/cli/commands.cljs`;
- `src/main/logseq/cli/completion_generator.cljs`;
- `src/main/logseq/cli/config.cljs`;
- `src/main/logseq/cli/format.cljs`;
- `src/main/logseq/cli/humanize.cljs`;
- `src/main/logseq/cli/main.cljs`;
- `src/main/logseq/cli/output_mode.cljs`;
- `src/main/logseq/cli/tree_text.cljs`; and
- `src/main/logseq/cli/uuid_refs.cljs`.
Delete their implementation-specific CLJS tests:
- `src/test/logseq/cli/command/`;
- `src/test/logseq/cli/auth_test.cljs`;
- `src/test/logseq/cli/commands_test.cljs`;
- `src/test/logseq/cli/completion_generator_test.cljs`;
- `src/test/logseq/cli/config_test.cljs`;
- `src/test/logseq/cli/format_test.cljs`;
- `src/test/logseq/cli/main_test.cljs`;
- `src/test/logseq/cli/output_mode_test.cljs`; and
- `src/test/logseq/cli/uuid_refs_test.cljs`.
Retain the active CLJS runtime boundary and its tests:
- `logseq.cli.common` and `logseq.cli.common.db-worker`, used by Electron and
worker handlers;
- `logseq.cli.root-dir`, used by db-worker-node and worker logging;
- `logseq.cli.server`, used by Electron runtime management;
- `logseq.cli.transport`, used by Electron database access;
- `logseq.cli.style`, used by db-worker-node;
- `logseq.cli.log` and `logseq.cli.profile`, used transitively by the active
server and transport helpers; and
- `logseq.cli.test-helper`, which is also consumed by db-worker-node tests.
Keep the shared helpers in their existing namespace for this decision. Moving
them to a neutral namespace would add unrelated churn without reducing the
duplicate CLI implementation.
Update `docs/cli/logseq-cli.md` so its query example points to the shipped OCaml
implementation in `cli/lib/query.ml` instead of `logseq.cli.command.query`.
Preserve `static/logseq-cli.js` as a generated artifact of the existing
OCaml/Melange staging flow; it is not part of the source deletion.
## Alternatives considered
### Retain the CLJS implementation as a reference
Rejected because the OCaml implementation, its unit/parity tests, CLI E2E
manifests, and the public command reference already own shipped behavior. A
second non-buildable implementation is a stale source of truth rather than an
executable reference.
### Delete every `logseq.cli` namespace
Rejected because Electron, db-worker-node, and worker production code still
consume the daemon, root-directory, transport, formatting, and shared database
helpers listed in the proposal.
### Move the retained helpers before deleting the command tree
Rejected for this decision because namespace relocation changes many active
runtime imports but is not required to remove the parallel CLI. It can be
considered separately if the `logseq.cli` name remains confusing after the
obsolete implementation is gone.
## Acceptance criteria
- The 31 unreachable CLJS source files and 26 implementation-specific test
files listed by the proposal are removed.
- The eight active CLJS production namespaces and their focused tests remain,
and repository-wide namespace search still accounts for every Electron,
db-worker-node, worker, and test-helper consumer.
- `shadow-cljs.edn`, root build scripts, CLI E2E preflight, npm package
preparation, and Desktop staging continue to identify
`cli/_build/default/dist/logseq-cli.js` as the sole CLI producer.
- `docs/cli/logseq-cli.md` no longer points readers to a deleted CLJS command
namespace.
- `node scripts/test-cli-release-config.mjs` passes.
- `pnpm --dir cli test` passes.
- `bb -f cli-e2e/bb.edn test --skip-build` passes against freshly staged CLI
and db-worker-node artifacts.
- Focused CLJS tests for `logseq.cli.common`, `logseq.cli.common.db-worker`,
`logseq.cli.log`, `logseq.cli.profile`, `logseq.cli.root-dir`,
`logseq.cli.server`, `logseq.cli.style`, and `logseq.cli.transport` pass.
- `bb dev:lint-and-test` passes.
## Risks
- A developer may have used the old CLJS namespaces manually even though they
have no build, package, or documented public entry point. This decision
intentionally gives up that unsupported workflow.
- Removing duplicate CLJS tests reduces coverage of the deleted implementation.
Shipped CLI behavior remains covered by `cli/test/` and `cli-e2e/`; active
shared CLJS runtime tests remain in place.
- The retained helpers continue to use the `logseq.cli` namespace, so the name
will describe runtime infrastructure as well as the historical location of
the removed CLI. Renaming them is outside this simplification.
## Questions
- None.
@@ -0,0 +1,88 @@
# Remove Unused db-sync Cycle Repair
## Problem
`deps/db-sync/src/logseq/db_sync/cycle.cljs` implements approximately 370 lines
of client-side DataScript repair for `:block/parent` and
`:logseq.property.class/extends` cycles. Its approximately 220-line unit test
namespace is the only current consumer.
The client remote-apply path stopped requiring and calling `fix-cycle!` in
commit `905e131770` (`fix: no need to fix parent cycle for blocks`) on
2026-03-20. Current `frontend.worker.sync.apply-txs` repairs duplicate outliner
orders but has no cycle-repair call. Repository-wide searches find no other
production, script, documentation-contract, reflection, registry, or generated
source reference. The `@logseq/db-sync` package is private and does not export
the namespace as an external API.
The unused utility therefore preserves a behavior model, transaction metadata,
and tests that are not part of runtime behavior. The implemented runtime guide
must also carry a special warning explaining that the utility is not integrated.
## Proposal
Delete:
- `deps/db-sync/src/logseq/db_sync/cycle.cljs`; and
- `deps/db-sync/test/logseq/db_sync/cycle_test.cljs`.
Remove the `Cycle repair utility` subsection from
`docs/agent-guide/implemented/architecture/2026-08-24-logseq-runtime-and-engineering-guide.md`.
The runtime guide should continue to describe the active duplicate-order repair
where relevant, without documenting a removed test-only implementation.
Do not change `frontend.worker.sync.apply-txs`, transaction application order,
outliner semantics, or server-side validation. Generated
`deps/db-sync/worker/dist/worker-test.js` is excluded from source edits and will
be regenerated by the db-sync test build.
## Alternatives considered
### Reconnect `fix-cycle!` to remote apply
Rejected as a simplification because it would add cycle-repair transactions and
change synchronized graph behavior. If runtime evidence shows cycle repair is
needed, that work belongs to a separate bugfix or architecture decision with
new behavior tests.
### Keep the utility as a test-only design reference
Rejected because version control already preserves its history, while the
current source and test suite should describe executable behavior. Keeping it
also forces the runtime guide to distinguish implemented code from the active
path.
### Extract a generic graph-cycle library
Rejected because there is no second production consumer and the extraction
would relocate unused complexity instead of deleting it.
## Acceptance criteria
- The cycle repair source and its self-contained unit test namespace are
removed.
- Repository-wide search finds no `logseq.db-sync.cycle`, `cycle/fix-cycle!`, or
equivalent build/test registration reference in tracked source.
- `frontend.worker.sync.apply-txs` retains its current remote apply and
duplicate-order repair behavior unchanged.
- The implemented runtime guide no longer documents the removed test-only
utility or suggests that active client sync repairs reference cycles.
- `pnpm --dir deps/db-sync test` passes and regenerates its test bundle without
the deleted namespace.
- `bb lint:carve` passes.
- `bb dev:lint-and-test` passes.
## Risks
- The deleted implementation includes algorithms for two kinds of cycles, so a
future runtime bugfix cannot reuse it directly from the working tree. Its Git
history and focused tests remain recoverable from commits before this
decision.
- The removal assumes that the March 2026 production-path deletion was
intentional for both supported attributes. Reintroducing any client-side
repair would be behavior-changing and requires a new decision rather than a
reversal hidden inside this simplification.
## Questions
- None.
@@ -0,0 +1,872 @@
# Logseq Runtime and Engineering Guide
Status: implemented
This is a compact, source-verified engineering guide for the runtime areas that
were previously documented across docs/agent-guide. It was checked against the
repository on 2026-08-24.
The guide explains durable architecture, data flow, invariants, failure behavior,
and verification entry points. It intentionally omits implementation schedules,
branch instructions, temporary measurements, review snapshots, and product
research. Source code, tests, generated OpenAPI, and active subsystem
documentation remain the detailed contracts behind this guide.
## Problem
Engineering knowledge about the CLI, db-worker-node, db-sync, rendering,
outliner performance, search, and Graph View was distributed across plans and
reports. The useful content was mixed with proposed work, obsolete paths, and
time-sensitive observations. Engineers need one short technical map that
preserves the valid constraints without treating historical plans as current
contracts.
## Decision
### System model
Logseq uses different runtime processes. Within one local runtime, the worker
database is authoritative for graph state. On Desktop, a graph has at most one
active local writer daemon; remote db-sync storage is a synchronized copy, not a
second local writer.
| Runtime | Main responsibility | Persistent database |
| --- | --- | --- |
| Browser renderer | UI, editor state, worker client | None directly |
| Browser db-worker | Graph transactions and queries | SQLite through OPFS |
| Desktop renderer | UI and remote persistence client | None directly |
| Electron main | Window and db-worker-node lifecycle | Filesystem coordination |
| db-worker-node | Graph transactions, queries, sync, search | Filesystem SQLite |
| CLI | Command parsing, orchestration, formatting | Uses db-worker-node |
| db-sync Worker/DO | Remote graph access and ordered synchronization | D1/DO SQLite and R2 |
Important ownership rules:
- The worker database is authoritative for graph state.
- Desktop and CLI use the same graph directory, lock protocol, and
db-worker-node runtime.
- The renderer must not create a second optimistic graph authority.
- Disk SQLite is the Desktop source of truth. OPFS export is not the Desktop
primary persistence path.
- A graph must not have two active writer daemons.
Primary source map:
| Area | Source |
| --- | --- |
| Worker database and thread APIs | src/main/frontend/worker/ |
| Browser persistence | src/main/frontend/persist_db/browser.cljs |
| Desktop remote persistence | src/main/frontend/persist_db/remote.cljs |
| Electron runtime manager | src/electron/electron/db_worker.cljs |
| Shared daemon lifecycle | src/main/logseq/cli/server.cljs |
| Node daemon | src/main/frontend/worker/db_worker_node.cljs |
| CLI | cli/ |
| db-sync server | deps/db-sync/src/logseq/db_sync/worker/ |
| Renderer DB subscriptions | src/main/frontend/db/ |
### Worker platform boundary
frontend.worker.platform is the worker capability boundary. The required adapter
sections are:
- env
- storage
- kv
- broadcast
- websocket
- crypto
- timers
- sqlite
Vector and embedding capabilities are present when the runtime supports semantic
search.
The browser adapter uses OPFS, browser storage, browser WebSocket, and the worker
postMessage channel. The Node adapter uses filesystem paths, Node WebSocket,
Node crypto/storage primitives, and node:sqlite DatabaseSync.
Business namespaces should depend on frontend.worker.platform instead of testing
the host runtime repeatedly. Missing required capabilities fail during platform
validation. Optional capabilities may be absent only where the feature itself is
optional.
Interactive requests use frontend.worker.ui-request:
1. The worker creates a unique request id.
2. The host receives a typed request and payload.
3. The host resolves or rejects that exact request.
4. Cancellation rejects outstanding requests during graph/runtime shutdown.
Browser flows may request UI input. Headless Node flows must use explicit input
or return a useful error. New worker business logic should not call renderer
functions directly. One non-Node search progress path still uses
frontend.worker.state/<invoke-main-thread; do not treat that exception as a
general worker API.
### db-worker-node daemon
db-worker-node is a graph-bound localhost daemon. It starts the same worker core
used by the browser, installs the Node platform adapter, opens the requested
repo, writes graph and server-list metadata, and becomes ready only after worker
initialization succeeds.
Client-facing endpoints:
| Method | Path | Purpose |
| --- | --- | --- |
| GET | /healthz | Readiness, bound repo, process, owner, revision, host, and port |
| GET | /v1/events | Server-Sent Events from worker broadcasts |
| POST | /v1/import-db-binary?repo=... | Stream a SQLite database import |
| POST | /v1/invoke | Invoke a worker thread API with Transit arguments |
| POST | /v1/shutdown | Graceful close and process shutdown |
The daemon also answers CORS preflight requests. It binds to `127.0.0.1` on an
OS-selected port and has no remote-bind option.
Most thread APIs require the first argument to identify the repo. The daemon
rejects:
- a missing or blank repo with HTTP 400;
- a repo that differs from the daemon's bound repo with HTTP 409.
Only explicitly listed process-level APIs may omit the repo. This binding keeps a
client from accidentally sending graph work to another daemon discovered from
stale metadata.
#### Graph lock and ownership
The three discovery records have deliberately different scopes:
- `db-worker.lock` records `repo`, `pid`, `lock-id`, and `owner-source`.
- `server-list` records only `pid` and `port` pairs.
- `/healthz` reports `repo`, readiness status, host, port, pid, owner source,
root directory, and runtime revision.
Neither the graph lock nor `server-list` is a readiness or revision authority.
Lifecycle behavior:
1. Resolve and validate the graph directory under the configured root.
2. Read the graph lock and remove it only when its owner process is absent.
3. Read `server-list`, discard entries whose pid is absent, and probe remaining
entries through `/healthz`.
4. Spawn only when neither a discovered graph server nor a graph lock exists.
5. Require both a graph lock and a discovered server, then wait for readiness.
6. Reuse the daemon only when its reported revision matches the requester.
7. On revision mismatch, stop that exact server, start once, and verify the new
revision; fail if stop, startup, or the second revision check fails.
A discovered process without the expected usable lock is not adopted as a valid
runtime; startup fails instead of returning an unowned endpoint.
Normal stop and restart operations respect owner boundaries. A proven revision
mismatch may replace the exact stale daemon across owner sources because the
requester cannot safely use it. Manual CLI cleanup remains limited to eligible
CLI-owned daemons.
#### Server list
root-dir/server-list is a discovery index of pid/port pairs. Mutations are
serialized through root-dir/server-list.lock.
The write protocol:
1. Create the lock with exclusive wx semantics.
2. Write lock owner metadata including pid, lock id, and timestamp.
3. Recover the lock only when its owner process is proven absent.
4. Read and normalize current entries while holding the lock.
5. Write a uniquely named temporary file.
6. Rename the temporary file over server-list atomically.
7. Remove the lock only when its lock id still matches.
Readers tolerate missing files and ignore malformed or duplicate entries. They
must still verify each entry through /healthz.
#### Electron graph switching and recovery
Electron owns graph-scoped runtimes in electron.db-worker. A window may bind to
one graph while another window keeps another graph runtime alive.
setCurrentGraph is metadata synchronization for the window graph path. It does
not release a worker. Runtime start/switch is handled by db-worker-runtime IPC,
and release is handled by explicit lifecycle or window close. Releasing from
setCurrentGraph can stop the newly selected runtime after a switch.
The renderer remote persistence client treats server-unavailable errors as a
runtime recovery signal. The current recovery threshold is one failed request.
Recovery is graph-scoped and must not silently switch the user to another graph.
The SSE client reconnects after 1000 ms by default and keeps scheduling another
attempt while the client remains connected; `disconnect!` stops that loop.
Request recovery is different: the first server-unavailable failure triggers at
most one recovery for the active runtime session. Session and repo checks stop a
stale recovery result from replacing the currently selected graph runtime.
#### Graph backups
Desktop and CLI share the graph backup layout:
~~~text
<root-dir>/graphs/<encoded-graph>/backup/<encoded-backup-name>/
db.sqlite
metadata.edn
~~~
Backup policy:
- Snapshot through SQLite backup APIs; do not copy a live database with a plain
filesystem copy.
- Include db.sqlite only.
- Exclude WAL/SHM sidecars, search-db.sqlite, and client-ops-db.sqlite.
- Reserve the destination directory atomically.
- Add a numeric suffix when a generated backup name already exists.
- Write metadata only after the database snapshot succeeds.
- Remove an incomplete reserved directory on failure.
- Resolve shared-helper backup paths as children of the graph backup root.
metadata.edn records schema version, name, repo, source, creation time, and
database path. Retention is source-specific so automatic pruning cannot delete
manual backups.
Electron runs automatic backups hourly for active graph windows, throttles the
same source, and retains 12 automatic versions. Manual Desktop and CLI backups
are not subject to that automatic retention policy.
The shared ClojureScript helper validates path containment. The current OCaml
CLI `backup restore --src` and `backup remove --src` paths only trim the supplied
name and concatenate it below the backup root; they do not reuse that containment
validator. Do not treat those two `--src` arguments as safe for untrusted input.
Markdown mirror output keeps page-level identity but does not emit block
database ids as HTML comments.
### db-sync architecture
db-sync separates four concerns:
- index-level graph, membership, access, and E2EE operations;
- graph-scoped ordered sync in a Durable Object;
- semantic REST operations for external clients;
- asset storage and signed download access through R2.
Key files:
| Concern | Source |
| --- | --- |
| Entry and dispatch | deps/db-sync/src/logseq/db_sync/worker/dispatch.cljs |
| Sync route registry | deps/db-sync/src/logseq/db_sync/worker/routes/sync.cljs |
| Semantic route registry/OpenAPI | deps/db-sync/src/logseq/db_sync/worker/routes/semantic.cljs |
| WebSocket protocol codec | deps/db-sync/src/logseq/db_sync/protocol.cljs |
| Sync handlers | deps/db-sync/src/logseq/db_sync/worker/handler/sync.cljs |
| Semantic handlers | deps/db-sync/src/logseq/db_sync/worker/handler/semantic.cljs |
| Storage | deps/db-sync/src/logseq/db_sync/storage.cljs |
| Client sync | src/main/frontend/worker/sync/ |
| MCP and ChatGPT entry | deps/db-sync/worker/entry.mjs |
Graph-scoped sync requests use /sync/<graph-id>/... and are forwarded to the
corresponding Durable Object.
#### Sync HTTP routes
The graph-scoped route registry contains:
| Method | Internal path | Purpose |
| --- | --- | --- |
| GET | /health | Graph sync readiness |
| GET | /pull | Transactions after a server t |
| GET | /checksum/diagnostics | Incremental and recomputed checksum details |
| GET | /snapshot/download | Snapshot download |
| GET | /snapshot/stream | Framed snapshot stream |
| DELETE | /admin/reset | Administrative graph reset |
| POST | /tx/batch | Ordered transaction batch |
| POST | /snapshot/upload | Streaming snapshot upload |
Use the route registry for the exact method/path contract. Public dispatch adds
graph id, authentication, access checks, and Durable Object forwarding.
#### WebSocket protocol
Messages are JSON maps. Transaction payloads inside the maps are Transit
encoded. UUIDs are serialized as strings.
Client messages:
| type | Important fields | Result |
| --- | --- | --- |
| hello | none | hello with current t and optional checksum |
| ping | none | pong |
| presence | editing-block-uuid | broadcast presence update |
| pull | since | pull/ok with t, txs, and optional checksum |
| tx/batch | t-before, txs, optional client-revision | tx/batch/ok or tx/reject |
The server also broadcasts online-users, presence, and changed notifications.
Malformed JSON, invalid since values, and unknown types return an error message.
Transaction batches use optimistic ordering:
- t-before must be a non-negative number.
- t-before must equal the server's current t.
- snapshot upload must be complete before normal transactions apply.
- a successful logical batch advances t and returns tx/batch/ok.
- a stale request returns tx/reject with the current t.
- a partial failure reports the new t plus successful and failed transaction
identifiers when available.
- peers receive one changed notification after the batch and checksum settle.
Clients must pull/rebase after stale rejection instead of retrying the same batch
blindly.
#### Semantic REST and MCP
The semantic API lives under /api/v1 and exposes operations for:
- graph discovery;
- pages and page references;
- blocks, recursive trees, and block moves;
- typed properties and batch property updates;
- journal capture;
- Task objects;
- tags and tagged objects;
- assets;
- graph search.
The semantic layer uses Logseq outliner and property semantics. It must not
implement mutations as arbitrary raw DataScript transactions.
Security and data rules:
- Every operation declares logseq/read or logseq/write OAuth scope.
- Graph access is checked before dispatch into the graph Durable Object.
- E2EE graphs fail closed because the server cannot interpret their content.
- Rate limiting happens before expensive Durable Object work.
- Property mutations use typed DB graph properties, not file-graph key:: text.
- Task creation uses the Task class and typed status/priority/date properties,
not Markdown TODO syntax.
- Asset uploads are limited to 100 MB and require an exact size plus SHA-256
checksum.
- The generated /openapi.json is the detailed external contract.
MCP is a thin integration over the semantic API. entry.mjs owns request wiring,
chatgpt_app.mjs owns app metadata, and chatgpt_asset_upload.mjs adapts asset
uploads. Do not create a second independent mutation API for MCP tools.
#### Authentication and E2EE state
Worker auth belongs in frontend.worker.state/*state under namespaced keys:
- :auth/id-token
- :auth/access-token
- :auth/refresh-token
- :auth/oauth-token-url
- :auth/oauth-domain
- :auth/oauth-client-id
frontend.worker.state/*db-sync-config contains transport configuration such as
:ws-url and :http-base. non-auth-db-sync-config strips auth-shaped keys before
storing transport config.
E2EE password rules:
- Never store plaintext passwords in cli.edn or db-sync config.
- Verify a supplied password against the encrypted private key before saving it.
- Do not overwrite a valid stored payload after a failed verification.
- Encrypt the persisted password with material derived from the refresh token.
- Browser storage uses the platform secret store.
- The Node platform prefers the OS keychain under the Logseq E2EE service.
- If keychain access fails, Node falls back to root-dir/kv-store.json.
- CLI E2E mode uses the KV store directly so tests do not mutate the keychain.
- Headless flows fail with a missing-password error and a command hint.
- Interactive browser/Desktop flows may request a password through ui-request.
CLI cloud tokens are stored separately in ~/logseq/auth.json. Runtime sync
receives auth state in memory.
#### Large operations
Large logical transactions must remain one ordered operation while bounding
individual allocations and requests.
Client upload behavior:
- frontend.worker.sync.apply-txs groups datoms without splitting an inseparable
datom group.
- Upload requests target a 5000-datom cap; one inseparable group may exceed it.
- Chunks are sent sequentially and preserve logical order.
Server apply behavior:
- A large entry targets 500-item apply chunks; one inseparable group may exceed
the target.
- Intermediate chunks suppress per-chunk checksum updates.
- The final checksum is updated from the complete logical transaction.
- The listener is installed and removed around the operation.
- Failure payloads preserve already successful transaction ids and the failed
transaction id when known.
Do not promise full rollback across already committed chunks. Preserve explicit
partial-success reporting so clients can reconcile deterministically.
#### Checksums
logseq.db-sync.checksum owns the checksum algorithm. It normalizes eligible
entities into stable tuples and supports both full recomputation and incremental
updates.
Checksum comparison is meaningful only when local and remote transaction
positions are synchronized. The client records the latest remote checksum and
logs a mismatch only after that readiness condition.
Investigation sequence:
1. Record graph id, local t, remote t, local checksum, and remote checksum.
2. Query /checksum/diagnostics for the server recomputation.
3. Recompute the local checksum from the same logical graph state.
4. Compare normalized tuple diagnostics, not raw SQLite row order.
5. Replay a captured transaction with the scripts exposed by
deps/db-sync/package.json when the incremental transition is suspect.
6. Distinguish a true state divergence from a stale t/checksum observation.
Snapshot upload may initialize a missing checksum only before transaction history
has advanced. It must not overwrite an existing different checksum.
#### Cycle repair utility
`logseq.db-sync.cycle` implements and tests reference-cycle repair for:
- :block/parent, cardinality one;
- :logseq.property.class/extends, cardinality many.
Its algorithm:
1. Collect entities touched by remote and local transaction reports.
2. Detect a reachable cycle with DFS across the configured attribute.
3. Prefer an edge whose current value differs from the corresponding value in
the remote transaction report.
4. Retract one edge on the cycle.
5. For block parent, add a safe remote parent or page root when possible.
6. For class extension, prefer the remote reference set or Root fallback.
7. Repeat until stable, with a 16-iteration safety cap.
Repair transactions use `:outliner-op :fix-cycle`, disable undo generation, and
set `:persist-op? false`.
Current integration boundary: the client remote-apply path in
`frontend.worker.sync.apply-txs` repairs duplicate outliner orders but does not
call `logseq.db-sync.cycle/fix-cycle!`. The utility and its unit tests therefore
must not be described as active client-side cycle repair.
#### Schema and failure policy
D1 schema changes require SQL migrations in deps/db-sync/worker/migrations.
Runtime schema initialization is not a substitute for a migration.
db-sync should fail closed on invalid auth, graph access, E2EE semantic access,
stale ordering, invalid snapshots, and malformed transaction payloads. Do not
introduce defaults that hide corrupt state.
### Incremental rendering and outliner transactions
The worker commits graph state once and derives renderer state from the committed
transaction.
Current flow:
1. An outliner/thread API transacts in the worker.
2. frontend.worker.db-listener receives the complete transaction report.
3. render-affected-keys derives exact resource invalidations.
4. render-delta builds one renderer delta.
5. The worker broadcasts :sync-db-changes.
6. frontend.db.subs applies the graph-scoped revision.
7. React hooks read immutable snapshots from frontend.db.hooks.
#### Render delta contract
A delta contains:
- graph-id;
- rev, derived from the authoritative database transaction position;
- optional operation id;
- complete block replacements keyed by block UUID;
- deleted block tombstones with revision and previous db/id when available;
- child membership patches per parent;
- affected render-resource keys.
Every replacement block carries :block/tx-id. A block cannot be both replaced
and deleted in one delta.
Child patches contain base-rev and rev plus ordered remove/upsert operations.
Membership changes are derived from:
- :block/parent;
- :block/order;
- :block/closed-value-property;
- :logseq.property/created-from-property;
- :logseq.property/deleted-at.
The renderer ignores a whole delta when its graph differs from the active graph
or its revision is not newer. For child patches, a mounted slot whose base
revision cannot be reconciled is marked stale and reloaded instead of being
merged speculatively.
#### Subscription store
frontend.db.subs owns one immutable external store. Important resource
identities include:
- [:block uuid]
- [:children parent-uuid]
- [:resource resource-key]
Subscriptions watch exact keys. Applying a delta updates cached blocks and
children, marks affected resources, and notifies only slots whose snapshot
changed.
Render-resource computation is registered in
frontend.worker.handler.render-resource.engine. Families include basic graph
lookups, property resources, views, and queries. The registry and
render-affected-keys must evolve together: every cached resource needs an exact
invalidation rule.
Checksum updates, db-sync persistence, Markdown mirror work, and search-index
updates run after the graph transaction commits. Each registered listener is
wrapped so synchronous or promise failures are reported through
`:capture-error`; they do not roll back the committed graph transaction.
#### Outliner performance guardrails
Outliner mutations use worker-owned transactions and publish their committed
result through the renderer delta path. Do not add a second optimistic block
tree or publish the same mutation independently from both a command response and
the DB listener. Page-window APIs should transfer the requested window, not a
full page, and graph-open work must not add graph-wide GC or `VACUUM`.
Useful transaction-pipeline measurements that are already logged include:
- performance id, outliner operation, and transaction count;
- renderer pipeline, delta construction, and broadcast time;
- checksum, persistence, sync-main, and registered-handler time;
- total listener time.
These measurements are diagnostics, not a fixed latency guarantee.
### CLI engineering guide
The shipped CLI is implemented in OCaml and compiled with Melange:
~~~text
cli/ OCaml
-> Dune/Melange
-> Vite bundle
-> cli/_build/default/dist/logseq-cli.js
-> scripts/stage-cli-runtime.mjs
-> static/logseq-cli.js
~~~
db-worker-node remains ClojureScript and is bundled separately to
dist/db-worker-node.js. There is no shadow-cljs logseq-cli target.
CLI source map:
| Concern | Source |
| --- | --- |
| Entry/orchestration | cli/lib/cli.ml |
| Command ids | cli/lib/command_id.ml |
| Registry/help/options | cli/lib/command_registry.ml |
| Parsing | cli/lib/cli_parse.ml |
| Actions | cli/lib/cli_action.ml |
| Worker transport | cli/lib/transport.ml |
| Daemon lifecycle | cli/lib/server_runtime.ml |
| Graph/import/export/backup | cli/lib/graph.ml |
| Sync | cli/lib/sync.ml |
| AgentBridge | cli/lib/agent.ml |
| Platform effects | cli/lib/platform/ |
| Public command reference | docs/cli/logseq-cli.md |
cli/spec contains interfaces and cli/test contains unit/parity tests. The CLI
uses the existing CLJS daemon; do not duplicate the worker database or sync
implementation in OCaml.
#### Configuration and output
With the default root, runtime files may include:
~~~text
~/logseq/
cli.edn
auth.json
kv-store.json
server-list
graphs/
~~~
Configuration precedence is global flag, then environment variable, then
cli.edn. Auth tokens and E2EE passwords are not CLI config fields.
Output modes:
- human is display-oriented and may truncate table titles by display width;
- json and edn preserve full values for scripts;
- namespaced keyword keys retain namespace/name form in JSON;
- UUIDs become strings in JSON;
- verbose and profile diagnostics go to stderr;
- normal structured stdout must not contain human warnings;
- sync progress is disabled by default for structured output unless explicitly
requested.
Executed commands are normalized internally to `Cli_result.t`, with status,
data or error, optional command id, output renderer, and optional exit code.
Human output may be a table or message; JSON and EDN serialize structured
results. `skill show` deliberately renders the skill body as raw human text.
#### Data operations
The CLI exposes list, show, search, query, upsert, move, and remove commands.
Important shared rules:
- Human list titles are CJK-aware and truncate by display width, not byte count.
- Structured list output never uses human truncation.
- Selectors must be unambiguous; commands reject conflicting id, UUID, ident,
name, and page options.
- list node tag/property filters use all-of semantics.
- Block and page references are rendered from UUID-backed graph data.
- show resolves nested block references with a depth cap.
- show page hierarchy is explicit and does not replace normal page content
display.
- Library is a special hierarchy root, but ordinary page hierarchy uses the
same bounded traversal and cycle protection.
- Mutations use worker outliner APIs rather than raw database editing in the
CLI.
SQLite export asks the worker to write the snapshot directly to the destination
path. EDN export forwards validated graph export options. SQLite import has a
top-level missing-graph check; EDN import may target an existing graph.
Current limitation: `graph backup restore` imports a SQLite backup but is not
included in the CLI's top-level missing-graph check. It must not be documented as
rejecting an existing destination until that constraint is implemented.
#### Sync behavior
CLI sync reuses worker-side sync logic:
- upload resolves or creates a remote graph identity before snapshot transfer;
- download starts a create-empty daemon and refuses a non-empty target;
- download uses a long-running command timeout;
- progress uses /v1/events and :rtc.log/download;
- asset download validates the asset entity and local checksum before enqueue;
- a valid local asset skips the remote request;
- a checksum mismatch requests a new download;
- sync config accepts transport keys only;
- E2EE password verification and storage remain worker-owned.
doctor validates the daemon bundle, root permissions, running server readiness,
and revision compatibility. When startup reports missing bundled modules, rebuild
db-worker-node and verify every asset in dist/db-worker-node-assets.json.
#### AgentBridge
cli/lib/agent.ml owns graph-scoped AgentBridge routing.
Implemented routing constraints:
- one bridge lock exists per graph and agent name;
- the agent name comes from configuration or hostname and must be non-empty;
- one master Codex session is started and resumed for task and comment dispatch;
- a task is routable only when it has a stable UUID, the Task class, TODO status,
the matching assignee, and no `:logseq.property.agent/session-id`;
- an ancestor task session id is passed to the master as inherited routing
context for descendant tasks.
Prompt templates from the AgentBridge registry are loaded and validated at
startup, and invalid custom templates are replaced with defaults. The current
dispatch path discards that returned template set and constructs hard-coded
master prompts instead. Custom registry templates therefore must not be
documented as affecting dispatched prompts until the dispatch path consumes
them.
The generated master instructions say that only the master may write graph
results, subagents are read-only, and a launched child session id must be saved
on the task. Those are prompt-level policies, not enforcement by the OCaml
bridge, so they must not be presented as runtime guarantees.
Keep graph queries, lock ownership, task routing, prompt construction, and
external process effects separately testable.
### Vector search
Desktop vector search uses:
- Electron embedding server:
src/electron/electron/embedding_server.cljs;
- default sentence-transformer model: all-MiniLM-L6-v2;
- embedding dimension: 384;
- vector context version: 3;
- zvec-backed Node vector index;
- SQLite keyword search plus vector results.
Each searchable block keeps at most one vector document, keyed by block UUID.
Both indexes derive their text from that block's search title; they do not
concatenate parent, sibling, or child context. SQLite FTS stores a normalized
form for ordinary blocks. The vector document embeds and retains the
pre-normalized title for ranking context-term boosts.
Constraints:
- Do not multiply vector count with rolling windows.
- Do not add parent/sibling traversal to full rebuild or incremental indexing
without a measured need and an explicit invalidation model.
- Preserve exact keyword matches ahead of weak vector hits.
- Current vector search returns at most 10 vector candidates and requires score
greater than 0.5.
- A completed vector rebuild writes model id, dimension, and context version to
index metadata. The current rebuild decision checks the SQLite search index
`PRAGMA user_version` or an explicit force flag; it does not compare the
persisted vector metadata on open. Do not claim automatic metadata-mismatch
rebuild until that check exists.
Incremental indexing derives affected searchable entities from the transaction.
It intentionally does not reindex adjacent siblings merely because a sibling was
reordered, and it does not expand a moved block update to the new parent. Page
hierarchy changes do reindex descendant pages whose indexed titles depend on the
hierarchy.
### Graph View
Graph View is a relationship browser built from worker graph data and rendered
with Pixi.
Source map:
| Concern | Source |
| --- | --- |
| Global UI and settings | src/main/frontend/components/graph.cljs |
| Page/block sidebar graph | src/main/frontend/components/page.cljs |
| Worker graph builder | src/main/frontend/worker/graph_view.cljs |
| React/Rum bridge | src/main/frontend/extensions/graph.cljs |
| Pixi renderer | src/main/frontend/extensions/graph/pixi.cljs |
| Layout and visibility logic | src/main/frontend/extensions/graph/pixi/logic.cljs |
| Styling | src/main/frontend/extensions/graph.css |
The renderer receives plain nodes and links. The worker emits string endpoint
ids and deduplicates links by directed endpoint pair. A later nonblank label can
replace an earlier label for the same pair, and class-extension links carry an
explicit `class-extends` edge type.
Relationship sources:
- :block/tags;
- :block/refs, lifted to owning pages where appropriate;
- user ref properties, labeled with the property title;
- :logseq.property.class/extends;
- :block/parent for page hierarchy in all-pages mode.
Global modes:
- tags-and-objects is the default;
- all-pages renders the visible page relationship graph.
tags-and-objects excludes property definitions, hidden/recycled entities,
excluded entities, and core internal tag classes. It renders tag/class nodes,
their objects, class-extension links, and visible ref-property links.
all-pages excludes hidden/recycled pages and internal property pages. Journals,
built-ins, excluded pages, and orphans are controlled by options. The large-graph
path activates at 10,000 page-name datoms, bounds visible ref links to 20,000,
then appends property, parent, and extension link tuples before applying a
20,000-link cap to the combined sequence. Because ref links come first,
structural links are not guaranteed to survive when the cap is exhausted.
The page graph centers on a page and includes references, mentions, tags, class
extensions, and selected second-order relationships. The block graph centers on
a block and connects incoming/outgoing referenced pages. Both use the same Pixi
page-mode renderer.
Renderer invariants:
- visible-node sets filter rendered nodes and links independently from the
source graph data;
- label selection is bounded and screen-cell based to reduce overlap;
- all-pages and tags-and-objects share the Pixi renderer plumbing;
- the renderer exposes explicit visibility updates and destroys its label,
edge-label, and application resources during cleanup.
Per-repo settings are stored under logseq.graph.settings.<repo>. They cover view
mode, selected tags, depth, link distance, grid layout, journal visibility, and
open settings groups. Time-travel cutoff is session state and is not persisted as
the graph's initial filter.
### Frontend state and UI dependencies
frontend.state remains the primary application state namespace. Focused modules
such as frontend.graph-tab own selected domains, but there is no general
src/main/frontend/state/ facade tree. Add a focused state namespace only when it
has real ownership, not to mirror a historical split plan.
The UI stack uses Base UI and Tailwind 4. Read package.json and current component
usage before changing dependency or styling conventions.
### Engineering workflow
Before changing a subsystem:
1. Read root and directory-specific AGENTS.md.
2. Locate the owning source, its callers, and its tests.
3. Confirm runtime boundaries: browser, renderer, Electron, Node worker, CLI, or
server.
4. Write or update the narrowest behavior test.
5. Preserve one authoritative data path.
6. Fail fast on invalid internal state.
7. Remove obsolete paths instead of adding compatibility fallbacks.
8. Run focused tests before broad verification.
Useful commands:
~~~sh
# Repository lint and unit tests
bb dev:lint-and-test
# One unit test
bb dev:test -v <namespace/testcase-name>
# Already-compiled CLJS namespaces
bb dev:run-test-namespaces -n <namespace>
# CLI
(cd cli && opam exec --switch=<compatible-ocaml-switch> -- dune runtest)
pnpm cli:release
pnpm db-worker-node:release:bundle
bb -f cli-e2e/bb.edn test --skip-build
# db-sync
pnpm --dir deps/db-sync test
pnpm --dir deps/db-sync test:chatgpt-app
pnpm --dir deps/db-sync test:large-op-128m
# Agent document validation
spec-dev-tool check --all
~~~
Use docs/cli/logseq-cli.md for the current CLI command reference and generated
OpenAPI for the current semantic API contract.
## Alternatives considered
### Keep the original plans as the technical reference
Rejected because proposed steps and old file paths are indistinguishable from
current behavior during search.
### Duplicate every current source contract in prose
Rejected because exhaustive route, command, and schema duplication would become
stale quickly. This guide records durable concepts and points detailed contracts
to executable registries and tests.
## Consequences
The guide preserves useful architecture, protocol, data-flow, performance, and
debugging knowledge in one document. Historical task sequencing, temporary
benchmarks, and obsolete proposals are intentionally absent.
The guide is concise enough to read as an orientation document, but engineers
must still inspect the named source and tests before modifying behavior.
@@ -0,0 +1,158 @@
# Lower CLI OCaml Minimum to 5.1.1
## Problem
The CLI does not declare an OCaml version constraint. `cli/dune-project`
depends on `ocaml` without a lower bound, so the generated
`cli/logseq-cli.opam` file does the same. At the same time, every GitHub Actions
workflow that builds the CLI selects OCaml 5.4.0. The repository therefore
neither advertises the intended minimum nor verifies it.
The local `default` opam switch uses OCaml 5.1.1 and Dune 3.23.1. Those tool
versions are sufficient for the project metadata and the pinned CLI
dependencies, but a clean CLI test build currently stops while parsing
`cli/spec/core/cli_primitive.mli`:
```text
type keyword = Melange_edn_melange.(keyword t)
^
Error: Syntax error
```
`Module.(type_expression)` is a type-level local open, an OCaml 5.2 language
feature. The [OCaml 5.2 release notes](https://github.com/ocaml/ocaml/releases/tag/5.2.0)
identify local opens in type expressions as new in that release. Parsing all
122 checked-in `.ml` and `.mli` files with the OCaml 5.1.1 compiler found this
as the only parser incompatibility. The equivalent fully qualified type
expression
`Melange_edn_melange.keyword Melange_edn_melange.t` parses under OCaml 5.1.1.
The compiler version and the installed dependency set are separate concerns.
The current `default` switch does not have Melange or the private pinned CLI
packages installed, so it cannot build the CLI without the normal dependency
installation step. A different local switch using the same OCaml 5.1.1
compiler already contains the required dependency family, including Melange,
`melange-edn-melange`, `melange-transit-melange`, `humanize`, and `rrbvec`.
The pinned `melange-edn` and `melange-transit` packages declare OCaml
`>= 5.1.1`, `humanize` declares OCaml `>= 5.0`, and Melange publishes a
compiler-specific 5.1 package variant. No dependency inspected requires OCaml
5.2 or newer.
The goal is therefore to make OCaml 5.1.1 the explicit, continuously verified
CLI minimum so the existing `default` switch can be used after installing the
project dependencies. It is not to make a switch with missing dependencies
build the CLI without bootstrapping them.
## Proposal
Declare OCaml `>= 5.1.1` in the `logseq-cli` package dependencies in
`cli/dune-project`, then regenerate and commit `cli/logseq-cli.opam` so both
files expose the same constraint.
Replace the single OCaml 5.2-only type-level local open in
`cli/spec/core/cli_primitive.mli` with the fully qualified OCaml 5.1-compatible
type expression:
```ocaml
type keyword = Melange_edn_melange.keyword Melange_edn_melange.t
```
This is a syntax-only change to an existing alias. It does not change the
public type, runtime representation, or CLI behavior. Do not add a conditional
compatibility layer or maintain separate source paths for different compiler
versions.
Change `OCAML_VERSION` from 5.4.0 to 5.1.1 in all four workflows that build the
CLI:
- `.github/workflows/build.yml`;
- `.github/workflows/build-desktop-release.yml`;
- `.github/workflows/deps-cli.yml`; and
- `.github/workflows/cli-sync-stress.yml`.
This makes the minimum compiler the single compiler baseline for CLI unit,
E2E, dependency-update, stress, Desktop release, and npm release builds. The
released JavaScript artifacts will therefore also be produced with the 5.1.1
compiler-specific Melange variant.
Keep the normal local bootstrap command as:
```sh
cd cli
opam install . --deps-only --with-test --yes
opam exec -- dune runtest
```
The implementation must verify the dependency installation in a clean 5.1.1
switch rather than relying on packages already pinned in a developer switch.
If the existing `pin-depends` metadata does not bootstrap the private packages
in that clean environment, fix that single bootstrap path as part of this
decision; do not introduce a fallback dependency-install path.
## Alternatives considered
### Keep OCaml 5.4.0 as the minimum
Rejected because the only checked-in language dependency on OCaml 5.2 or newer
is a shorthand type expression with a direct 5.1-compatible spelling. The
inspected dependencies already support OCaml 5.1.1, and requiring a separate
5.4 switch adds local setup cost without providing a needed CLI capability.
### Declare `>= 5.1.1` without changing the source
Rejected because the declaration would be false. A clean OCaml 5.1.1 build
currently fails before type checking, and an existing Dune build directory can
hide the problem by reusing artifacts produced with a newer compiler.
### Keep the package unconstrained and rely on documentation
Rejected because opam could select an unsupported older compiler and CI would
not enforce the documented minimum. The package manifest is the authoritative
place for the compiler contract.
### Maintain separate source for OCaml 5.1 and newer compilers
Rejected because the fully qualified type is accepted by both compiler lines
and preserves the same public type. A compatibility branch or preprocessor
would add complexity without retaining a distinct capability.
## Acceptance criteria
- `cli/dune-project` declares `ocaml (>= 5.1.1)`, and the generated
`cli/logseq-cli.opam` file contains the equivalent constraint.
- `cli/spec/core/cli_primitive.mli` contains no type-level local open and
exposes the same `keyword` alias through fully qualified type constructors.
- In a clean opam switch whose compiler is exactly OCaml 5.1.1,
`opam install . --deps-only --with-test --yes` succeeds from `cli/` without
manually installing a newer compiler.
- A clean, non-cached `opam exec -- dune runtest` succeeds with OCaml 5.1.1.
- `opam exec -- pnpm cli:release` succeeds with OCaml 5.1.1, and
`node dist/logseq.js --help` succeeds against the staged artifact.
- `bb -f cli-e2e/bb.edn test --skip-build` passes against artifacts freshly
built with OCaml 5.1.1.
- `.github/workflows/build.yml`, `.github/workflows/build-desktop-release.yml`,
`.github/workflows/deps-cli.yml`, and
`.github/workflows/cli-sync-stress.yml` all select OCaml 5.1.1.
- The required GitHub Actions paths collectively exercise dependency
bootstrap, CLI unit and E2E tests, release builds, smoke tests, and stress
tests with OCaml 5.1.1 so a future use of OCaml 5.2-only syntax cannot merge
or ship unnoticed.
- The existing OCaml 5.4 build remains supported because the package contract
has no upper bound.
## Risks
- Building release artifacts with OCaml 5.1.1 selects a different
compiler-specific Melange package variant than OCaml 5.4.0. Unit, smoke, and
CLI E2E tests must validate the generated JavaScript rather than assuming the
compiler downgrade is syntax-only at the artifact level.
- The private dependencies in `pin-depends` track `main`, so their future
minimum OCaml version can move independently of this repository. The clean
5.1.1 dependency-install CI step is the guard against that drift.
- Incremental Dune artifacts built under another switch can conceal parser
incompatibilities. Minimum-version verification must use a clean build
directory.
- Installing the CLI dependencies into a multipurpose `default` switch changes
that switch's package set. This decision makes the compiler version
sufficient; it does not promise that installing the dependencies is free of
solver changes to unrelated packages already present in the switch.
@@ -0,0 +1,118 @@
# DB Sync Node.js Adapter Implementation Plan
Goal: Build a Node.js server adapter for DB sync so users can self-host without Cloudflare dependencies.
Architecture: Reuse the existing db-sync core logic and route handlers while introducing a platform abstraction layer that swaps Cloudflare APIs for Node.js equivalents.
Architecture: Provide a new Node.js entrypoint that wires HTTP and WebSocket handling to the shared handlers and pluggable storage and auth backends.
Tech Stack: ClojureScript, shadow-cljs, Node.js LTS, standard Node HTTP and WebSocket libraries, existing db-sync ClojureScript modules.
Related: Builds on the engineering context consolidated in docs/agent-guide/implemented/architecture/2026-08-24-logseq-runtime-and-engineering-guide.md and docs/adr/0001-nodejs-db-sync-server-adapter.md.
## Problem statement
The current DB sync server implementation assumes a Cloudflare Worker runtime and related APIs.
That assumption prevents users from running the sync server on standard Node.js infrastructure.
We need a portable adapter that preserves the DB sync protocol and behavior while replacing Cloudflare-specific primitives.
## Testing Plan
I will add an integration test that spins up the Node.js adapter, runs a health check, and performs a minimal pull and tx/batch round-trip over HTTP to confirm protocol compatibility.
I will add an integration test that opens a WebSocket connection, performs hello and pull, and validates changed notifications on tx/batch.
I will add a unit test that exercises the platform abstraction layer to ensure request and response coercion behave the same for both Node and worker inputs.
I will add a unit test that validates storage and auth adapter selection from configuration, including error handling for missing drivers.
NOTE: I will write all tests before I add any implementation behavior.
## Scope
The Node.js adapter will implement the existing HTTP and WebSocket endpoints summarized in docs/agent-guide/implemented/architecture/2026-08-24-logseq-runtime-and-engineering-guide.md; current route and protocol source remains authoritative.
The adapter will run the same handler logic currently used by the Cloudflare worker.
The adapter will support pluggable storage and auth providers to match the existing worker behavior.
## Non-goals
This plan does not add new DB sync protocol features.
This plan does not migrate existing cloud hosting or change client behavior.
This plan does not redesign storage schemas or transaction ordering.
## Architecture Overview
The adapter will introduce a platform boundary and a Node runtime entrypoint that binds HTTP and WS requests to the existing worker handlers.
The platform boundary will normalize request, response, and WebSocket interfaces so the core logic remains unchanged.
The Node entrypoint will be responsible only for server lifecycle and wiring adapters.
+--------------------+ HTTP/WS +------------------------+ storage/auth +------------------+
| Logseq Client Apps | <--------------> | Node.js DB Sync Adapter | <------------------> | Storage Backends |
+--------------------+ +------------------------+ +------------------+
| Shared db-sync handlers |
+------------------------+
## Implementation Plan
1. Read docs/agent-guide/implemented/architecture/2026-08-24-logseq-runtime-and-engineering-guide.md and list the Cloudflare-specific APIs used by the worker in deps/db-sync/src/logseq/db_sync/worker/.
2. Create a platform abstraction namespace in deps/db-sync/src/logseq/db_sync/platform/core.cljs that defines the minimal request, response, and WebSocket operations used by handlers.
3. Add a Cloudflare platform adapter in deps/db-sync/src/logseq/db_sync/platform/cloudflare.cljs that wraps the current Worker Request, Response, and WebSocket types.
4. Add a Node platform adapter in deps/db-sync/src/logseq/db_sync/platform/node.cljs that wraps Node HTTP requests, responses, and WebSocket connections.
5. Update deps/db-sync/src/logseq/db_sync/worker/dispatch.cljs and deps/db-sync/src/logseq/db_sync/worker/http.cljs to depend on the platform abstraction instead of direct Worker APIs.
6. Add a Node server entrypoint in deps/db-sync/src/logseq/db_sync/node/entry.cljs that sets up HTTP routes, WS upgrade handling, and lifecycle start/stop.
7. Add a Node routing layer in deps/db-sync/src/logseq/db_sync/node/routes.cljs that maps incoming requests to the existing worker route handlers.
8. Introduce configuration parsing in deps/db-sync/src/logseq/db_sync/node/config.cljs to select storage and auth drivers via environment variables.
9. Add Node adapter implementations for storage and assets in deps/db-sync/src/logseq/db_sync/node/storage.cljs and deps/db-sync/src/logseq/db_sync/node/assets.cljs that map to the existing storage interfaces.
10. Add a new shadow-cljs build target in deps/db-sync/shadow-cljs.edn for the Node adapter output.
11. Add build and run scripts to deps/db-sync/package.json for the Node adapter, including a dev watch command.
12. Update the active db-sync documentation with the new local dev and test commands for the Node adapter.
13. Add a new self-hosting section to docs/develop-logseq.md with minimal steps to run the Node adapter.
14. Add integration tests under deps/db-sync/test/logseq/db_sync/node_adapter_test.cljs that launch the Node adapter and exercise HTTP and WS paths.
15. Add unit tests under deps/db-sync/test/logseq/db_sync/platform_test.cljs that cover request normalization and error propagation.
16. Run the tests using the commands listed in the Verification section and confirm they fail before implementation and pass after implementation.
## Configuration Matrix
Use the following environment variables for the Node adapter configuration.
| Variable | Purpose | Example |
| --- | --- | --- |
| DB_SYNC_PORT | HTTP server port | 8080 |
| DB_SYNC_BASE_URL | External base URL for asset links | https://sync.example.com |
| DB_SYNC_STORAGE_DRIVER | Storage backend selection | sqlite |
| DB_SYNC_ASSETS_DRIVER | Asset storage backend selection | filesystem |
| DB_SYNC_LOG_LEVEL | Log verbosity | info |
| COGNITO_ISSUER | Cognito issuer URL | https://cognito-idp.us-east-2.amazonaws.com/us-east-2_kAqZcxIeM |
| COGNITO_CLIENT_ID | Cognito app client id | 1qi1uijg8b6ra70nejvbptis0q |
| COGNITO_JWKS_URL | Cognito JWKS URL | https://cognito-idp.us-east-2.amazonaws.com/us-east-2_kAqZcxIeM/.well-known/jwks.json |
## Verification
Run the server-side test suite.
```bash
bb dev:db-sync-test
```
Expected result is a zero exit code and no failing tests.
Run the Node adapter integration tests.
```bash
cd deps/db-sync
pnpm test:node-adapter
```
Expected result is a zero exit code and logs that the Node adapter started and all tests passed.
## Edge Cases
Unauthorized requests should return the same 401 or 403 responses as the Cloudflare worker.
Invalid request payloads must produce the same error responses as the worker routes.
WebSocket message validation must reject unknown types with the same error shape.
Snapshot upload should preserve content-encoding and reject missing bodies consistently.
Asset uploads must enforce size limits and return the same error codes as the worker.
## Testing Details
I will add integration tests that launch the Node adapter and use HTTP and WebSocket calls to validate real protocol behavior rather than mocking handlers.
I will add unit tests for the platform adapters to ensure coercion and error handling match existing worker semantics.
These tests validate observable behavior and response shapes instead of internal data structures.
## Implementation Details
- Introduce a platform interface to normalize request, response, and WebSocket operations.
- Keep all protocol validation and handler logic inside deps/db-sync/src/logseq/db_sync/worker to avoid divergence.
- Make the Node entrypoint responsible only for wiring and lifecycle.
- Add configuration parsing and driver selection in Node-specific namespaces.
- Add a new shadow-cljs build target for the Node adapter output.
- Add npm scripts for building and testing the Node adapter.
- Update docs to include self-hosting and local dev guidance.
## Question
Where should the AGENTS.workflow.md guidance live for plan documents in this repo.
Do we want to support the same storage backends as Cloudflare on day one or limit to a single local driver for the first release.
Should the Node adapter include optional CORS configuration or match the current worker defaults exactly.
---
+76
View File
@@ -0,0 +1,76 @@
# ADR: Reactions via Properties
## Status
- Proposed
## Context
- Users want lightweight reactions (e.g., 👍 ❤️) on blocks and pages.
- Reactions must be stored in the graph so they sync, can be queried, and work across devices.
- The system already uses properties to attach structured metadata to blocks/pages.
- We need to show who reacted and which emoji they used.
## Decision
- Store reactions as separate entities linked to the reacted block/page.
- Each reaction entity records:
- Emoji id (from Logseq’s supported `emojis-data` set).
- Optional `:logseq.property/created-by-ref` pointing to the reacting user (absent for anonymous graphs).
- Reacted block/page reference.
- `:block/created-at` timestamp for the reaction entity.
- No `:logseq.property/reactions` collection property is required; use the reverse ref
`(:logseq.property.reaction/_target node-entity)` to fetch reactions for a node.
- Keep the property name namespaced in logseq.db.frontend.property/built-in-properties.
### Proposed entity shape
```
{:db/id ...
:logseq.property.reaction/emoji-id "smile"
:logseq.property/created-by-ref <user-db-id> ;; omitted for anonymous graphs
:logseq.property.reaction/target <target-db-id> ;; block/page db id
:block/created-at 1710000000000}
```
### Read/write rules
- Toggling a reaction adds/removes a reaction entity for the current emoji/user.
- If anonymous, only one reaction per emoji per block/page (no user id).
- Reactions are derived via reverse reference lookup; no dedicated collection
property is stored on the node.
### Example queries
```clj
;; Given a block/page entity `node-entity`, fetch all reactions.
(:logseq.property.reaction/_target node-entity)
;; Filter reactions by emoji id.
(filter #(= "smile" (:logseq.property.reaction/emoji-id %))
(:logseq.property.reaction/_target node-entity))
;; Count reactions per emoji id.
(->> (:logseq.property.reaction/_target node-entity)
(map :logseq.property.reaction/emoji-id)
(frequencies))
;; Filter reactions by user id (when present).
(filter #(= user-db-id (:logseq.property/created-by-ref %))
(:logseq.property.reaction/_target node-entity))
```
## Consequences
- Reactions sync naturally as part of DB transactions and are queryable.
- Data model supports “who reacted” and multiple users per emoji without map merging.
- Adds more entities; need efficient queries and indexes.
## Alternatives Considered
- **Dedicated table/attribute per emoji**: complicates schema, increases complexity.
- **Property map (emoji -> users)**: smaller but harder to resolve conflicts and query per user.
- **Inline text markers**: not structured, hard to query and sync.
## Open Questions
- Which user identifier should be stored as `:logseq.property/created-by-ref`?
Each user has a page in the graph
- How to handle anonymous/local graphs (no user identity)?
Record reactions, for anonymous graphs, don't store :logseq.property/created-by-ref
## Notes for Implementation
- Add emoji entity schema to DB validation.
- UI should show a summary (emoji + count) and a hover/popover with user list.
- User can toggle reaction.
+66
View File
@@ -0,0 +1,66 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 19.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="120.1px" height="130.2px" viewBox="0 0 120.1 130.2" style="enable-background:new 0 0 120.1 130.2;" xml:space="preserve"
>
<g>
<linearGradient id="XMLID_2_" gradientUnits="userSpaceOnUse" x1="31.8412" y1="120.5578" x2="110.2402" y2="73.24">
<stop offset="0" style="stop-color:#FCEE39"/>
<stop offset="1" style="stop-color:#F37B3D"/>
</linearGradient>
<path id="XMLID_3041_" style="fill:url(#XMLID_2_);" d="M118.6,71.8c0.9-0.8,1.4-1.9,1.5-3.2c0.1-2.6-1.8-4.7-4.4-4.9
c-1.2-0.1-2.4,0.4-3.3,1.1l0,0l-83.8,45.9c-1.9,0.8-3.6,2.2-4.7,4.1c-2.9,4.8-1.3,11,3.6,13.9c3.4,2,7.5,1.8,10.7-0.2l0,0l0,0
c0.2-0.2,0.5-0.3,0.7-0.5l78-54.8C117.3,72.9,118.4,72.1,118.6,71.8L118.6,71.8L118.6,71.8z"/>
<linearGradient id="XMLID_3_" gradientUnits="userSpaceOnUse" x1="48.3607" y1="6.9083" x2="119.9179" y2="69.5546">
<stop offset="0" style="stop-color:#EF5A6B"/>
<stop offset="0.57" style="stop-color:#F26F4E"/>
<stop offset="1" style="stop-color:#F37B3D"/>
</linearGradient>
<path id="XMLID_3049_" style="fill:url(#XMLID_3_);" d="M118.8,65.1L118.8,65.1L55,2.5C53.6,1,51.6,0,49.3,0
c-4.3,0-7.7,3.5-7.7,7.7v0c0,2.1,0.8,3.9,2.1,5.3l0,0l0,0c0.4,0.4,0.8,0.7,1.2,1l67.4,57.7l0,0c0.8,0.7,1.8,1.2,3,1.3
c2.6,0.1,4.7-1.8,4.9-4.4C120.2,67.3,119.7,66,118.8,65.1z"/>
<linearGradient id="XMLID_4_" gradientUnits="userSpaceOnUse" x1="52.9467" y1="63.6407" x2="10.5379" y2="37.1562">
<stop offset="0" style="stop-color:#7C59A4"/>
<stop offset="0.3852" style="stop-color:#AF4C92"/>
<stop offset="0.7654" style="stop-color:#DC4183"/>
<stop offset="0.957" style="stop-color:#ED3D7D"/>
</linearGradient>
<path id="XMLID_3042_" style="fill:url(#XMLID_4_);" d="M57.1,59.5C57,59.5,17.7,28.5,16.9,28l0,0l0,0c-0.6-0.3-1.2-0.6-1.8-0.9
c-5.8-2.2-12.2,0.8-14.4,6.6c-1.9,5.1,0.2,10.7,4.6,13.4l0,0l0,0C6,47.5,6.6,47.8,7.3,48c0.4,0.2,45.4,18.8,45.4,18.8l0,0
c1.8,0.8,3.9,0.3,5.1-1.2C59.3,63.7,59,61,57.1,59.5z"/>
<linearGradient id="XMLID_5_" gradientUnits="userSpaceOnUse" x1="52.1736" y1="3.7019" x2="10.7706" y2="37.8971">
<stop offset="0" style="stop-color:#EF5A6B"/>
<stop offset="0.364" style="stop-color:#EE4E72"/>
<stop offset="1" style="stop-color:#ED3D7D"/>
</linearGradient>
<path id="XMLID_3057_" style="fill:url(#XMLID_5_);" d="M49.3,0c-1.7,0-3.3,0.6-4.6,1.5L4.9,28.3c-0.1,0.1-0.2,0.1-0.2,0.2l-0.1,0
l0,0c-1.7,1.2-3.1,3-3.9,5.1C-1.5,39.4,1.5,45.9,7.3,48c3.6,1.4,7.5,0.7,10.4-1.4l0,0l0,0c0.7-0.5,1.3-1,1.8-1.6l34.6-31.2l0,0
c1.8-1.4,3-3.6,3-6.1v0C57.1,3.5,53.6,0,49.3,0z"/>
<g id="XMLID_3008_">
<rect id="XMLID_3033_" x="34.6" y="37.4" style="fill:#000000;" width="51" height="51"/>
<rect id="XMLID_3032_" x="39" y="78.8" style="fill:#FFFFFF;" width="19.1" height="3.2"/>
<g id="XMLID_3009_">
<path id="XMLID_3030_" style="fill:#FFFFFF;" d="M38.8,50.8l1.5-1.4c0.4,0.5,0.8,0.8,1.3,0.8c0.6,0,0.9-0.4,0.9-1.2l0-5.3l2.3,0
l0,5.3c0,1-0.3,1.8-0.8,2.3c-0.5,0.5-1.3,0.8-2.3,0.8C40.2,52.2,39.4,51.6,38.8,50.8z"/>
<path id="XMLID_3028_" style="fill:#FFFFFF;" d="M45.3,43.8l6.7,0v1.9l-4.4,0V47l4,0l0,1.8l-4,0l0,1.3l4.5,0l0,2l-6.7,0
L45.3,43.8z"/>
<path id="XMLID_3026_" style="fill:#FFFFFF;" d="M55,45.8l-2.5,0l0-2l7.3,0l0,2l-2.5,0l0,6.3l-2.3,0L55,45.8z"/>
<path id="XMLID_3022_" style="fill:#FFFFFF;" d="M39,54l4.3,0c1,0,1.8,0.3,2.3,0.7c0.3,0.3,0.5,0.8,0.5,1.4v0
c0,1-0.5,1.5-1.3,1.9c1,0.3,1.6,0.9,1.6,2v0c0,1.4-1.2,2.3-3.1,2.3l-4.3,0L39,54z M43.8,56.6c0-0.5-0.4-0.7-1-0.7l-1.5,0l0,1.5
l1.4,0C43.4,57.3,43.8,57.1,43.8,56.6L43.8,56.6z M43,59l-1.8,0l0,1.5H43c0.7,0,1.1-0.3,1.1-0.8v0C44.1,59.2,43.7,59,43,59z"/>
<path id="XMLID_3019_" style="fill:#FFFFFF;" d="M46.8,54l3.9,0c1.3,0,2.1,0.3,2.7,0.9c0.5,0.5,0.7,1.1,0.7,1.9v0
c0,1.3-0.7,2.1-1.7,2.6l2,2.9l-2.6,0l-1.7-2.5h-1l0,2.5l-2.3,0L46.8,54z M50.6,58c0.8,0,1.2-0.4,1.2-1v0c0-0.7-0.5-1-1.2-1
l-1.5,0v2H50.6z"/>
<path id="XMLID_3016_" style="fill:#FFFFFF;" d="M56.8,54l2.2,0l3.5,8.4l-2.5,0l-0.6-1.5l-3.2,0l-0.6,1.5l-2.4,0L56.8,54z
M58.8,59l-0.9-2.3L57,59L58.8,59z"/>
<path id="XMLID_3014_" style="fill:#FFFFFF;" d="M62.8,54l2.3,0l0,8.3l-2.3,0L62.8,54z"/>
<path id="XMLID_3012_" style="fill:#FFFFFF;" d="M65.7,54l2.1,0l3.4,4.4l0-4.4l2.3,0l0,8.3l-2,0L68,57.8l0,4.6l-2.3,0L65.7,54z"
/>
<path id="XMLID_3010_" style="fill:#FFFFFF;" d="M73.7,61.1l1.3-1.5c0.8,0.7,1.7,1,2.7,1c0.6,0,1-0.2,1-0.6v0
c0-0.4-0.3-0.5-1.4-0.8c-1.8-0.4-3.1-0.9-3.1-2.6v0c0-1.5,1.2-2.7,3.2-2.7c1.4,0,2.5,0.4,3.4,1.1l-1.2,1.6
c-0.8-0.5-1.6-0.8-2.3-0.8c-0.6,0-0.8,0.2-0.8,0.5v0c0,0.4,0.3,0.5,1.4,0.8c1.9,0.4,3.1,1,3.1,2.6v0c0,1.7-1.3,2.7-3.4,2.7
C76.1,62.5,74.7,62,73.7,61.1z"/>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.8 KiB

+468
View File
@@ -0,0 +1,468 @@
# Logseq CLI (Node)
The Logseq CLI is a Node.js program built from the `cli/` Dune, Melange, and Vite runtime. It connects to a ClojureScript db-worker-node server managed by the CLI. When installed, the CLI binary name is `logseq`.
## Build the CLI
```bash
pnpm cli:release
pnpm db-worker-node:release:bundle
```
`pnpm cli:release` bundles the `cli/` runtime and stages it to `static/logseq-cli.js`, which is the stable local, npm package, and desktop packaging runtime path.
`pnpm db-worker-node:release:bundle` compiles and bundles `db-worker-node` with Vite, and writes a standalone runtime to `dist/db-worker-node.js` plus an asset manifest at `dist/db-worker-node-assets.json` (which may contain an empty `assets` array when no extra files are required).
## db-worker-node lifecycle
`logseq` manages `db-worker-node` automatically. You should not start the server manually. The server binds to localhost on a random port and records that port in the repo lock file.
Desktop + CLI shared semantics:
- Electron desktop and CLI are expected to use the same `db-worker-node` and lock-file protocol for a graph.
- Disk SQLite under `~/logseq/graphs` is the source of truth; OPFS periodic export is not part of the desktop primary write path.
- If a daemon already exists for the graph and reports the same revision as the requester, CLI reuses it via lock-file discovery instead of starting a second writer.
- If the discovered daemon reports a different revision, startup stops that exact server, starts a replacement from the requester's bundled runtime, and only returns a usable endpoint after the replacement reports the expected revision.
- A proven revision mismatch may be stopped across owner sources for the same repo/root-dir. Matching-revision servers keep the normal owner boundary.
- If lock ownership is invalid or stale, startup cleans stale lock state before retrying.
- Lock metadata includes an `owner-source` value (`cli`, `electron`, `unknown`) and lifecycle actions enforce owner boundaries.
- `server stop` and `server restart` are owner-aware: CLI can only stop/restart servers it owns (or legacy `unknown` ownership).
- If lock is missing but a matching orphan `db-worker-node` process still exists for the same repo/root-dir, startup performs orphan cleanup before retrying.
## Run the CLI
```bash
node ./dist/logseq.js graph list
```
You can also use npm link to make ./dist/logseq.js globally available, run:
```
npm link
```
If installed(or linked) globally, run:
```bash
logseq graph list
```
## Configuration
The CLI config file defaults to `<root-dir>/cli.edn`, where `root-dir` defaults to `~/logseq`.
Supported keys include:
- `:graph` - The current active graph. Set this with `graph switch`.
- `:root-dir` - CLI root directory. Default is `~/logseq`.
- Graph data directory is derived as `<root-dir>/graphs`.
- Config file default is derived as `<root-dir>/cli.edn`.
- Server list file default is derived as `<root-dir>/server-list`.
- Graph directories under `<root-dir>/graphs` are user-facing graph names e.g. `demo` and do not start with `logseq_db_`.
- `:output-format` - Format for output. Default is `:human`. Use `:json` or `:edn` for scripting.
- `:list-title-max-display-width` - For `:human` output, the max display width for TITLE column, defaulting to `40`.
- `:http-base` - Http base domain for sync service. Interact with this via `sync config`.
- `:ws-url` - Websocket url for sync service. Interact with this via `sync config`.
- `:timeout-ms` - Request timeout in milliseconds.
- `:login-timeout-ms` - Login callback timeout. Defaults to 5 minutes.
- `:logout-timeout-ms` - Logout callback timeout. Defaults to 2 minutes.
- `:custom-queries` - Map of custom queries which are run with `query --name`. See [below for more](#custom-queries).
CLI global flags take precedence over environment variables, which take precedence over the config file. Here is a mapping of these three:
| Config key | Environment variable | Global flag |
| --- | --- | --- |
| :graph | $LOGSEQ_CLI_GRAPH | --graph |
| :root-dir | $LOGSEQ_CLI_ROOT_DIR | --root-dir |
| :output-format | $LOGSEQ_CLI_OUTPUT | --output |
| :timeout-ms | $LOGSEQ_CLI_TIMEOUT_MS | --timeout-ms |
| :login-timeout-ms | $LOGSEQ_CLI_LOGIN_TIMEOUT_MS | n/a |
| :logout-timeout-ms | $LOGSEQ_CLI_LOGOUT_TIMEOUT_MS | n/a |
Legacy notes:
* Migration note: If you previously used `~/.logseq/cli-graphs` or `~/.logseq/cli.edn`, pass `--root-dir` and/or `--config` to continue using equivalent custom locations.
* `:e2ee-password` in `cli.edn` is ignored and removed silently during config read/update. Use `sync start --e2ee-password` or `sync download --e2ee-password` instead.
* `cli.edn` no longer persists cloud auth tokens. CLI login state is stored separately in `~/logseq/auth.json`.
### Custom Queries
Custom queries are defined in `:custom-queries` of a config file. This config is a map with the key as a query name and the value as a map with the following keys:
* `:query` - Required datalog query as a vector. Queries can use built-in rules from `logseq.db.frontend.rules` by appending `%` to the `:in` part of a query. See `logseq.cli.command.query` for example queries.
* `:doc` - Optional doc string describing the query.
* `:inputs` - Optional vector of inputs where each input is a map. Valid keys for the map are `:name` and `:default`. This defines positional arguments to a query e.g. the arguments a user passes map to these inputs and the `:in` bindings in a `:query`.
## Authentication
Use `logseq login` to authenticate the current machine with Logseq cloud.
- `logseq login` starts a temporary callback server at `http://localhost:8765/auth/callback`, opens a browser to the Logseq Cognito Hosted UI, exchanges the returned authorization code, and writes `~/logseq/auth.json`.
- `logseq logout` removes `~/logseq/auth.json`, opens a browser to the Cognito Hosted UI logout endpoint, and completes the browser logout flow at `http://localhost:8765/logout-complete`.
- Sync commands still pass an in-memory runtime `:auth-token` to db-sync, but that token is now resolved from `auth.json` instead of `cli.edn`.
Default auth file: `~/logseq/auth.json`
Auth file contents include the persisted Cognito `id-token`, `access-token`, `refresh-token`, `expires-at`, `sub`, `email`, and `updated-at` values needed for headless refresh.
Verbose logging:
- `--verbose` enables structured debug logs to stderr for CLI option parsing and db-worker-node API calls.
- `sync download` can stream realtime progress lines to stdout when progress is enabled; debug previews remain truncated.
Timeouts:
- `--timeout-ms` continues to control request timeout behavior for CLI transport.
- Login callback timeout is controlled separately by `:login-timeout-ms` / `LOGSEQ_CLI_LOGIN_TIMEOUT_MS` and defaults to 5 minutes.
- Logout callback timeout is controlled separately by `:logout-timeout-ms` / `LOGSEQ_CLI_LOGOUT_TIMEOUT_MS` and defaults to 2 minutes.
## Commands
Graph commands:
- `graph list` - list all db graphs
- `graph create --graph <name>` - create a new db graph and switch to it
- Fails with `graph-exists` if a local graph with the same name already exists
- `--enable-sync` creates the graph, switches to it, uploads it to Logseq Sync, and starts sync in one command
- `--e2ee-password <password>` is accepted only with `--enable-sync` and uses the same password verification path as `sync upload` and `sync start`
- `graph switch --graph <name>` - switch current graph
- `graph remove --graph <name>` - remove a graph
- `graph validate --graph <name>` - validate graph data
- `graph info [--graph <name>]` - show graph metadata (defaults to current graph)
- `graph export --type edn|sqlite --file <path> [--graph <name>]` - export a graph to EDN or SQLite
- EDN export also accepts `--edn-options/-e <edn-map>` and `--pretty-print/-p`
- `--edn-options` is an EDN map; `:export-type` (if present) overrides the default `:graph`, and every other key is forwarded to the worker as `:graph-options` (for example, `'{:export-type :graph-human :include-timestamps? true :exclude-built-in-pages? true :exclude-namespaces #{:user :project}}'`)
- `--pretty-print` writes the EDN file through `clojure.pprint` for readability while remaining round-trippable via `graph import --type edn`
- SQLite export writes the snapshot directly to the destination path through `db-worker-node` instead of round-tripping a base64 payload through the CLI
- `--edn-options` and `--pretty-print` are rejected when `--type sqlite` is selected; a non-map value for `--edn-options` is also rejected
- `graph import --type edn|sqlite --input <path> --graph <name>` - import a graph from EDN or SQLite; SQLite import requires a new graph, while EDN import may target an existing graph
- `graph backup list` - list backup snapshots under `<root-dir>/graphs/<graph>/backup`
- `graph backup create [--graph <name>] [--name <label>]` - create a backup snapshot for the selected graph
- `graph backup restore --src <backup-name> --dst <graph-name>` - restore one backup snapshot into a graph; the current command does not reject an existing destination graph
- `graph backup remove --src <backup-name>` - delete one backup snapshot
For any command that requires `--graph`, if the target graph does not exist, the CLI returns `graph not exists` (except for `graph create`). SQLite `graph import` fails if the target graph already exists; EDN import and `graph backup restore` do not currently share that top-level preflight.
Backup scope note:
- `graph backup create` copies only `db.sqlite`.
- `search-db.sqlite` and `client-ops-db.sqlite` are intentionally excluded.
- Desktop graph backups use the same `<root-dir>/graphs/<graph>/backup/<backup-name>/db.sqlite` layout, so the CLI can list, restore, and remove Desktop-created graph backups when it uses the same root directory.
Server commands:
- `server list` - list running db-worker-node servers
- `server cleanup` - manually terminate revision-mismatched CLI-owned db-worker-node servers discovered from lock files in the current root-dir
- `server start --graph <name>` - start db-worker-node for a graph
- `server stop --graph <name>` - stop db-worker-node for a graph
- `server restart --graph <name>` - restart db-worker-node for a graph
- `doctor [--dev-script]` - run runtime diagnostics for `db-worker-node.js`, `root-dir` permissions, and running server readiness (`--dev-script` checks `static/db-worker-node.js` explicitly)
Auth commands:
- `login` - authenticate this machine and create/update `~/logseq/auth.json`
- `logout` - remove persisted CLI auth from `~/logseq/auth.json`
Debug commands:
- `debug pull --id <db-id> [--graph <name>]` - pull a raw entity by db id with selector `[*]`
- `debug pull --uuid <uuid> [--graph <name>]` - pull a raw entity by block UUID lookup
- `debug pull --ident <db-ident> [--graph <name>]` - pull a raw entity by `:db/ident` lookup
- `--ident` must be a strict EDN keyword (for example `:logseq.class/Tag`)
- exactly one of `--id`, `--uuid`, or `--ident` is required
- if `--graph` is omitted, CLI falls back to current graph config
Utility commands:
- `completion <zsh|bash>` - generate shell completion script to stdout
- `example <command-or-prefix...>` - show runnable command examples for a command path or command prefix (phase 1 covers Graph Inspect and Edit commands)
- exact selector example: `logseq example upsert page`
- prefix selector example: `logseq example upsert`
- `skill show` - print built-in `logseq-cli` skill markdown to stdout
- always prints raw markdown text, even when `--output json` or `--output edn` is set
- `skill install` - install built-in skill to `./.agents/skills/logseq-cli/SKILL.md`
- `skill install --global` - install built-in skill to `~/.agents/skills/logseq-cli/SKILL.md`
Setup for zsh (add to `~/.zshrc`):
```bash
autoload -Uz compinit && compinit
eval "$(logseq completion zsh)"
```
Setup for bash (add to `~/.bashrc`):
```bash
eval "$(logseq completion bash)"
```
Skill command examples:
```bash
# Print markdown content to stdout
logseq skill show
# Install for current working directory
logseq skill install
# Install for current user home directory
logseq skill install --global
```
Server ownership behavior:
- `server stop` and `server restart` can return `server-owned-by-other` if the daemon was started by another owner source.
- `server start` can return `server-start-timeout-orphan` when lock creation times out and orphan matching processes are detected.
- Normal connection startup compares the discovered server revision with the local requester revision. Missing revision is treated as mismatch.
- On revision mismatch, startup attempts one graceful-first restart of the exact discovered server for the same repo/root-dir, even if the stale server has a different owner source. If the replacement still reports a different revision, startup fails fast and does not return an incompatible endpoint.
- Manual `server stop` and `server restart` keep owner protections; cross-owner stop is only used by the automatic revision-mismatch startup path after the target mismatch is proven.
- `server list` human output includes both `OWNER` and `REVISION` columns.
- `server list` prints a compatibility warning in human output when any server revision string is not exactly equal to the local CLI revision string.
- `server cleanup` remains a manual maintenance command. It checks discovered servers in the current root-dir, treats `revision != local CLI revision` (including missing revision) as mismatch, and attempts graceful-first termination only for `:owner-source :cli` targets.
- `server cleanup` structured output includes `checked`, `mismatched`, `eligible`, `skipped-owner`, `killed`, and `failed` summaries.
- Structured output (`--output json|edn`) includes per-server `revision` data but does not include human warning text.
Sync commands:
- `sync status --graph <name>` - show db-sync runtime state for a graph daemon
- `sync start --graph <name> [--e2ee-password <password>]` - start db-sync websocket client for a graph
- `sync stop --graph <name>` - stop db-sync client on a graph daemon
- `sync upload --graph <name>` - upload local graph snapshot to remote
- `sync download --graph <name> [--progress true|false] [--e2ee-password <password>]` - download remote graph `<name>` into a same-name local graph directory
- `sync asset download --graph <name> --id <asset-db-id>` - request one remote asset download by the `ID` shown by `list asset`
- `sync asset download --graph <name> --uuid <asset-uuid>` - request one remote asset download by asset block UUID
- `sync remote-graphs [--graph <name>]` - list remote graphs visible to the current login context
- `sync ensure-keys [--graph <name>]` - ensure user RSA keys for sync/e2ee
- `sync grant-access --graph <name> --graph-id <uuid> --email <email>` - grant encrypted graph access to a user
- `sync config set [--graph <name>] ws-url|http-base <value>` - set non-auth db-sync runtime config key
- `sync config get [--graph <name>] ws-url|http-base` - get non-auth db-sync runtime config key
- `sync config unset [--graph <name>] ws-url|http-base` - remove non-auth db-sync runtime config key
Sync start behavior:
- `sync start --e2ee-password <password>` verifies the password against user encrypted private key before persisting it.
- Verification and persistence run in worker-side sync crypt logic (shared with desktop/web interaction paths).
- Wrong `--e2ee-password` fails fast and does not overwrite a previously stored encrypted password payload.
Sync upload behavior:
- `sync upload` requires `--graph <name>`.
- The CLI starts or reuses that graph's `db-worker-node`, applies the current sync config, and uploads the local snapshot only after the worker has resolved a usable remote graph id.
- If the local graph already has sync metadata, upload reuses the stored remote `graph-id`.
- If the local graph does not have a stored remote `graph-id`, upload first lists visible remote graphs and reuses an exact same-name match when one exists.
- If no same-name remote graph exists, upload creates a new remote graph and persists the returned remote metadata locally before snapshot transfer.
- Successful upload persists graph identity metadata locally in both client-op state and graph KV (`logseq.kv/graph-uuid`, `logseq.kv/graph-remote?`, and `logseq.kv/graph-rtc-e2ee?`) so CLI and web upload/bootstrap flows stay aligned.
- Fresh uploads default to encrypted remote graph creation unless local sync metadata explicitly marks the graph as non-e2ee. In headless CLI mode, run `logseq login` first so refresh-token based E2EE password persistence can be used by follow-up `sync start`/`sync download` flows.
- `sync upload` returns a real error instead of false success when login state, remote graph bootstrap, or snapshot upload fails.
- Common upload failures include missing/invalid CLI login state, missing `http-base`, remote graph creation failure, snapshot upload failure, and local DB/worker startup failure.
- Troubleshooting: after a successful upload, run `graph info --graph <name> --output json` and confirm `data.kv.logseq.kv/graph-uuid` is present. If it is missing, rerun `sync upload` for the same graph to trigger identity backfill.
Sync download behavior:
- `sync download` requires `--graph <name>`.
- If a local graph with the same name already exists, the CLI returns `graph-exists`.
- If no remote graph with that name exists, the CLI returns `remote-graph-not-found`.
- `sync download` starts `db-worker-node` in create-empty mode so local startup does not write `db-initial-data` before snapshot import.
- The final snapshot download/import invoke uses a command-specific long-running timeout (30 minutes by default) rather than the generic short-request timeout path.
- Progress streaming uses db-worker-node SSE `/v1/events` and shared `:rtc.log/download` events.
- `--progress` defaults to `true` for human output.
- For structured output (`--output json|edn`), progress is auto-disabled unless explicitly overridden with `--progress true`.
- `--progress false` always suppresses progress streaming.
- If the target graph DB is not empty at download time, the CLI returns `graph-db-not-empty` and aborts before import.
- For e2ee remote graphs, provide `--e2ee-password` on `sync download` (or persist once via `sync start --e2ee-password`).
- If e2ee password is required but missing, `sync start`, `sync download`, and `sync status` return `e2ee-password-not-found` with a hint to provide `--e2ee-password`.
Sync asset download behavior:
- `sync asset download` requires `--graph` and exactly one of `--id` or `--uuid`.
- `--id` selects the asset node by the Datascript db/id shown as `ID` in `list asset` human output.
- `--uuid` selects the asset block UUID for scripts that already track UUIDs.
- The command requires sync to already be running for the graph. If the graph's sync client is not active, it returns `sync-not-started` with a hint to run `logseq sync start --graph <name>` first.
- The command uses the existing worker asset request API (`:thread-api/db-sync-request-asset-download`) and returns immediately after the worker accepts the enqueue request.
- Before enqueueing, the CLI checks the local `assets/<asset-uuid>.<asset-type>` file. If the file exists and its checksum matches asset metadata, the command reports `download-requested? false` and skips the request.
- If the local file exists but its checksum mismatches, the command reports `checksum-status mismatch`, prints a mismatch hint in human output, and requests a re-download.
- The first version does not accept `--e2ee-password`; persist E2EE password state with existing `sync start` or `sync download` flows before requesting asset download.
- Structured output includes asset identity and status fields such as `asset-id`, `asset-uuid`, `asset-type`, `download-requested?`, `checksum-status`, `skipped-reason`, and `hint` when applicable. It intentionally omits local filesystem paths.
Sync config persistence:
- `sync config set/unset` writes non-auth sync config to the CLI config file selected by `--config`.
- If `--config` is not provided, the default config path is `~/logseq/cli.edn`.
- `sync config get` reads from that same config source.
- `:e2ee-password` is not part of sync config and is silently ignored when found in legacy `cli.edn`.
- Cloud auth is persisted separately in `~/logseq/auth.json`.
E2EE password persistence locations:
- Browser runtime stores the refresh-token-encrypted password payload in its platform secret storage.
- Node runtime prefers the OS keychain under the `Logseq E2EE` service. If keychain access fails, it falls back to `<root-dir>/kv-store.json`. CLI E2E mode uses the KV store directly.
Inspect and edit commands:
- `list page [--expand] [--limit <n>] [--offset <n>] [--sort <field>] [--order asc|desc]` - list pages (defaults to `--sort updated-at --order desc`)
- `list tag [--expand] [--limit <n>] [--offset <n>] [--sort <field>] [--order asc|desc]` - list tags (defaults to `--sort updated-at --order desc`)
- `list property [--expand] [--limit <n>] [--offset <n>] [--sort <field>] [--order asc|desc]` - list properties (defaults to `--sort updated-at --order desc`; `TYPE` and `CARDINALITY` are included by default even without `--expand`; missing schema cardinality is treated as `one`)
- `list task [--status <status>] [--priority <low|medium|high|urgent>] [-c|--content <text>] [--fields <csv>] [--limit <n>] [--offset <n>] [--sort <field>] [--order asc|desc]` - list task nodes tagged with `#Task` (supports both pages and blocks; defaults to `--sort updated-at --order desc`)
- `--status` is validated at runtime using values from the current graph; invalid values return an error that includes available values from that graph.
- `list node [--tags <csv>] [--properties <csv>] [--fields <csv>] [--limit <n>] [--offset <n>] [--sort <field>] [--order asc|desc]` - list ordinary nodes (pages and blocks) filtered by tags/properties (supports selector forms id/uuid/ident/name; at least one of `--tags` or `--properties` is required; defaults to `--sort updated-at --order desc`)
- `--tags` and `--properties` use **all-of** semantics, and when both are present they are combined with **AND**.
- CSV tokens are trimmed and empty tokens are ignored; if a provided filter becomes empty after normalization, CLI returns `invalid-options`.
- `list asset [--fields <csv>] [--limit <n>] [--offset <n>] [--sort <field>] [--order asc|desc]` - list nodes tagged with `#Asset` (`:logseq.class/Asset`; defaults to `--sort updated-at --order desc`)
- `upsert block --content <text> [--target-page <name>|--target-id <id>|--target-uuid <uuid>] [--pos first-child|last-child|sibling]` - create blocks; defaults to today’s journal page if no target is given
- `upsert block --blocks <edn> [--target-page <name>|--target-id <id>|--target-uuid <uuid>] [--pos first-child|last-child|sibling]` - insert blocks via EDN vector
- `upsert block --blocks-file <path> [--target-page <name>|--target-id <id>|--target-uuid <uuid>] [--pos first-child|last-child|sibling]` - insert blocks from an EDN file
- `upsert block --id <id>|--uuid <uuid> [--content <text>] [--target-id <id>|--target-uuid <uuid>|--target-page <name>] [--pos first-child|last-child|sibling] [--update-tags <edn-vector>] [--update-properties <edn-map>] [--remove-tags <edn-vector>] [--remove-properties <edn-vector>]` - update and/or move a block
- `--status` is not supported on `upsert block`; use `upsert task --status ...` for task status updates.
- `upsert page --page <name> [--update-tags <edn-vector>] [--update-properties <edn-map>] [--remove-tags <edn-vector>] [--remove-properties <edn-vector>]` - create (or update by page name) a page
- `upsert page --id <id> [--update-tags <edn-vector>] [--update-properties <edn-map>] [--remove-tags <edn-vector>] [--remove-properties <edn-vector>]` - update a page by id (cannot be combined with `--page`)
- `upsert task --content <text> [--target-page <name>|--target-id <id>|--target-uuid <uuid>] [--pos first-child|last-child|sibling] [--status <status>] [--priority <low|medium|high|urgent>] [--scheduled <datetime>] [--deadline <datetime>] [--no-status] [--no-priority] [--no-scheduled] [--no-deadline]` - create a task block and ensure `#Task` is attached
- `upsert task --page <name> [--status <status>] [--priority <low|medium|high|urgent>] [--scheduled <datetime>] [--deadline <datetime>] [--no-status] [--no-priority] [--no-scheduled] [--no-deadline]` - create/update a task page and ensure `#Task` is attached
- `upsert task --id <id>|--uuid <uuid> [--status <status>] [--priority <low|medium|high|urgent>] [--scheduled <datetime>] [--deadline <datetime>] [--no-status] [--no-priority] [--no-scheduled] [--no-deadline]` - update an existing node and ensure `#Task` is attached
- `--status` is validated at runtime using values from the current graph; invalid values return an error that includes available values from that graph.
- generic task tag/property mutation options are not supported on `upsert task`; use `upsert block --update-tags/--update-properties/--remove-tags/--remove-properties` when needed.
- for the same field, set and clear options are mutually exclusive (for example: `--status todo --no-status` is invalid).
- `upsert asset --path <asset-file-path> [--content <text>] [--target-page <name>|--target-id <id>|--target-uuid <uuid>] [--pos first-child|last-child|sibling]` - create an asset node, add `#Asset`, set asset metadata (`type`, `size`, `checksum`), and copy the local file into graph `assets/` as `<block-uuid>.<ext>`
- `upsert asset --id <id>|--uuid <uuid> [--content <text>]` - update an existing asset node title; target node must be tagged with `#Asset`
- create mode requires `--path`; update mode rejects `--path`.
- `upsert tag --name <name>` - create or upsert a tag by name
- `upsert tag --id <id> [--name <name>]` - validate a tag by id; when `--name` is provided, rename that tag id (no-op if normalized name is unchanged)
- `upsert tag --id <id> --name <name>` conflicts: returns `tag-name-conflict` when target name is a non-tag page, and `tag-rename-conflict` when target name is another existing tag
- `upsert property --name <name> [--type <type>] [--cardinality one|many] [--hide true|false] [--public true|false]` - create or update a property by name
- `upsert property --id <id> [--type <type>] [--cardinality one|many] [--hide true|false] [--public true|false]` - update a property by id
- `move --id <id>|--uuid <uuid> --target-id <id>|--target-uuid <uuid>|--target-page <name> [--pos first-child|last-child|sibling]` - move a block and its children (defaults to first-child)
- `remove --id <id>|--uuid <uuid>|--page <name>` - remove blocks (by db/id or UUID) or pages
- `search block --content <query>` - search blocks by `:block/title` (case-insensitive substring)
- `search page --content <query>` - search pages by `:block/name` (case-insensitive substring)
- `search property --content <query>` - search properties by `:block/title` (Property entities only)
- `search tag --content <query>` - search tags by `:block/title` (Tag entities only)
- `query --query <edn> [--inputs <edn-vector>]` - run a Datascript query against the graph
- `query --name <query-name> [--inputs <edn-vector>]` - run a named query (built-in or from `cli.edn`)
- `query list` - list available named queries
- `show --page <name> [--level <n>]` - show page content tree
- Use `--page-hierarchy true` to display child pages connected through page hierarchy instead of normal page content blocks.
- `show --uuid <uuid> [--level <n>]` - show block tree
- `show --id <id> [--level <n>]` - show block tree by db/id
Help output:
```
Subcommands:
list page [options] List pages
list tag [options] List tags
list property [options] List properties
list task [options] List tasks
list node [options] List nodes
list asset [options] List assets
upsert block [options] Upsert block
upsert page [options] Upsert page
upsert task [options] Upsert task
upsert asset [options] Upsert asset
upsert tag [options] Upsert tag
upsert property [options] Upsert property
move [options] Move block
remove [options] Remove block or page
search block [options] Search blocks by title
search page [options] Search pages by name
search property [options] Search properties by title
search tag [options] Search tags by title
show [options] Show tree
```
Options grouping:
- Help output separates **Global options** (apply to all commands) and **Command options** (command-specific flags).
Version output:
- `logseq --version` prints:
```
Build time: <timestamp>
Revision: <commit>
```
Output formats:
- Global `--output <human|json|edn>` applies to all commands
- Output formatting is controlled via global `--output`, `:output-format` in config, or `LOGSEQ_CLI_OUTPUT`.
- Global `--profile` enables stage timing output to **stderr**. This is for debugging latency and does not change command stdout payloads.
- Human profile output is rendered as a tree (similar to `show` output style). The elapsed time column is printed at the far left with fixed width for alignment, for example:
```text
146ms command=list status=ok
stages
146ms └── cli.total
4ms ├── cli.parse-args
139ms └── cli.execute-action
129ms └── transport.invoke:thread-api/cli-list-pages
```
- Human output is plain text. List/search commands render tables with a final `Count: N` line. For list and search subcommands, the ID column uses `:db/id` (not UUID). If `:db/ident` exists, an `IDENT` column is included. `list property` includes dedicated `TYPE` and `CARDINALITY` columns; `list node`/`list asset` include a dedicated `TYPE` column (page/block) and page context columns for blocks. Search table columns are `ID` and `TITLE`. For `list page|tag|property|task|node|asset` in human output, the `TITLE` column is display-width-aware (CJK-safe), defaults to max width `40`, and truncates overflow with `…`; set `:list-title-max-display-width` in `cli.edn` to override. JSON/EDN outputs keep full titles (no truncation). Block titles can include multiple lines; multi-line rows align additional lines under the `TITLE` column. Times such as list `UPDATED-AT`/`CREATED-AT` and `graph info` `Created at` are shown in human-friendly relative form. Errors include error codes and may include a `Hint:` line. Use `--output json|edn` for structured output.
- `example` human output includes `Selector`, `Matched commands`, and `Examples` sections. Structured output (`json`/`edn`) includes `selector`, `matched-commands`, `examples`, and `message` fields under `data`.
- `skill show` always prints raw markdown text to stdout, regardless of `--output` mode.
- `sync download` progress lines are streamed to stdout only when progress is enabled. In `json`/`edn` mode, progress is disabled by default unless `--progress true` is provided.
- JSON machine output preserves namespaced keyword semantics:
- Namespaced keyword keys are emitted as canonical string keys in `namespace/name` form (for example `:block/title` -> `"block/title"`).
- Unqualified keyword keys remain plain strings (for example `:status` -> `"status"`).
- Keyword values are emitted as strings with namespace text preserved when present (for example `:db.cardinality/one` -> `"db.cardinality/one"`).
- UUID values are emitted as strings.
- For `list property`, `TYPE` and cardinality are returned in default output (without `--expand`) for human and structured (`json`/`edn`) formats.
- Human output renders cardinality as `one` or `many` in the `CARDINALITY` column.
- JSON keeps namespaced key/value form via `"db/cardinality"` and values like `"db.cardinality/one"` or `"db.cardinality/many"`.
- EDN keeps `:db/cardinality` (for example `:db.cardinality/one` or `:db.cardinality/many`).
- When a property omits schema cardinality, CLI treats it as default `one`.
JSON key migration (flat -> namespaced):
| Old JSON key path | New JSON key path |
| --- | --- |
| `data.items[].title` | `data.items[].block/title` |
| `data.items[].id` | `data.items[].db/id` |
| `data.items[].type` | `data.items[].logseq.property/type` |
| `data.items[].cardinality` | `data.items[].db/cardinality` |
| `data.root.children[]` | `data.root.block/children[]` |
- `upsert page`, `upsert block`, `upsert task`, and `upsert asset` return entity ids in `data.result` for JSON/EDN output, and include ids in human output.
- Human example:
```text
Upserted page:
[123]
```
- Human example:
```text
Upserted blocks:
[201 202]
```
- JSON example: `{"status":"ok","data":{"result":[123]}}`
- EDN example: `{:status :ok, :data {:result [123]}}`
- `doctor` output includes overall status (`ok`, `warning`, `error`) and per-check rows for `db-worker-script`, `data-dir`, `running-servers`, and `server-revision-mismatch`. For scripting, `--output json|edn` keeps the structured check payload.
- Common doctor failures and warnings:
- `doctor-script-missing`: `db-worker-node.js` runtime target is missing (default target: `dist/db-worker-node.js`; use `doctor --dev-script` to check `static/db-worker-node.js`).
- `doctor-script-unreadable`: script path exists but is not a readable file.
- `data-dir-permission`: configured data dir is not readable or writable.
- `doctor-server-not-ready`: one or more lock-discovered servers are still in `:starting` state (warning).
- `doctor-server-revision-mismatch`: one or more discovered servers use a different revision than the local CLI revision (warning). Follow the printed remediation command for each affected graph: `logseq server restart --graph <name>`.
- If bundled runtime startup fails with missing-module or missing-file errors, rebuild with `pnpm db-worker-node:release:bundle` and confirm `dist/db-worker-node.js` exists and every path listed in `dist/db-worker-node-assets.json` is present next to it.
- `query` human output returns a plain string (the query result rendered via `pr-str`), which is convenient for pipelines like `logseq query ... | xargs logseq show --id`.
- Built-in named queries currently include `block-search`, `task-search`, `recent-updated`, `list-status`, and `list-priority`. Use `query list` to see the full set for your config.
- Show output resolves block reference UUIDs inside text, replacing `[[<uuid>]]` with the referenced block content. Nested references are resolved recursively up to 10 levels to avoid excessive expansion. For example: `[[<uuid1>]]` → `[[some text [[<uuid2>]]]]` and then `<uuid2>` is also replaced.
- When `show` targets an ordinary block (`--id` or `--uuid`), human output prepends one breadcrumb line (`page > ... > nearest parent`) above the root block line. Each segment is display-width truncated to `24` with `…`.
```text
Project Alpha > Milestone 2026 > API rollout
5137 Implement retry policy for upload worker
5138 ├── Add timeout backoff guard
5139 └── Add deterministic retry test
```
- `show` tree lines print `:db/id` as the first column:
```text
id1 block1
id2 ├── b2
id3 │ └── b3
id4 ├── b4
id5 │ ├── b5
id6 │ │ └── b6
id7 │ └── b7
id8 └── b8
```
Troubleshooting:
- If authenticated sync commands fail with missing or invalid local auth, run `logseq logout` and then `logseq login` again.
- You can also manually remove `~/logseq/auth.json` and repeat `logseq login`.
Examples:
```bash
node ./dist/logseq.js login
node ./dist/logseq.js graph create --graph demo
node ./dist/logseq.js graph export --type edn --file /tmp/demo.edn --graph demo
node ./dist/logseq.js graph import --type edn --input /tmp/demo.edn --graph demo-import
node ./dist/logseq.js graph backup create --graph demo --name nightly
node ./dist/logseq.js graph backup list
node ./dist/logseq.js graph backup restore --src demo-nightly-20260101T000000Z --dst demo-restore
node ./dist/logseq.js graph backup remove --src demo-nightly-20260101T000000Z
node ./dist/logseq.js upsert block --target-page TestPage --content "hello world"
node ./dist/logseq.js move --uuid <uuid> --target-page TargetPage
node ./dist/logseq.js search block --content "hello"
node ./dist/logseq.js show --page TestPage --output json
node ./dist/logseq.js show --page Foo --page-hierarchy true
node ./dist/logseq.js debug pull --graph demo --ident :logseq.class/Tag --output json
node ./dist/logseq.js server list
node ./dist/logseq.js doctor
node ./dist/logseq.js doctor --dev-script
node ./dist/logseq.js doctor --output json
node ./dist/logseq.js --graph demo sync start --e2ee-password "my-secret"
node ./dist/logseq.js --graph demo sync download --e2ee-password "my-secret"
node ./dist/logseq.js logout
```
+214
View File
@@ -0,0 +1,214 @@
# OCaml CLI Bugs and Fixes
Last updated: 2026-07-01
This document tracks bugs found while using the OCaml Logseq CLI and the CLI sync stress workflow. The scope is split deliberately:
- OCaml CLI product bugs: code under `cli/lib` and tests under `cli/test`.
- CLI stress harness bugs: `scripts/cli-concurrent-edit-stress.mjs` and its tests.
- Sync/db-worker bugs exposed by CLI stress: root causes outside the OCaml CLI, but reproducible through CLI-driven concurrent editing.
For detailed sync stress logs and per-run evidence, see `docs/sync/failed-cases.md`.
## OCaml CLI Product Bugs
### Tag-name resolution failed for block tag updates
- Status: fixed.
- Symptom: `upsert block --update-tags '["cli-stress-tag-a"]'` failed before the outliner mutation with a Datascript parser error: `Cannot parse :find`.
- Reproduced by: `cli-test-5` during expanded CLI sync stress.
- Root cause: string tag-name resolution used a duplicated Datascript class query path. Numeric tag ids worked, but tag names failed.
- Fix: `cli/lib/upsert.ml`, `cli/lib/add.ml`, and `cli/lib/update.ml` now use the existing tag-list endpoint (`thread-api/cli-list-tags`) instead of the broken query path.
- Regression coverage: `cli/test/test_cases.ml` covers `upsert block --update-tags '["Tag A"]'`.
### Release CLI failed to reuse a starting db-worker-node
- Status: fixed.
- Symptom: concurrent CLI commands failed with `server-start-failed`, `failed to publish health`, or transient `fetch failed` while db-worker-node was already starting.
- Reproduced by: `cli-sync-stress-1000-20260701-1` and an earlier 5000-op stress attempt.
- Root cause: `cli/lib/server_runtime.ml` discovered existing workers only from successful `/healthz` responses. It treated HTTP 503 `starting` health payloads as absent, then did a one-shot final health lookup after spawning. Under concurrent CLI startup this could spawn duplicate workers or fail while the existing worker was almost ready.
- Fix: `cli/lib/server_runtime.ml` accepts both ready and starting health payloads for discovery, waits for readiness, respects the db-worker lock, and retries final health discovery before failing.
- Regression coverage: CLI parity tests cover reusing a starting db-worker-node and retrying final health discovery.
## CLI Stress Harness Bugs
These were not OCaml CLI product defects, but they affected our ability to reproduce real concurrent-edit bugs reliably.
### Local sync server was only checked, not started
- Status: fixed.
- Symptom: `--sync` failed immediately with `Local db-sync server is not healthy at http://127.0.0.1:18080/health`.
- Root cause: the harness required a local db-sync server but only performed a health check.
- Fix: the harness starts `cli-e2e/scripts/db_sync_server.py` automatically for local `--sync` runs unless `--no-start-sync-server` is passed.
- Regression coverage: JavaScript harness tests cover local sync server start arguments.
### Sync start ran before local upload/init
- Status: fixed.
- Symptom: `sync start` failed with `auth-refresh-failed`, `Run logseq login first`, and a local HTTP 404.
- Root cause: the graph was not initialized and uploaded to the local sync server before `sync start`.
- Fix: the harness checks `sync status`, prepares graph E2EE metadata when needed, runs `sync ensure-keys`, uploads the graph, then starts sync.
- Regression coverage: JavaScript harness tests cover local sync upload and ensure-key arguments.
### Stale block ids failed normal concurrent operations
- Status: fixed as harness classification.
- Symptom: concurrent move/update/delete operations failed with `source-not-found`, `target-not-found`, `block-not-found`, `page-not-found`, `recycled-page`, or `upsert-id-not-found`.
- Root cause: workers choose ids from a shared live-id pool; another worker can delete or recycle the same target before the selected operation runs.
- Fix: those outcomes are classified as expected race conflicts. The harness drops stale ids and refreshes the pool.
- Regression coverage: JavaScript harness tests cover stale id extraction and expected race classification.
### Volatile property/tag delete races stopped long runs
- Status: fixed as harness classification.
- Symptom: `property-delete-recreate` could fail with `property-not-found` or `ambiguous-property-name`; `tag-delete-recreate` could fail with `tag-not-found`.
- Root cause: the harness intentionally uses shared volatile property/tag names across workers. Under concurrent delete/recreate, name selectors can legitimately find zero or multiple entities.
- Fix: those delete-phase outcomes are classified as expected race conflicts.
- Regression coverage: JavaScript harness tests cover volatile property and tag race classifiers.
### Raw page operations reused shared mutable page targets
- Status: fixed in harness.
- Symptom: `thread-api/apply-outliner-ops` returned HTTP 200 with `resultTransit false` for raw `delete-page`, or nil for permanent recycle delete after a lost soft delete.
- Root cause: raw page delete/restore/recycle operations selected shared mutable pages, so other workers could delete or restore the same page while the operation was being verified. Some generated page titles were also only sequence-based and could collide across workers.
- Fix: raw create/delete/restore/recycle paths now use operation-owned unique page titles that include worker id, sequence, run id, and a UUID.
- Regression coverage: JavaScript harness tests cover `uniqueOperationPageTitle`.
### Retried stress run reused contaminated graph roots
- Status: documented as invalid test evidence.
- Symptom: a retry failed with stale invalid sync state from an earlier run.
- Root cause: the same graph/root/log path was reused after a failed run.
- Fix: fresh verification uses unique graph names and root directories; existing roots are not treated as fresh evidence.
## Sync/Db-Worker Bugs Exposed by CLI Stress
These were found through the OCaml CLI stress workflow but fixed outside the OCaml CLI layer.
### Duplicate `:block/uuid` after failed remote rebase
- Status: fixed.
- Symptom: `sync start` reached an open websocket but stopped on a stored `last-error`: duplicate `:block/uuid` unique constraint.
- Root cause: remote tx application with local changes used the live Datascript connection while reversing local txs, applying remote txs, and replaying locals. An exception could leave the live conn in an intermediate state.
- Fix: remote rebase uses `batch-transact-with-temp-conn!`; live state is committed only after the temp result succeeds.
- Regression coverage: worker db-sync tests cover invalid final rebase rejection and cardinality-one preservation.
### Temp rebase conn lost Datascript schema
- Status: fixed.
- Symptom: reverse/rebase could accumulate multiple `:block/parent` or `:block/order` values.
- Root cause: the temporary connection was created without the source DB schema, so cardinality-one replacement behavior was not preserved.
- Fix: temp conns are created with `(:schema db)` before swapping in the source DB.
- Regression coverage: deps/db and frontend worker tests cover cardinality-one preservation.
### Receive queue failures were invisible to `sync status`
- Status: fixed.
- Symptom: a receive-loop exception could stop remote application while `sync status` did not expose the error through `last-error`.
- Root cause: the receive queue catch path logged but did not update sync error state.
- Fix: receive queue failures now call `set-last-sync-error!`.
- Regression coverage: `receive-queue-failure-updates-last-sync-error-test`.
### Recycle restore/permanent-delete returned no observable apply result
- Status: fixed.
- Symptom: `apply-outliner-ops` could return HTTP 200 with nil/false result for recycle restore or permanent delete.
- Root cause: `logseq.outliner.op/apply-op!` did not set `*result` for `:restore-recycled` and `:recycle-delete-permanently`.
- Fix: both branches return their mutation result through `*result`.
- Regression coverage: `recycle-ops-return-apply-result-test`.
### Stale remote move before later remote delete failed after local reversal
- Status: fixed and stress verified.
- Symptom: remote apply failed with `Nothing found for entity id [:block/uuid ...]` while a later remote tx deleted that same block.
- Root cause: local reversal removed the moved block before the remote batch applied a stale move that was superseded by a later delete.
- Fix: remote apply skips stale operation datoms when the referenced block is already missing and the same remote batch deletes that block.
- Regression coverage: worker tests cover stale move-before-delete for both moved block and target block.
### Missing block after local reversal needed server repair
- Status: fixed and stress verified.
- Symptom: after offline journal races, remote apply failed on a missing block UUID that still existed on the server and had no later remote delete.
- Root cause: repair preflight checked against live DB before reversing local txs. The block became missing only after local reversal, so repair data was not fetched.
- Fix: remote apply performs an isolated dry-run of local reversal and fetches server repair data for refs that become missing only after reversal.
- Regression coverage: worker tests cover block repair after local reversal and adjacent repair/rebase cases.
### Rejected local tx stayed applied locally
- Status: fixed and stress verified.
- Symptom: all queues were empty and `last-error` was nil, but one client had a real checksum divergence and was missing blocks accepted by the server and other clients.
- Root cause: when the server rejected a local tx as non-recoverable, the client marked it failed and non-pending but did not roll back the optimistic local mutation.
- Fix: `tx/reject` handling now rolls back the rejected tx in a temp conn, then rebases later non-rejected pending txs.
- Regression coverage: focused `tx/reject` worker tests and fresh 5000-op stress.
### Idle sync status exposed stale or nil local checksum
- Status: fixed by targeted test and fresh stress verification.
- Symptom: `local-tx == remote-tx`, pending queues were zero, graph validation passed, but `sync status` showed a stale local checksum or `nil`.
- Root cause: sync status read the cached local checksum from client-ops metadata. When no later tx arrived, a stale or missing cache remained visible even though recomputing from the Datascript DB matched remote.
- Fix: idle `sync-counts` recomputes and updates the local checksum when pending queues are zero, tx positions match, and the cached checksum is nil or differs from remote.
- Regression coverage: `sync-counts-refreshes-idle-stale-local-checksum-test` covers stale string and nil values.
### Reversing queued parent insert orphaned existing children
- Status: fixed by targeted test and fresh 5000-op stress verification.
- Symptom: after reconnect, sync rebase reversed an earlier `insert-blocks` tx by retracting a parent while children still referenced it, causing `DB write failed with invalid data` and missing required `:block/parent`.
- Root cause: raw reverse tx-data for `:insert-blocks` could be narrower than the current local subtree. It retracted the parent but not current descendants that were not present in the reverse tx slice.
- Fix: `reverse-history-action!` expands `:insert-blocks` reverse retracts to include current descendants before retracting the parent.
- Regression coverage: `apply-remote-txs-reverses-parent-insert-with-existing-child-without-orphaning-test`.
### Pending tx snapshot drift during remote apply
- Status: fixed by targeted tests and fresh 5000-op stress verification.
- Symptom: a recovered severe `:db-sync/apply-remote-txs-failed` occurred when remote apply used pending txs from one snapshot and a temp DB copied after a later local delete.
- Root cause: remote apply captured pending txs first, then copied the live DB. A new pending local tx could land between those steps, so the temp DB no longer matched the local tx list being reversed.
- Fix: remote apply retries from fresh pending txs and current DB when either the failure itself is the internal `:pending-tx-snapshot-changed` control signal, or when an ordinary apply error happens while the pending tx snapshot still differs. This keeps missing-entity drift retryable without leaking the internal control signal into `last-error`.
- Regression coverage: `apply-remote-txs-rechecks-local-txs-when-local-delete-races-temp-snapshot-test`, `apply-remote-txs-delays-retry-when-local-txs-keep-changing-test`, and `apply-remote-txs-retries-snapshot-drift-even-if-pending-list-stabilizes-test`.
### Pending tx snapshot changed before temp remote apply commit
- Status: fixed by targeted tests and fresh 5000-op stress verification.
- Symptom: remote apply could successfully commit an older temp DB view over a new local page delete; the next permanent recycle delete returned nil because the page was no longer recycled.
- Root cause: remote apply protected only the exception path from stale pending snapshots. It did not recheck the pending tx id list just before committing the temp result to the live conn.
- Fix: `batch-transact-with-temp-conn!` accepts a `:before-commit` hook, and remote apply uses it to abort and retry if pending local tx ids changed.
- Regression coverage: worker test for temp-commit race, deps/db test for aborting live commit, and JavaScript harness tests for unique page targets.
### Concurrent validated transacts could lose writes
- Status: fixed by targeted test and fresh 5000-op stress verification.
- Symptom: a 5000-op run ended with one client missing property-history entities and task properties while the corresponding client-op had been persisted and ACKed.
- Root cause: validated `transact-sync` read `db`, ran `d/with`, validated, then committed with `reset! conn db-after`. If two validated transacts started from the same DB, the later reset could overwrite the earlier committed live DB state while the earlier tx was still stored as a client op.
- Fix: validated `transact-sync` now commits with `compare-and-set!`. If the live conn changed before commit, it recomputes and revalidates from the current DB. If validation failed against a stale DB, it retries instead of throwing the stale validation result.
- Regression coverage: `validated-transact-retries-when-live-conn-changes-before-commit-test`.
## Open or Diagnostic Cases
### Stored server checksum metadata drift
- Status: open.
- Symptom: clients and direct server recompute matched, but server `sync_meta.checksum` stored a stale value.
- Root cause: pending.
- Current diagnostic: an opt-in `DB_SYNC_CHECKSUM_ASSERT=true` path recomputes server checksum after each appended tx and throws if incremental metadata drifts. It has not reproduced the original drift yet.
### RTC closed with pending local changes after offline/resume
- Status: open.
- Symptom: `rtc-state` or `ws-state` becomes closed while local changes remain pending, and sync may not restart until manual start or app refresh.
- Root cause: pending. Candidate areas are explicit offline/stop races, stale closed-client reuse, and uncleared inflight state.
- Evidence: stress runs reproduced transient closed websocket states with pending local changes, but some later recovered without manual restart.
### Missing `local-tx` must not initialize to zero
- Status: existing fix documented.
- Symptom: old local graph/client-ops state can have missing `sync_meta.local-tx`.
- Root cause: treating missing `local-tx` as `0` forces the client to read too many server txs.
- Expected behavior: sync start skips with `:client-op-not-ready` until client-op metadata has a real integer `local-tx`.
- Regression coverage: restart tests cover skip behavior for missing `local-tx`.
## Current Verification Snapshot
- JavaScript stress harness tests: `rtk node --test scripts/cli-concurrent-edit-stress.test.mjs scripts/cli-sync-stress-workflow.test.mjs` passed with 30 tests.
- Focused worker db-sync regression tests for parent insert reverse, pending snapshot retry, idle checksum refresh, stale remote move/delete, validated transact CAS, and retryable snapshot drift `last-error` pollution passed.
- `rtk pnpm db-worker-node:release:bundle` rebuilt `static/db-worker-node.js`.
- Fresh 5000-op CLI sync stress on graph `cli-sync-stress-5000-20260701-snapshot-last-error-1` completed `5001` started ops with 3 clients, offline simulation, auto-created journal races, HTTP outliner ops, undo/redo, insert/delete/move-heavy traffic, matching final checksum `5790fdbc975a6b36` on all clients, and final `graph validate` passing on all clients.
- The latest 5000-op event log had no `sync-start-runtime-error`, `pending-tx-snapshot-changed`, `apply-remote-txs-failed`, fatal event, error-level event, or checksum mismatch marker.
+139
View File
@@ -0,0 +1,139 @@
## Intro
Thanks for helping improve Logseq translations.
This guide is for contributors who translate existing UI text or add missing
translations for a locale. It is not the guide for changing application code,
inventing dictionary keys, or rewriting the English source text in
`src/resources/dicts/en.edn`.
If the English wording or key name is wrong, ask a developer to update
`en.edn` and follow [the key naming guide](i18n-key-naming.md).
## Setup
To run the commands in this doc, install
[Babashka](https://github.com/babashka/babashka#installation).
## Where Translations Live
Translation dictionaries live under
[src/resources/dicts/](https://github.com/logseq/logseq/blob/master/src/resources/dicts/).
Each locale has its own EDN file, for example `es.edn`.
`en.edn` is the source of truth for keys and English text. Most translation
contributors only need to edit their locale file.
## Find Missing Translations
To see the overall translation status of every locale:
```sh
bb lang:list
```
That table includes `:untranslated-count`, which shows how many English keys
are still missing for each locale, and `:same-as-en-count`, which helps you
spot locales that still contain entries copied from English.
To see which entries are missing for one locale, use `es` as an example:
```sh
bb lang:missing es
```
To print copy/paste-ready entries:
```sh
bb lang:missing es --copy
```
That command prints the missing keys and the current English value so you can
paste them into your locale file and translate them there.
## Find Entries Still Matching English
To list them for one locale, use `es` as an example:
```sh
bb lang:pseudo es
```
This is a review tool, not a hard error. Some entries may legitimately match
English, but many are unfinished translations copied from `en.edn`.
## Edit a Locale
1. Run `bb lang:missing <locale>`.
2. Add the missing keys to `src/resources/dicts/<locale>.edn`.
3. Save the file.
4. Run `bb lang:missing <locale>` again until the list is empty or contains
only entries you want to leave for later.
Missing keys are allowed. Logseq falls back to English automatically, so do not
copy English into your locale file just to make the list shorter.
### Editing Tips
- Translate the complete sentence or label owned by the key. Do not rename keys
or split one sentence across multiple keys.
- If the English value is a plain string, keep your locale value a plain
string.
- Keep placeholders exactly aligned with English, for example `{1}` and `{2}`.
- If the English value uses hiccup or `(fn ...)`, keep the same outer shape and
translate only the user-visible strings inside it. If changing that structure
seems necessary, ask a developer for help.
- Preserve emoji and icon glyphs from `en.edn` exactly, but use punctuation
that is natural for your language.
- If a sentence is already correct in your language without plural logic, use a
plain string. Do not add function logic just because English does.
## Fix Mistakes
Run this before submitting translation changes:
```sh
bb lang:validate-translations
```
It checks for:
- translation keys referenced from code that do not exist in `en.edn`
- locale keys that do not exist in `en.edn`
- dictionary keys that are no longer used
- placeholder mismatches such as `{1}` vs `{2}`
- locale entries that no longer match an English rich-translation shape
`bb lang:validate-translations` does not flag entries that still match English.
Use `bb lang:pseudo <locale>` when you want to review those separately.
To remove stale or invalid keys automatically:
```sh
bb lang:validate-translations --fix
```
`--fix` removes invalid or unused keys. It does not repair placeholder mistakes
or rewrite rich translations for you.
After editing dictionary files, run:
```sh
bb lang:format-dicts
```
This restores the repo's canonical key ordering and namespace spacing.
You do not need `bb lang:lint-hardcoded` for translation-only work. That
command is for developers who are editing UI code.
## Add a Language
To add a new language:
1. Add an entry to `frontend.dicts/languages`.
2. Create a new file under `src/resources/dicts/` and name it after the locale,
for example `zz.edn`.
3. Add that file to `frontend.dicts/dicts`.
4. Use the `bb lang:missing <locale>` workflow to populate translations.
5. Run `bb lang:validate-translations` and `bb lang:format-dicts`.
+547
View File
@@ -0,0 +1,547 @@
## Description
This page describes development practices for this codebase.
## Linting
Most of our linters require babashka. Before running them, please [install babashka](https://github.com/babashka/babashka#installation). To invoke all the linters in this section, run
```sh
bb lint:dev
```
### Clojure code
To lint:
```sh
clojure -M:clj-kondo --parallel --lint src
```
We lint our Clojure(Script) code with https://github.com/clj-kondo/clj-kondo/. If you need to configure specific linters, see [this documentation](https://github.com/clj-kondo/clj-kondo/blob/master/doc/linters.md). Where possible, a global linting configuration is used and namespace specific configuration is avoided.
For engineers, there is a faster version of this command that only checks files that you have changed: `bb lint:kondo-git-changes`.
There are outstanding linting items that are currently ignored to allow linting the rest of the codebase in CI. These outstanding linting items should be addressed at some point:
* Comments starting with `TODO:lint`
* Code marked with `#_:clj-kondo/ignore` require a good understanding of the context to address as they usually involve something with a side effect or require changing multiple fns up the call stack.
### Unused vars
We use https://github.com/borkdude/carve to detect unused vars in our codebase.
To run this linter:
```sh
bb lint:carve
```
By default, the script runs in CI mode which prints unused vars if they are
found. The script can be run in an interactive mode which prompts for keeping
(ignoring) an unused var or removing it. Run this mode with:
```sh
bb lint:carve '{:interactive true}'
```
When a var is ignored, it is added to `.carve/ignore`. Please add a comment for
why a var is ignored to help others understand why it's unused.
### Large vars
Large vars have a lot of complexity and make it hard for the team to maintain
and understand them. To run this linter:
```sh
bb lint:large-vars
```
To configure the linter, see the `[:tasks/config :large-vars]` path of bb.edn.
### Document namespaces
Documentation helps teams share their knowledge and enables more individuals to contribute to the codebase. Documenting our namespaces is a good first step to improving our documentation. To run this linter:
```sh
bb lint:ns-docstrings
```
To skip documenting a ns, use the common `^:no-doc` metadata flag.
### Datalog linting
We use [datascript](https://github.com/tonsky/datascript)'s datalog to power our
modeling and querying layer. Since datalog is concise, it is easy to write
something invalid. To avoid typos and other preventable mistakes, we lint our
queries and rules. Our queries are linted through clj-kondo and
[datalog-parser](https://github.com/lambdaforge/datalog-parser). clj-kondo will
error if it detects an invalid query.
### Translations
We use [tongue](https://github.com/tonsky/tongue) for translations.
Responsibilities are split across a few files:
* [docs/contributing-to-translations.md](./contributing-to-translations.md) is
for locale contributors.
* [docs/i18n-key-naming.md](./i18n-key-naming.md) is for naming and reusing
keys in `src/resources/dicts/en.edn`.
* [.i18n-lint.toml](../.i18n-lint.toml) is the source of truth for hardcoded UI
text lint scope, translatable helpers/attributes, exclusions, and allowlists.
#### What must be internationalized
Inside the scope defined by `.i18n-lint.toml`, all user-visible UI text must be
internationalized.
Exceptions:
* Console output does not need translation.
* Keep out-of-scope developer-only `(Dev)` labels next to the developer
UI/command definition; do not add them to translation dictionaries.
If you introduce a new UI helper, alert API, UI namespace, translatable
attribute, or other shipped UI surface, update `.i18n-lint.toml` so the lint
continues to cover it.
#### Translation helpers
All translation helpers live in
`src/main/frontend/context/i18n.cljs`. Do not add parallel ad hoc i18n helpers
elsewhere.
| Helper | Use for |
|---|---|
| `t` | Standard translation with preferred-locale lookup |
| `tt` | Try multiple keys and return the first existing translation |
| `t-en` | Force English output, for example when UI text also needs an English console copy |
| `interpolate-rich-text` / `interpolate-rich-text-node` | Replace placeholders with rich-text or hiccup fragments |
| `interpolate-sentence` | Keep a full sentence in one key while inserting placeholders and inline links |
| `replace-newlines-with-br` | Render translated newline characters as `[:br]` nodes |
| `locale-join-rich-text` / `locale-join-rich-text-node` | Join rich fragments with locale-aware separators |
| `locale-format-number` / `locale-format-date` / `locale-format-time` | Format dynamic numbers and dates before passing them into translations |
#### Developer workflow
1. Use `.i18n-lint.toml` to decide whether the text is in i18n scope.
2. Search `src/resources/dicts/en.edn` for an existing key with the same
semantic owner and textual role.
3. If no exact match exists, follow
[the key naming guide](./i18n-key-naming.md) and add the English source text
to `en.edn`.
4. Add non-English locale entries only when you are also providing actual
translations. When renaming or removing keys, clean up stale locale keys.
5. Replace the literal with the appropriate helper from
`frontend.context.i18n`.
Recommended checks:
```sh
bb lang:validate-translations
bb lang:lint-hardcoded --git-changed
bb lang:format-dicts
```
`bb lang:format-dicts` is the repo-owned formatter for dictionary key ordering
and namespace spacing. Run it after editing dict files.
#### Content rules
* Keep each translation as complete as possible. Do not assemble sentences from
fragments in the caller.
* For plain dynamic text, use placeholders like `{1}` and pre-format arguments
in the caller before passing them to `t`.
* Function-valued translations are allowed only when a locale needs real logic
or rich-text hiccup output. When functions are necessary, only `str`, `when`,
`if`, and `=` are allowed inside the function body.
* Keep rich text in a single translation entry. Do not split one sentence
across multiple keys.
* Non-English locale files should contain only actual translations. Do not copy
English values just to fill gaps; Tongue falls back to `:en`.
* Preserve emoji/icon glyphs from `en.edn` exactly, and use punctuation natural
to each locale.
* Pluralization is locale-specific. Do not force English singular/plural rules
onto other languages.
### Spell Checker
We use [typos](https://github.com/crate-ci/typos) to spell check our source code.
To install it locally and use it:
```sh
$ brew install typos-cli
# Catch any errors
$ typos
# Fix errors
$ typos -w
```
To configure it e.g. for dealing with false positives, see `typos.toml`.
### Separate Worker from Frontend
The worker and frontend code share common code from deps/ and `frontend.common.*`. However, the worker should never depend on other frontend namespaces as it could pull in libraries like React which cause it to fail hard. Likewise the frontend should never depend on worker namespaces. Run this linter to ensure worker and frontend namespaces don't require each other:
```
$ bb lint:worker-and-frontend-separate
Valid worker namespaces!
Valid frontend namespaces!
```
## Testing
We have unit, performance and end to end tests.
### End to End Tests
Even though we have a nightly release channel, it's hard for testing users (thanks to the brave users!) to notice all issues in a limited time, as Logseq is covering so many features.
To run end to end tests, see [clj-e2e tests](/clj-e2e/README.md).
### Unit Testing
Our unit tests use the [shadow-cljs test-runner](https://shadow-cljs.github.io/docs/UsersGuide.html#_testing). To run them:
```bash
pnpm test
```
By convention, a namespace's tests are found at a corresponding namespace
of the same name with an added `-test` suffix. For example, tests
for `frontend.db.model` are found in `frontend.db.model-test`.
There are a couple different ways to run tests:
* [Focus tests](#focus-tests) - Run one or more tests from the CLI
* [Autorun tests](#autorun-tests) - Autorun tests from the CLI
* [Repl tests](#repl-tests) - Run tests from REPL
There a couple types of tests and they can overlap with each other:
* [Database tests](#database-tests) - Tests that involve a datascript DB.
* [Performance tests](#performance-tests) - Tests that aim to measure and enforce a performance characteristic.
* [Async tests](#async-tests) - Tests that run async code and require some helpers.
#### Focus Tests
Tests can be selectively run on the commandline using our own test runner which
provides the same test selection options as [cognitect-labs/test
runner](https://github.com/cognitect-labs/test-runner#invoke-with-clojure--m-clojuremain).
For this workflow:
1. Run `clj -M:test watch test` in one shell
2. Focus tests:
1. Add `^:focus` metadata flags to tests e.g. `(deftest ^:focus test-name ...)`.
2. In another shell, run `node static/tests.js -i focus` to only run those
tests. To run all tests except those tests run `node static/tests.js -e focus`.
3. Or focus namespaces: Using the regex option `-r`, run tests for `frontend.db.query-dsl-test` with `node static/tests.js -r query-dsl`.
Multiple options can be specified to AND selections. For example, to run all `frontend.db.query-dsl-test` tests except for the focused one: `node static/tests.js -r query-dsl -e focus`
For help on more options, run `node static/tests.js -h`.
#### Autorun Tests
To run tests automatically on file save, run `clojure -M:test watch test
--config-merge '{:autorun true}'`. Specific namespace(s) can be auto run with
the `:ns-regexp` option e.g. `clojure -M:test watch test --config-merge
'{:autorun true :ns-regexp "frontend.db.query-dsl-test"}'`.
#### REPL tests
Most unit tests e.g. ones that are browser compatible and don't require node libraries, can be run from the REPL. To do so:
* Start a REPL for your editor. See [here for an example](https://github.com/logseq/logseq/blob/master/docs/develop-logseq.md#repl-setup).
* Load a test namespace.
* Run `(cljs.test/run-tests)` to run tests for the current test namespace.
#### Database tests
To write a test that uses a datascript db:
* Be sure your test ns has test fixtures from `test-helper` ns to create and
destroy test databases after each test.
* The easiest way to set up test data is to use `test-helper/load-test-files`.
* For the repo argument that most fns take, pass it `test-helper/test-db`
#### Performance tests
To write a performance test:
* Use `frontend.util/with-time-number` to get the time in ms.
* Example:
```clojure
(are [x timeout] (>= timeout (:time (util/with-time-number (block/normalize-block x true))))
... )
```
For examples of these tests, see `frontend.db.query-dsl-test` and `frontend.db.model-test`.
#### Async Tests
Async unit testing is well supported in ClojureScript.
https://clojurescript.org/tools/testing#async-testing is a good guide for how to
do this. We have a couple of test helpers that make testing async easier:
- `frontend.test.helper/deftest-async` - `deftest` for async tests that ensures
uncaught exceptions don't abruptly end the test suite. If you don't use this
macro for async tests, you are expected to handle unexpected failures in your test
- `frontend.test.helper/with-reset` - A version of `with-redefs` that works for
async contexts
## Accessibility
Please refer to our [accessibility guidelines](accessibility.md).
## Logging
For logging, we use https://github.com/lambdaisland/glogi. When in development,
be sure to have [enabled custom
formatters](https://github.com/binaryage/cljs-devtools/blob/master/docs/installation.md#enable-custom-formatters-in-chrome)
in the desktop app and browser. Without this enabled, most of the log messages
aren't readable.
## Data validation and generation
We use [malli](https://github.com/metosin/malli) and
[spec](https://github.com/clojure/spec.alpha) data validation, fn validation
(and generation someday). malli has the advantage that its schema is data and
can be used for additional purposes.
Reusable malli schemas should go under `src/main/frontend/schema/` and be
compatible with clojure and clojurescript. See
`frontend.schema.handler.plugin-config` for an example.
Reusable specs should go under `src/main/frontend/spec/` and be compatible with
clojure and clojurescript. See `frontend.spec.storage` for an example.
By following these conventions, these should also be usable by babashka. This is
helpful as it allows for third party tools to be written with logseq's data
model.
### Optionally Validating Functions
We use [malli](https://github.com/metosin/malli) for optionally validating fns
a.k.a instrumenting fns. Function validation is enabled in dev mode. To add
typing for a fn, just add it to a var's metadata [per this
example](https://github.com/metosin/malli/blob/master/docs/function-schemas.md#function-schema-metadata).
We also have clj-kondo type annotations derived from these fn schemas. To
re-generate them after new schemas have been added, update the namespaces in
`gen-malli-kondo-config.core` and then run `bb dev:gen-malli-kondo-config`. To
learn more about fn instrumentation, see [this
page](https://github.com/metosin/malli/blob/master/docs/clojurescript-function-instrumentation.md).
## Auto-formatting
Currently the codebase is not formatted/indented consistently. We loosely follow https://github.com/bbatsov/clojure-style-guide. [cljfmt](https://cljdoc.org/d/cljfmt/) is a common formatter used for Clojure, analogous to Prettier for other languages. You can do so easily with the [Calva](https://marketplace.visualstudio.com/items?itemName=betterthantomorrow.calva) extension in [VSCode](https://code.visualstudio.com/): It will (mostly) indent your code correctly as you type, and you can move your cursor to the start of the line(s) you've written and press `Tab` to auto-indent all Clojure forms nested under the one starting on the current line.
## Naming
We strive to use explicit names that are self explanatory so that our codebase is readable and maintainable. Sometimes we use abbreviations for frequently occurring concepts. Some common abbreviations:
* `rpath` - Relative path e.g. `logseq/config.edn`
* `fpath` - Full path e.g. `/full/path/to/logseq/config.edn`
## Development Tools
### Babashka tasks
There are a number of bb tasks under `dev:` for development. Some useful ones to
point out:
* `dev:validate-repo-config-edn` - Validate a repo config.edn
```sh
bb dev:validate-repo-config-edn deps/common/resources/templates/config.edn
```
* `dev:publishing` - Build a publishing app for a given graph dir. If the
publishing frontend is out of date, it builds that first which takes time.
Subsequent runs are quick.
```sh
# One time setup
$ cd scripts && pnpm install && cd -
# Build a release publishing app
$ bb dev:publishing /path/to/graph-dir tmp/publish
# OR build a dev publishing app that watches frontend changes
$ bb dev:publishing /path/to/graph-dir tmp/publish --dev
# View the publishing app in a browser
$ python3 -m http.server 8080 -d tmp/publish &; open http://localhost:8080
# Rebuild the publishing backend for dev/release.
# Handy when making backend changes in deps/publishing or
# to test a different graph
$ bb dev:publishing-backend /path/graph-dir tmp/publish
```
There are also some tasks under `nbb:` which are useful for inspecting database
changes in realtime. See [these
docs](https://github.com/logseq/bb-tasks#logseqbb-tasksnbbwatch) for more info.
#### DB Graph Tasks
These tasks are specific to database graphs. For these tasks there is a one time setup:
```sh
$ cd deps/db && pnpm install && cd ../outliner && pnpm install && cd ../graph-parser && pnpm install && cd ../..
```
* `dev:db-cli` - Run a CLI command from deps/db using latest deps/db code
* `dev:query` - Query a DB graph
```sh
$ bb dev:query woot '[:find (pull ?b [*]) :where (block-content ?b "Dogma")]'
DB contains 833 datoms
[{:block/tx-id 536870923, :block/link #:db{:id 100065}, :block/uuid #uuid "65565c26-f972-4400-bce4-a15df488784d", :block/updated-at 1700158508564, :block/order "a0", :block/refs [#:db{:id 100064}], :block/created-at 1700158502056, :block/tags [#:db{:id 100064}], :block/title "Dogma #[[65565c2a-b1c5-4dc8-a0f0-81b786bc5c6d]]", :db/id 100090, :block/parent #:db{:id 100051}, :block/page #:db{:id 100051}}]
```
* `dev:transact` - Run a `d/transact!` against the queried results of a DB graph
```sh
# The second arg is a datascript like with db-query. The third arg is a fn that is applied to each query result to generate transact data
$ bb dev:transact
Usage: $0 GRAPH-DIR QUERY TRANSACT-FN
# First use the -n flag to see a dry-run of what would happen
$ bb dev:transact test-db '[:find ?b :where [?b :block/title "say wut"]]' '(fn [id] (vector :db/add id :block/title "say woot!"))' -n
Would update 1 blocks with the following tx:
[[:db/add 169 :block/title "say woot!"]]
With the following blocks updated:
(#:block{:title "say wut"})
# When the transact looks good, run it without the flag
$ bb dev:transact test-db '[:find ?b :where [?b :block/title "say wut"]]' '(fn [id] (vector :db/add id :block/title "say woot!"))'
Updated 1 block(s) for graph test-db!
```
Run the dev command `Replace graph with its db.sqlite file` to use the updated graph in the desktop app.
* `dev:create` - Create a DB graph given a `sqlite.build` EDN file
First in Electron, create the name of the graph you want create e.g. `inferred`.
Then:
```sh
bb dev:create inferred deps/db/script/create_graph/inferred.edn
Generating 11 pages and 0 blocks ...
Created graph inferred!
```
Finally, upload this created graph with the dev command: `Replace graph with
its db.sqlite file`. You'll be switched to the graph and you can use it!
* `dev:import` and `dev:import-many` - Imports a file graph to DB graph, for one or many graphs
```sh
# Import the local test graph with the debug option
$ bb dev:import deps/graph-parser/test/resources/exporter-test-graph test-file-graph -d
Importing 43 files ...
...
# Import and validate multiple file graphs and write them to ./out/
$ bb dev:import-many /path/to/foo /path/to/bar -d
Importing ./out/foo ...
Importing 321 files ...
Valid!
Importing ./out/bar ...
Importing 542 files ...
Valid!
```
* `dev:datoms` and `dev:diff-datoms` - Save a db's datoms to file and diff two datom files
```sh
# Save a current datoms snapshot of a graph
$ bb dev:datoms woot w2.edn
# After some edits, save another datoms snapshot
$ bb dev:datoms woot w3.edn
# Diff the two datom snapshots
# This snapshot correctly shows an added block with content "b7" and a property using a closed :default value
$ bb dev:diff-datoms w2.edn w3.edn
[[]
[[162 :block/title "b7" 536871039 true]
[162 :block/created-at 1703004379103 536871037 true]
[162 :block/page 149 536871037 true]
[162 :block/parent 149 536871037 true]
[162 :block/refs 108 536871043 true]
[162 :block/refs 160 536871043 true]
[162
:block/uuid
#uuid "6581c8db-a2a2-4e09-b30d-cdea6ad69512"
536871037
true]]]
# By default this task ignores commonly changing datascript attributes.
# To see all changed attributes, tell the task to ignore a nonexistent attribute:
$ bb dev:diff-datoms w2.edn w3.edn -i a
[[[nil nil 536871029 536871030]
[nil nil 1702998192728 536871029]
[nil nil 536871035 536871036]
[nil nil 1703000139716 536871035]
[nil nil 149 536871033]
[nil nil 536871035 536871036]]
[[nil nil 536871041 536871042]
[nil nil 1703004384793 536871041]
[nil nil 536871039 536871040]
[nil nil 1703004380918 536871039]
[nil nil 162 536871037]
[nil nil 536871037 536871038]
[162 :block/title "b7" 536871039 true]
[162 :block/created-at 1703004379103 536871037 true]
[162 :block/order "a0" 536871037 true]
[162 :block/page 149 536871037 true]
[162 :block/parent 149 536871037 true]
[162 :block/refs 108 536871043 true]
[162 :block/refs 160 536871043 true]
[162 :block/tx-id 536871043 536871044 true]
[162 :block/updated-at 1703004380918 536871039 true]
[162
:block/uuid
#uuid "6581c8db-a2a2-4e09-b30d-cdea6ad69512"
536871037
true]]]
```
### Dev Commands
In the app, you can enable Dev commands under `Settings > Advanced > Developer
mode`. Then search for commands labeled with `(Dev)`. Those labels are
intentionally hardcoded English developer-only labels, not translation keys.
Commands include inspectors for block/page data and AST.
### Desktop Developer Tools
Since the desktop app is built with Electron, a full set of Chromium developer
tools is available under the menu `View > Toggle Developer Tools`. Handy tools
include a JS console and HTML inspector.
## Security Practices
* Our builds should not include unverified, third-party resources as this opens
up the app to possibly harmful injections. If a third-party resource is
included, it should be verified against an official distributor. Use
https://github.com/logseq/logseq/pull/9712 as an example to include a third
party resource and not the examples under resources/js/.
## FAQ
If dev app launch failed after electron upgrade:
```sh
pnpm install
pnpm watch
```
In another window:
```sh
cd static
pnpm install
cd ..
pnpm dev-electron-app
```
and kill all electron process
Then a normal start happens via `pnpm dev-electron-app`
+91
View File
@@ -0,0 +1,91 @@
# iOS development
## Installation
- Install Xcode 13 from App Store.
- Install [CocoaPods](https://cocoapods.org/)
```shell
sudo gem install cocoapods
```
Note: use the following commands from *ios/App* directory to fix **ffi_c.bundle** related issue for M1 MacBook [^1].
(Working directory: `ios/App`)
```shell
arch -x86_64 sudo gem install ffi
arch -x86_64 pod install
```
## Set up development environment
### Build the development app
- Generate the local HTTPS certificate used by Shadow CLJS:
```shell
bb dev:mobile-https-cert
```
- Install `ssl/mobile-dev/logseq-dev-ca.cer` on the iOS device and enable full trust for it in iOS Settings.
- Working directory: Logseq root directory
- Run `LOGSEQ_SHADOW_HTTPS=true pnpm mobile-watch` from the logseq project root directory in terminal.
- Run `LOGSEQ_APP_SERVER_URL=https://your-local-ip-address:3002/mobile/ pnpm exec cap sync ios` in another terminal to copy web assets from public to *ios/App/App/public*, create *capacitor.config.json* in *ios/App/App*, and update iOS plugins.
- Connect your iOS device to MacBook.
- Run `pnpm exec cap open ios` to open Logseq project in Xcode, and build the app there.
or, you can run `bb dev:ios-app` to generate the certificate, start the HTTPS mobile watcher, sync iOS with the HTTPS dev-server URL, and open Xcode. To download bb, see https://github.com/babashka/babashka#installation. Also, in order to use mobile bb tasks on macOS, `gsed` needs to be installed in your system (run `brew install gnu-sed` to install).
Note: if the dev build isn't reflecting the change of code, restart `pnpm mobile-watch` and run `pnpm exec cap sync ios` again.
### Build the release app
- Comment out `server` section above in **capacitor.config.ts**.
- Connect your iOS device to MacBook.
- Run `pnpm run-ios-release` to install the release app to your iOS device.
or, you can run `bb release:ios-app` to do those steps with one command.
[^1] https://github.com/CocoaPods/CocoaPods/issues/10220#issuecomment-730963835
# Android development
## Installation
- Install Android studio [^1] and SDK (newer than 30) tools
Note: for M1 MacBook users.
- Download version **Mac with Apple Chip**
- unzip it and move **Android Studio.app** file to **Applications**, or you will get the following error later.
```
[error] Unable to launch Android Studio. Is it installed?
Attempted to open Android Studio at: /Applications/Android Studio.app
You can configure this with the CAPACITOR_ANDROID_STUDIO_PATH environment variable.
```
- In Android Studio, open **Tools** -> **SDK Manager** to install other SDK tools [^2].
> In the SDK Tools tab, make sure to install at least the following:
>> - Android SDK Build-Tools
>> - Android SDK Command-line Tools
>> - Android Emulator
>> - Android SDK Platform-Tools
## Set up development environment
### Build the development app
- Run `pnpm install && pnpm mobile-watch` from the logseq project root directory in terminal.
- Run `LOGSEQ_APP_SERVER_URL=https://your-local-ip-address:3002/mobile/ pnpm exec cap sync android` in another terminal.
- Run `pnpm exec cap run android` to install app into your device.
or, you can run `bb dev:android-app` to do those steps with one command if you are on macOS.
Then,
- In Android Studio, open **Tools** -> **AVD Manager** to create Android Virtual Device (AVD), and launch it in the emulator.
- In Android Studio, open **Run** -> **Run** to run Logseq.
- After logseq startup in Android virtual device, repl should be able to connect
- For browser console print and devtool remote debug, open chrome, type url chrome://inspect/#devices, you should see your device there, click inspect
### Build a release and install it to your android device
- Comment out `server` section above in **capacitor.config.ts**.
- Connect your device to PC.
- Run `pnpm run-android-release`.
or, you can run `bb release:android-app` to do those steps with one command.
### Build an apk
- Comment out `server` section above in **capacitor.config.ts**.
- Run `pnpm run-android-release`
or, you can run `bb release:android-app` to do those steps with one command.
Then,
- In Android Studio, open **Build** -> **Build Bundles / APKs** -> **Build APKs**.
- Get your apk in `android/app/build/apk/debug`.
+74
View File
@@ -0,0 +1,74 @@
# Setup Logseq development dependencies on Windows
This is a guide on setting up Logseq development dependencies on Windows. Once these dependencies are installed, you can follow the [develop-logseq](develop-logseq.md) docs for build instructions.
## [scoop](https://scoop.sh/)
Scoop provides a `clojure.exe` shim which works in Command Prompt and Powershell windows.
```
scoop bucket add scoop-clojure https://github.com/littleli/scoop-clojure
scoop bucket add extras
scoop bucket add java
scoop install java/openjdk clj-deps babashka leiningen nodejs-lts
```
## Winget
Winget is a package manager installed by default on windows.
```
winget install --id CoreyButler.NVMforWindows
nvm install 18
nvm use 18
npm install -g pnpm
winget install --id Microsoft.OpenJDK.17
winget install --id Microsoft.VisualStudio.2022.Community
```
An installer for clojure is available from [casselc/clj-msi](https://github.com/casselc/clj-msi/releases/)
## [chocolatey](https://chocolatey.org/)
Chocolatey installs Clojure as a PowerShell module and alias, and does not provide `clojure` for `cmd.exe`.
[@andelf has written a wrapper utility](https://github.com/andelf/clojure-cli) which you can install with `cargo install --git https://github.com/andelf/clojure-cli.git` instead.
```
choco install nvm
nvm install 18
nvm use 18
npm install -g pnpm
choco install visualstudio2022community
choco install javaruntime
choco install clojure
```
## Troubleshooting
### Configuring a proxy for internet access
```
$env:GLOBAL_AGENT_HTTPS_PROXY='http://<proxy-host>:<proxy-port>'
$env:ELECTRON_GET_USE_PROXY='true'
$env:HTTPS_PROXY='http://<proxy-host>:<proxy-port>'
$env:HTTP_PROXY='http://<proxy-host>:<proxy-port>'
```
### node-gyp cannot find visual studio
During the build process `node-gyp` may complain that it cannot find Visual Studio. Try building the app in Developer Powershell for VS(shipped with Visual Studio). If this does not work for you, [This issue](https://github.com/nodejs/node-gyp/issues/2203) may be helpful.
### Set up Clojure CLI repository mirror
add the following pair to `deps.edn`:
```
:mvn/repos {
"central" {:url "https://maven.aliyun.com/repository/public"}
"clojars" {:url "https://mirrors.tuna.tsinghua.edu.cn/clojars"}
}
```
The mirrors above are friendly to Chinese developers(with bad network), developers with self-hosted repositories can use their own services.
+173
View File
@@ -0,0 +1,173 @@
# Develop Logseq
## Requirements
- [Node.js](https://nodejs.org/en/download/) (See [build.yml](https://github.com/logseq/logseq/blob/master/.github/workflows/build.yml) for allowed version) & [pnpm](https://pnpm.io/installation)
- [Java & Clojure](https://clojure.org/guides/getting_started). (If you run into `Execution error (FileNotFoundException) at java.io.FileInputStream/open0 (FileInputStream.java:-2). -M:cljs (No such file or directory)`, it means you have a wrong Clojure version installed. Please uninstall it and follow the instructions linked.)
## Clone project
This is a required step before doing any development or production builds.
```bash
git clone https://github.com/logseq/logseq
cd logseq
```
## Browser development
### Development
```bash
pnpm install
pnpm watch
```
Then open the browser <http://localhost:3001>.
### REPL setup
#### VSCode + Calva
With ```pnpm watch``` running, it should prints ``shadow-cljs - nREPL server started on port 8701``
You may connect to the nREPL server with:
``cmd + shift + p`` -> ``Calva: Connect to a Running REPL Server in the Project`` -> ``logseq`` -> ``shadow-cljs``->``:app`` ->``localhost:8701``
(change ``:app`` to ``:electron`` if you want to connect to the main thread of the Electron app)
Open a dev environment (Browser dev app on ``localhost:3000`` or Desktop dev app), then you can play REPL on the current editing file:
``cmd + shift + p`` -> ``Calva: Load/Evaluate Current File and its Requires/Dependencies``
#### Connect to the web-worker context
##### Emacs + Cider
When connecting to a CLJ nrepl (NOTE: if you are already in a CLJS nrepl, use `:cljs/quit` to go back to CLJ nrepl),
you may run `(shadow.user/worker-repl)`, or use `(shadow/nrepl-select :app {:runtime-id <id-num>})` to connect to a web-worker context.
> [!TIP]
> you can find the `<id-num>` in http://localhost:9630/runtimes
##### Intellij Idea/Cursive-ide
The setup is almost same as Calva except it requires switching REPL from CLJ to CLJS manually.
1. Start nrepl with ```pnpm watch```, wait until it prints ``shadow-cljs - nREPL server started on port 8701``
2. Create a new remote REPL run configuration:
- Connection type: nREPL
- Context module: logseq
- :radio_button: Use port from file with localhost
- :radio_button: Use standard port file
3. Start the remote REPL, now you are in CLJ REPL instead of target CLJS REPL
4. In the REPL, execute ```(shadow.cljs.devtools.api/repl :app)```
5. Verify you are in CLJS REPL by executing ```(js/alert "hello world")```, it should show an alert dialog in the browser window
> [!WARNING]
> You need open the browser dev app (http://localhost:3001) before executing step 5, otherwise it will throw an error:
>
> ```No available JS runtime. See https://shadow-cljs.github.io/docs/UsersGuide.html#repl-troubleshooting=> nil```
### Production Build
```bash
pnpm release
```
The released files will be at `static/` directory.
## Desktop app development
### Development
1. Install npm packages for building the desktop app
``` bash
pnpm install
cd static
pnpm install
cd ..
```
2. Compile to JavaScript and open the dev app
```bash
pnpm watch
# Wait until watch reports `Build Completed.` for `:electron` and `:app`.
# Then, run the following command in a different shell.
# If you have opened desktop logseq, you should close it. Otherwise, this command will fail.
pnpm dev-electron-app
```
Alternatively, run `bb dev:electron-start` to do this step with one command. To
download bb, see https://github.com/babashka/babashka#installation.
3. (Optional) Update dependencies if `resources/package.json` has changed since
the last time you used dev Logseq.
```bash
# pull new changes
git pull
cd static && pnpm install && cd ..
```
Here `static/` is generated by `pnpm watch` command.
### Production Build
Build a release:
```bash
pnpm release-electron
```
The final released binaries or installers will be at `static/out/`.
## DB sync
DB sync can be run locally in one of two ways as described in the following
sections. To use a local sync approach, the app must be built with
`$ENABLE_DB_SYNC_LOCAL` e.g. `ENABLE_DB_SYNC_LOCAL=true pnpm watch`. For more
about db sync, see [its readme](/deps/db-sync/README.md).
### DB sync Cloudflare Worker adapter
Build and run a Cloudlare worker locally
```bash
cd deps/db-sync
pnpm install
pnpm release
# This migration is a one time setup
cd worker && wrangler d1 migrations apply DB --local && cd -
pnpm dev
```
When testing
### DB sync Node adapter (self-hosted)
Build and run the Node.js adapter for self-hosted DB sync.
```bash
cd deps/db-sync
pnpm install
DB_SYNC_PORT=8787 \
COGNITO_ISSUER=https://cognito-idp.us-east-2.amazonaws.com/us-east-2_kAqZcxIeM \
COGNITO_CLIENT_ID=1qi1uijg8b6ra70nejvbptis0q \
COGNITO_JWKS_URL=https://cognito-idp.us-east-2.amazonaws.com/us-east-2_kAqZcxIeM/.well-known/jwks.json \
pnpm build:node-adapter
DB_SYNC_PORT=8787 \
COGNITO_ISSUER=https://cognito-idp.us-east-2.amazonaws.com/us-east-2_kAqZcxIeM \
COGNITO_CLIENT_ID=1qi1uijg8b6ra70nejvbptis0q \
COGNITO_JWKS_URL=https://cognito-idp.us-east-2.amazonaws.com/us-east-2_kAqZcxIeM/.well-known/jwks.json \
pnpm start:node-adapter
```
Optional environment variables:
- DB_SYNC_DATA_DIR (defaults to data/db-sync)
Notes:
- The Cognito values above match `ENABLE_DB_SYNC_LOCAL=true pnpm watch` default auth config.
- For production builds, use the production Cognito pool values from `src/main/frontend/config.cljs`.
+80
View File
@@ -0,0 +1,80 @@
# Logseq Docker Web App Guide
From v0.5.6, Logseq is also available as a Docker image of Web App.
The Docker image is available at [ghcr.io/logseq/logseq-webapp:latest](https://github.com/logseq/logseq/pkgs/container/logseq-webapp).
> **Note**
> Logseq web app uses [File System Access API](https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API) to access the file system. You need a [compatible browser](https://caniuse.com/native-filesystem-api).
> Also, an HTTPS connection is required if you are accessing it remotely.
## Simple one-line start(local machine)
```shell
docker pull ghcr.io/logseq/logseq-webapp:latest
docker run -d --rm -p 127.0.0.1:3001:80 ghcr.io/logseq/logseq-webapp:latest
```
Open the browser and go to <http://localhost:3001>.
## Remote(non-local) access
Here we use the [mkcert](https://github.com/FiloSottile/mkcert) to generate locally-trusted development certificates. For other purposes, you should apply a certificate from a trusted CA.
Suppose you are deploying the web app to 192.168.11.95.
### Install mkcert(web app of Filesystem API requires HTTPS)
```shell
# macOS
brew install mkcert
# or archlinux
sudo pacman -Ss mkcert
# or follow the install instructions from https://github.com/FiloSottile/mkcert
```
### Install mkcert root CA
```shell
mkcert -install
```
### Prepare SSL cert
```shell
mkcert 192.168.11.95 # public IP address or hostname of the remote machine
```
### Prepare SSL Nginx conf
```nginx
# ssl.conf
server {
listen 443 ssl;
ssl_certificate /etc/nginx/certs/192.168.11.95.pem;
ssl_certificate_key /etc/nginx/certs/192.168.11.95-key.pem;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
```
### Pull Docker image
Copy the `*.key` and `ssl.conf` files to target machine.
```shell
docker pull ghcr.io/logseq/logseq-webapp:latest
docker run -d --rm -p 8443:443 -v `pwd`:/etc/nginx/certs -v ./ssl.conf:/etc/nginx/conf.d/ssl.conf ghcr.io/logseq/logseq-webapp:latest
```
> **Note**
> The above command will expose the web app to the public network, which is not recommended and may cause security issues.
> Please make sure the firewall is configured properly.
### Done!
Open your browser and navigate to `https://192.168.11.95:8443`.
+710
View File
@@ -0,0 +1,710 @@
# Logseq i18n Key Naming Standard
## Purpose
This document defines how to name new i18n keys in `src/resources/dicts/en.edn`.
Goal: given any new user-facing string, this document should let you determine
its key name directly.
Secondary goal: keep prefixes converged. A name that is slightly less "pure" but
stays inside an existing owner is usually better than creating a new low-density
root or singleton dotted subdomain.
This standard is intended to be deterministic. After applying it, you should be
able to choose one reasonable key name. If you still cannot determine the name,
treat that as a gap in the standard rather than guessing:
- AI agents must stop and ask for human guidance.
- Developers are encouraged to report the gap to the Logseq team so the standard
can be clarified.
Audience:
- developers adding or renaming English keys
- AI agents reviewing or generating i18n changes
Non-English locale contributors should not invent or rename keys. They should
use [contributing-to-translations.md](contributing-to-translations.md) instead.
This document is only about key naming and reuse. Rules for placeholders,
hiccup, punctuation, locale fallback, linting, and helper selection live in
[dev-practices.md](dev-practices.md).
Developer-only `(Dev)` labels are out of scope for this document. Keep them as
inline English labels next to the developer UI/command definition instead of
adding translation keys.
## Key Shape
Use this shape:
```clojure
:<root>[.<subdomain>]/<leaf>
```
Rules:
- `<root>` chooses the semantic owner
- `<subdomain>` is optional and used only for a stable subfeature, workflow, or
representation
- `<leaf>` describes the text's role inside that owner
- `<root>` names are singular semantic owners
- All segments use kebab-case
Examples:
```clojure
:ui/close
:page.delete/confirm-title
:nav.all-pages/title
:settings.editor/show-brackets
:plugin.install-from-file/success
:view.table/sort-ascending
:cmdk.action/open
:mobile.toolbar/undo
```
## Before Naming a New Key
1. Search `src/resources/dicts/en.edn`.
2. Reuse a key only when both match:
- semantic owner
- textual role
3. If the English text matches but the owner or role differs, create a new key.
Examples:
- toolbar `"Bold"` and command `"Bold"` are different keys
- dialog `"Close"` and window `"Close"` are different keys
- reusable `"Copied!"` feedback may share a `notification/*` key only when it is
intentionally cross-domain
## Step 1: Choose the Owner
The namespace must be chosen by owner, not by file path, not by component name,
and not by where the text happens to be rendered.
There are only 5 owner classes.
### 1. Interaction Systems
Use when the text belongs to an interaction registry or interaction subsystem.
| Namespace | Use for |
|---|---|
| `command.*` | Built-in command descriptions |
| `shortcut.category` | Shortcut help categories |
| `keymap` | Keybinding editor text |
| `cmdk` | Command palette text |
Use this class when:
- the text is attached to a command id
- the text names a shortcut group
- the text belongs to rebinding/conflict/chord UI
- the text belongs only to command palette behavior
For `command.*` keys:
- the subdomain is the command group name
- for built-in command descriptions, mirror the command id namespace even when
the command opens another surface or workflow; the owner is still the command
registry entry
- use a stable semantic group name, not an implementation placeholder
- avoid new opaque or self-referential groups such as `command.command`
- `command.command-palette/*` is valid for descriptions attached to
`:command-palette/*` ids; reserve `cmdk.*` for command-palette UI copy itself
Examples:
```clojure
:command.editor/bold
:command.graph/open
:command.page/toggle-favorite
:command.shell/run
:shortcut.category/block-editing
:keymap/search-placeholder
:cmdk.action/open
```
### 2. Shared Primitives
Use only when the wording keeps the same meaning across unrelated domains.
| Namespace | Use for |
|---|---|
| `ui` | Generic actions and states |
| `nav` | Global destinations and route-level constraints |
| `notification` | Reusable cross-feature feedback and notification-center shell controls |
| `search` | Generic search vocabulary |
| `select` | Generic picker vocabulary |
| `format` | Formatting vocabulary |
| `color` | Color vocabulary |
Qualification rules:
- removing product context does not change the meaning
- the wording can be reused in multiple unrelated domains
- the wording does not name a specific entity or workflow
- the wording stays natural with the same grammatical role across locales; if
callers need different inflection, gender, number, part of speech, or
label-vs-status behavior, do not force one shared key just because English
matches
- if the text names a product entity such as `graph`, `page`, or `server`, use
that product domain instead
- do not use `notification` for feature-specific toast text just because it is
shown via `notification/show!`; the delivery mechanism does not determine
owner
Examples:
```clojure
:ui/close
:ui/save
:nav/home
:notification/copied
:search/no-result
:select/default-prompt
:format/bold
:color/red
```
### 3. Product Domains
This is the default class. Most keys should be here.
Use when the text belongs to a first-class product feature, entity, or workflow.
The 5 groups below are taxonomy buckets, not a priority order. Do not infer
ownership priority from subsection order. When multiple product domains seem
plausible, use the conflict rules below.
#### 3.1 Workspace and content domains
- `graph`
- `file`
- `page`
- `block`
- `node`
- `journal`
- `library`
- `date`
- `editor`
- `reference`
- `property`
- `class`
- `view`
- `query`
- `icon`
- `asset`
- `pdf`
- `flashcard`
#### 3.2 Data movement and publishing domains
- `import`
- `export`
- `publish`
#### 3.3 Customization, AI, and extensibility domains
- `settings`
- `theme`
- `plugin`
- `ai`
- `youtube`
- `zotero`
- `server`
- `storage`
`ai` is a reserved owner for future built-in AI feature UI. Current AI-related
settings copy may still live under `settings.ai/*`.
#### 3.4 Account, cloud, and security domains
- `account`
- `sync`
- `collaboration`
- `encryption`
#### 3.5 Support, diagnostics, and lifecycle domains
- `onboarding`
- `help`
- `bug-report`
- `shell`
- `profiler`
- `updater`
- `deeplink`
#### Product domain boundaries
Use this table to resolve common conflicts.
| Namespace | Owns | Does not own |
|---|---|---|
| `graph` | Graph lifecycle, graph switching, graph-level state, graph visualization entry points | Individual pages, blocks, raw files |
| `file` | Raw file browser, file metadata, file-level errors | Graph switching, page semantics, import workflow |
| `page` | Page metadata and page-level workflows | Active editing mechanics |
| `block` | Block as stored content entity | Active editing session behavior |
| `node` | Generic node vocabulary intentionally shared across page/block/tag/property-like entities | Page-only, block-only, property-only, or class-only workflows |
| `editor` | Active authoring behavior: selection, cursor actions, paste, heading changes, inline creation | Command registry text, page metadata, property schema |
| `journal` | Journal-only behavior | Generic page behavior |
| `library` | Library page copy and library-specific add/remove flows | Generic page search or generic page metadata outside the library feature |
| `date` | Relative-date vocabulary, natural-language date phrases, and date-only labeling/parsing copy | Journal-only workflows, editor command registries |
| `reference` | Backlinks, linked references, block refs, page refs | Generic search or editing text |
| `property` | Property schema, values, choices, dialogs, validation | Query semantics and result presentation |
| `class` | Class/tag schema and class-specific configuration | Generic property schema |
| `query` | Query definition, query source, query inputs, live-query semantics | Table sorting, grouping, row selection |
| `view` | Result presentation, table controls, grouping, sorting, columns, selection, representation modes | Query source semantics or property schema |
| `icon` | Icon picker, emoji/icon browsing, icon-search tabs and counts | Generic search vocabulary or generic select/picker wording outside icon picking |
| `asset` | Attachments and embedded media assets | Generic file browser or export |
| `pdf` | PDF viewer and PDF-specific reading/annotation behavior | Generic asset browsing or generic reference behavior |
| `flashcard` | Card review, card study flow, card-specific review UI | Generic editor actions or generic query/view controls |
| `import` | Import workflows, import source parsing, import options, and import-specific validation/feedback | Export, publish, or generic file browser wording |
| `export` | Export workflows, export format/options, export progress, and export-specific feedback | Import flows, publish lifecycle, or generic file browser wording |
| `publish` | Publish and unpublish flows, publish access settings, and publish status/failure messages | Generic export formats/backups, sync state, or account identity |
| `settings` | Built-in settings shell copy: settings sections, built-in setting labels, descriptions, and feedback about changing built-in settings | Child feature workflows or subsystem state merely rendered inside settings |
| `theme` | Theme selection and theme-specific customization | Generic settings |
| `plugin` | Plugin lifecycle, marketplace, plugin configuration, install/update/remove flows | Built-in settings or theme selection |
| `ai` | Semantic search, embedding model selection, model download states, and other built-in AI feature UI | Generic settings scaffolding or non-AI search vocabulary |
| `youtube` | YouTube-specific embed and timestamp behavior | Generic asset/video wording or generic mobile warnings |
| `zotero` | Built-in Zotero integration, Zotero attachment access, Zotero-linked or imported file affordances, and Zotero-specific defaults | Generic file browser, generic import/export, or plugin lifecycle |
| `server` | Local HTTP API, MCP, local server setup and diagnostics | Cloud sync or account identity |
| `storage` | Local persistence, sqlite/local-db storage errors, recycle UI and recycle storage constraints | Cloud sync lifecycle or file browser UI |
| `account` | Login, identity, plan, membership, billing-facing account state, and account-authentication actions such as resetting the account password | Graph sync state or passwords/keys that gate encrypted data |
| `sync` | Graph sync, storage usage, invitations, remote graph lifecycle | Login identity or password management |
| `collaboration` | Collaborators, participants, collaboration-only permissions and presence | Generic sync storage accounting |
| `encryption` | Passwords, keypairs, encrypted graph access, and key reset flows for encrypted data | Login/billing identity state or account-authentication actions |
| `onboarding` | First-run setup and initial import/graph setup | General settings or ongoing help |
| `help` | Help hub copy: documentation, handbook, shortcut help, and community/support entry points | Child workflows launched from help, such as bug-reporting |
| `bug-report` | Bug reporting, diagnostics, issue helpers | General help navigation |
| `shell` | Built-in shell command runner UI and its workflow | Built-in command descriptions or generic terminal wording outside the shell runner feature |
| `profiler` | Built-in profiling and diagnostics UI for developers or advanced users | Bug reporting copy, generic settings, or runtime performance logs |
| `updater` | App-release update lifecycle: checking, availability, download/install progress, restart/install actions, and updater-specific errors/status | Settings-shell copy, plugin-update UI, or other container/entry-point copy |
| `deeplink` | `logseq://` or deep-link open flows and deep-link resolution errors | Generic navigation labels or route names |
#### Product domain conflict rules
When multiple product domains could plausibly own the same text, apply these
rules in order:
1. Choose the narrowest stable owner that names the feature, entity,
integration, or workflow itself.
2. Container or hub owners own only their own shell copy. They do not own child
feature copy just because it is rendered there.
3. Status, progress, result, validation, and error copy belongs to the subsystem
or workflow emitting that state.
4. Render location, launch point, or current screen does not determine owner.
5. If the same feature text can appear in multiple places, keep one
feature-owned key instead of forking container-specific duplicates.
Conflict examples:
```clojure
:settings.general/check-for-updates
:updater/checking-for-updates
:help.shortcuts/title
:bug-report.inspector/title
```
More product-domain examples:
```clojure
:page/delete
:page.validation/name-no-hash
:page.convert/cant-be-block
:editor/remove-heading
:editor.slash/node-reference
:date.nlp/today
:node/built-in-cant-delete-error
:property/default-value
:view.table/sort-ascending
:plugin/install
:settings.editor/show-brackets
:sync/invitation-sent
:encryption/reset-password
:bug-report.inspector/title
```
### 4. Shell Surfaces
Use only when the meaning depends on the shell surface itself.
| Namespace | Use for |
|---|---|
| `header` | Header-only actions and labels |
| `sidebar.left` | Left sidebar shell affordances |
| `sidebar.right` | Right sidebar shell affordances |
| `context-menu` | Context menu-only affordances |
| `window` | Window chrome actions |
Use this class when:
- moving the text to another surface would change its meaning
- the text describes pane controls, sidebar controls, or window chrome
- the text is not reused in another surface or runtime with the same meaning
Do not use a surface namespace for:
- feature titles rendered inside a surface
- route or destination labels rendered inside a surface
- domain workflows that happen to be launched from a surface
- text that already appears with the same meaning in another surface; move it to
`ui`, `nav`, or the feature owner
Examples:
```clojure
:header/go-back
:sidebar.left/favorites
:sidebar.right/close
:context-menu/set-icon
:window/minimize
```
### 5. Platform Runtimes
Use only when the text exists because one runtime has a unique implementation.
| Namespace | Use for |
|---|---|
| `mobile` | Mobile-only runtime behavior |
| `electron` | Electron-only runtime behavior |
Use this class when:
- the workflow exists only on one runtime
- the wording refers to a native/runtime-only capability
Examples:
```clojure
:mobile.tab/graphs
:mobile.settings/version
:electron/new-window
:electron/add-to-dictionary
```
## Step 2: Apply the Decision Tree
Choose the first matching branch and stop.
1. Is the text owned by an interaction system? Use `command.*`,
`shortcut.category`, `keymap`, or `cmdk`.
2. Is the text a shared primitive reused across unrelated domains? Use `ui`,
`nav`, `notification`, `search`, `select`, `format`, or `color`.
3. Is the text owned by a product domain? Use the matching product domain
namespace. If multiple product domains seem possible, apply `Product domain
conflict rules` and then stop.
4. Is the text owned by a shell surface? Use `header`, `sidebar.left`,
`sidebar.right`, `context-menu`, or `window`.
5. Is the text runtime-exclusive? Use `mobile` or `electron`.
If none fits, define a new product domain only when the feature has a clear,
long-lived product boundary. Otherwise, keep the nearest existing product domain
and use a more specific leaf.
## Owner Constraints
- Do not create roots from implementation modules or component files such as
`outliner`, `content`, or `views`.
- Do not create plural owner roots such as `flashcards` or `views`. Use the
singular owner.
- Do not use implementation acronyms such as `e2ee` when the product-facing
owner is `encryption`.
- Do not use implementation state holders such as `state` as owners. Use the
semantic feature owner such as `journal.default-query/*`.
- Do not use a surface owner for a destination label. Use `nav/*` or the feature
owner.
- Do not use a container or hub owner such as `settings` or `help` for child
feature text just because the feature is rendered there.
- Do not use a validator or storage engine as owner for a domain rule.
Validation copy belongs to the constrained domain.
- Treat a new root with fewer than ~5 plausible near-term keys as a smell, not a
goal. Small roots are acceptable only when they name a first-class product
feature, entity, or integration with a clear independent boundary.
- When keeping a new root, update this taxonomy in the same change so the
standard stays aligned with `src/resources/dicts/en.edn`.
- Not every existing key in `en.edn` is a good naming precedent. Prefer this
standard even when some legacy keys remain unchanged for compatibility.
Examples:
```clojure
:reference.filter/title
:help.handbook/title
:page.validation/name-blank
:property.choice/already-exists
:class.validation/extends-cycle
```
## Established Namespace Notes
These namespaces already exist in `en.edn` and are acceptable patterns, but
they have specific reuse guidance.
| Namespace | Status | Guidance |
|---|---|---|
| `property.built-in`, `class.built-in` | Intentional | Stable built-in schema vocabularies under the `property` and `class` owners. |
| `block.macro`, `property.repeat-recur-unit` | Intentional | Stable representation/enum groups. This pattern is acceptable when the subdomain names a real user-facing concept. |
## Step 3: Decide Whether a Subdomain Is Needed
Use a dotted subdomain only for one of these 4 cases.
### 1. Stable section
Examples:
```clojure
:nav.all-pages/title
:settings/account
:settings.editor/show-brackets
```
### 2. Stable workflow
Examples:
```clojure
:page.delete/confirm-title
:page.delete/warning
:page.delete/success
:plugin.install-from-file/title
:editor.slash/group-basic
```
### 3. Stable representation or mode
Examples:
```clojure
:view.table/default-title
:view.table/sort-ascending
:mobile.toolbar/undo
:server.status/running
:cmdk.action/open
```
### 4. Stable validator, conversion, or settings section
Examples:
```clojure
:page.validation/name-no-hash
:page.convert/cant-be-block
:property.choice/already-exists
:settings/account
:help.shortcuts/title
```
Rules:
- use `.validation/` when the message is the direct result of a validation
check, constraint violation, or failed precondition
- use an existing workflow subdomain such as `.convert/` or `.delete/` for
workflow-specific actions, confirmations, and blockers
- do not create a narrower workflow-variant subdomain when an existing workflow
already owns the text
- for built-in settings tab labels, use flat keys such as `:settings/general`;
reserve `:settings.<section>/*` for copy inside that settings section
- choose compact concept names for subdomains; do not copy a long UI label
phrase into a subdomain when a shorter stable concept name exists
- prefer a flat key when the dotted subdomain would only contain one string for
now
- if an owner already has a flat canonical key for the concept, prefer flat
role-suffixed siblings such as `about-title` or `auto-update-check-feedback`
over introducing a dotted subdomain just to add another role
- a flat leaf with a structured suffix such as `about-title` or `terms-title` is
acceptable when the same owner already needs the base leaf such as `about` or
`terms` for a different role, and creating a dotted singleton namespace would
be worse
- create a new dotted subdomain only when at least one of these is true:
- the namespace already has sibling keys
- the workflow or section clearly needs multiple roles such as `title` +
`desc`, `confirm-title` + `confirm-desc`, or `empty` + `empty-desc`
- the flat leaf would become less readable than the dotted form
- a prefix with 2 to 4 keys is often healthy; the main smell is a singleton
dotted subdomain shape such as `help.about/*` or `graph.delete-local/*`
Good examples:
```clojure
:page.convert/tag-to-page-action
:page.convert/tag-to-page-confirm-desc
:property.validation/invalid-name
:help/about-title
:help/about
:graph/delete-local-confirm-desc
```
Do not use a subdomain for:
- component names
- implementation names
- generic layout slices
- words like `main`, `section`, `btn`, or `modal` when they are only
implementation layout terms and not real user-facing modes, surfaces, or
scopes
Bad shapes for new keys:
- `:<owner>.main/*`
- `:command.command/*`
## Step 4: Choose the Leaf
The leaf describes the text's role inside its owner.
### 1. Canonical labels
Use a bare subject or action when the text is the canonical label itself.
Examples:
```clojure
:ui/save
:page/backlinks
:property/default-value
:plugin/install
```
### 2. Structured role suffixes
Use these suffixes consistently.
| Suffix | Use for |
|---|---|
| `title` | Panel, section, page, dialog, modal title |
| `desc` | Supporting description |
| `label` | Control, nav, picker, or form label when it is not the title |
| `prompt` | Short picker or flow prompt |
| `placeholder` | Input placeholder |
| `hint` | Short inline help |
| `tip` | Advice or explanatory tip |
| `tooltip` | Hover text |
| `empty` | Empty-state heading or label |
| `empty-desc` | Empty-state description |
| `confirm-title` | Confirmation title |
| `confirm-desc` | Confirmation body |
| `success` | Success feedback |
| `error` | Error feedback |
| `warning` | Warning feedback |
| `feedback` | Neutral or severity-agnostic feedback |
| `count` | Parameterized count text |
| `action` | Action label when a bare verb would be ambiguous |
Additional rules:
- use `desc`, not `description`, for the textual role suffix
- this does not ban the literal word `Description` when it is the product term
being named
- use `prompt`, not `message`, for short chooser, picker, or action-sheet
instructions
- use `label` when the text prefixes an inline value such as an ID, date, or
selected item
- do not split one sentence into `*-prefix` and `*-suffix` keys; keep a single
translation entry and insert links, shortcuts, or styled fragments with
placeholders
- use `error` or `warning` for failure feedback; prefer `*-error` or `*-warning`
over `*-failed`
- for success, error, and warning feedback, prefer an action or condition stem
such as `update-success`, `unpublish-error`, or `invalid-date-warning` instead
of past-tense English like `updated` or `failed`
- do not mechanically shorten a leaf just because one word also appears in the
owner; keep the action or condition name when it distinguishes a workflow or
condition inside that owner, for example `:publish/publish-error`,
`:import/zip-import-error`, or `:date/invalid-date-warning`
- use `feedback` when the same toast or callout may appear with varying
severity, or when the severity is incidental to the wording
- use `status` only when the text names a status field, status value, or status
representation in the product model; do not use `status` as a catch-all suffix
for post-action toasts
- when the base concept is already a fixed product term, keep it intact even if
the role suffix repeats an English word, for example `:ui/error-boundary-error`
Examples:
```clojure
:help.shortcuts/label
:graph.switch/select-prompt
:nav.all-pages/title
:server.config/port-label
:graph/delete-local-confirm-desc
:plugin/auto-update-check-feedback
:property/update-success
:publish/unpublish-error
:plugin.install-from-file/success
:graph.switch/empty-desc
:page.convert/tag-to-page-action
```
Use `error` or `warning` for failure feedback, based on the feedback severity
shown in the UI. Do not use `failure` as a leaf.
## Reuse Rules
Do not reuse a key only because the English text matches.
Reuse a key only when both are the same:
1. semantic owner
2. textual role
Examples:
- toolbar `"Bold"` and command `"Bold"` are different keys
- dialog `"Close"` and window `"Close"` are different keys
- `"Copied!"` may be shared only if it is intentionally a reusable cross-domain
notification
- settings-shell `"Check for updates"` and updater-state `"Checking for
updates"` are different keys because the owner differs
When two keys are truly duplicates:
- keep the key that already follows the standard
- deprecate the duplicate key
- do not merge keys when one message carries extra workflow or domain-specific
detail
## Naming Workflow
For every new string:
1. Identify the owner with the decision tree.
2. Choose the root namespace from the owner taxonomy.
3. Add a subdomain only if the string belongs to a stable section, workflow, or
representation.
4. Choose the leaf from the role rules.
5. Search `src/resources/dicts/en.edn` for an existing key with the same owner
and role.
6. Reuse only on exact semantic match.
7. If the new name would create a new root or a singleton dotted subdomain,
justify why convergence would be worse without it.
8. Add the English source text to `src/resources/dicts/en.edn`.
9. After editing dict files, run `bb lang:format-dicts`.
## Canonical Examples
| Need | Correct key |
|---|---|
| Generic dialog close button | `:ui/close` |
| Header back button tooltip | `:header/go-back` |
| Window close button | `:window/close` |
| Graph local deletion confirmation body | `:graph/delete-local-confirm-desc` |
| Page name validation error | `:page.validation/name-no-hash` |
| Active editor action `"Remove heading"` | `:editor/remove-heading` |
| Built-in node delete validation | `:node/built-in-cant-delete-error` |
| Property name input placeholder | `:property/name-placeholder` |
| Recycle item restore action | `:storage.recycle/restore` |
| Recycle page deletion metadata | `:storage.recycle/page-deleted-at` |
| Graph switch picker prompt | `:graph.switch/select-prompt` |
| Export copied page data feedback | `:export/page-data-copied` |
| Live query table title | `:view.table/live-query-title` |
| Table sort ascending action | `:view.table/sort-ascending` |
| Plugin install-from-file success | `:plugin.install-from-file/success` |
| Command palette open action | `:cmdk.action/open` |
| Mobile-only graph tab | `:mobile.tab/graphs` |
| Server running status | `:server.status/running` |
+123
View File
@@ -0,0 +1,123 @@
| Label | Description |
| :------------------------: | :------------------------------------------------------------------------------------------------------: |
| `:status/automatic-stale` | stale or no longer relevant. Added automatically by GH Stale Action |
| `:type/bug` | Something isn't working. Affects daily use. |
| `:type/bug-fix` | Related to fixing a bug |
| `:type/dev` | Related to development tasks |
| `:type/enhancement` | Enhancement to Logseq. Does not affect the overall basic use |
| `:type/feature` | New feature |
| `:type/feature-request` | Feature requests are in Logseq forum https://discuss.logseq.com/ |
| `:type/hold` | PR or issue is temporarily paused and will be revisited later |
| `:type/performance` | Performance related, speed or cpu usage. |
| `:type/question` | Not bug. Frequently asked question would be collected in Logseq Forum's FAQ section |
| `:type/regression` | Problem introduced by a change |
| `:type/releasing` | Related to the release process |
| `accessibility` | Related to improving accessibility for users with disabilities |
| `assets` | Related to project assets, such as images |
| `awaiting-response` | Issue will be closed if a reply is not received |
| `block-ref` | Related to block references |
| `breaking-change` | Change that breaks existing functionality or compatibility |
| `browser` | Related to browser compatibility |
| `build` | Related to building and development of Logseq |
| `can-be-reproduced` | Can be reliably observed to occur under specific conditions |
| `card` | Related to Logseq Flashcards feature |
| `chore` | Related to maintenance tasks |
| `ci` | Related to continuous integration |
| `css` | Related to Logseq CSS |
| `data-stability` | Related to data stability |
| `dependencies` | Pull requests that update a dependency file |
| `desktop` | Related to desktop compatibility |
| `docker` | Related to Docker |
| `draw` | Related to drawing or diagramming functionality |
| `duplicate` | Duplicated issue |
| `editor` | Related to the Logseq editor |
| `editor:autocomplete` | Related to the autocomplete feature in the editor |
| `editor:code` | Related to codeblocks feature in the editor |
| `editor:copy-paste` | Related to copy & paste actions in the editor |
| `editor:lazy-loading` | Related to lazy loading in the editor |
| `editor:popups` | Related to popups in the editor |
| `editor:undo-redo` | Related to undo & redo actions in the editor |
| `electron` | Related to Electron framework |
| `encryption` | Related to encryption |
| `estimate: large` | Require major refactor of a feature |
| `estimate: medium` | Medium effort required |
| `estimate: small` | Small effort required, maybe a few lines of code |
| `estimate: very large` | A project level feature (as large as the projects listed in our roadmap) |
| `export` | Related to exporting data from Logseq |
| `feature` | New feature (duplicate) |
| `filenames` | Related to file names |
| `firefox` | Related to Firefox compatibility |
| `fix` | Related to fixing a bug or an issue |
| `fixed-next-release ✅` | Fixed and will be in the next release |
| `format:markdown` | Related to Markdown format |
| `format:org-mode` | Related to Org mode format |
| `from:in-app` | Reported from inside the application |
| `fs` | Related to the file system |
| `git` | Related to Git version control |
| `good first issue` | Good for newcomers |
| `graph` | Related to Logseq graph feature |
| `help-wanted` | Extra attention or help is needed |
| `hierarchy` | Related to pages hierarchy |
| `i18n` | Related to internationalization |
| `import` | Related to importing data or functionality into Logseq |
| `input-method` | Related to input methods, such as keyboard layouts or handwriting recognition |
| `installation` | Related to installation or setup of Logseq |
| `integration:dropbox` | Related to integration with Dropbox |
| `integration:gdrive` | Related to integration with Google Drive |
| `integration:icloud-drive` | Related to integration with iCloud Drive |
| `integration:nutstore` | Related to integration with 坚果云 |
| `integration:other` | Related to integration with other services or applications |
| `integration:zotero` | Related to integration with Zotero |
| `ipad` | Related to iPad compatibility |
| `journals` | Related to journaling or logging functionality |
| `keymap:other` | Related to other key maps or keyboard layouts |
| `lang:cjk` | Related to Chinese, Japanese, and Korean languages |
| `lang:cyrillic` | Related to languages that use the Cyrillic alphabet |
| `lang:estonian` | Related to the Estonian language |
| `lang:latin1` | Related to languages that use the ISO/IEC 8859-1 character set |
| `lang:rtl` | Related to right-to-left languages |
| `left-sidebar` | Related to the left sidebar |
| `logbook` | Related to a logbook |
| `Logseq Sync` | Related to Logseq Sync |
| `looking-for-review` | PRs that require review and feedback before being merged |
| `math` | Related to mathematical formatting or functionality |
| `mobile` | Related to mobile compatibility or functionality |
| `mobile:android` | Related to Android compatibility or functionality |
| `mobile:browser` | Related to browser compatibility or functionality on mobile devices |
| `mobile:ios` | Related to iOS compatibility or functionality |
| `multi-window` | Related to multi-window functionality |
| `need-to-refactor` | Code refactoring is needed |
| `need-to-reproduce` | More information is needed to reproduce the issue |
| `os:linux` | Related to Linux compatibility or functionality |
| `os:macos` | Related to macOS compatibility or functionality |
| `os:other` | Related to compatibility or functionality on other operating systems |
| `os:windows` | Related to Windows compatibility or functionality |
| `page-ref` | Related to page references |
| `parser` | Related to the Markdown or Org mode parser |
| `pdf` | Related to PDF formatting or functionality |
| `plugins` | Related to Logseq plugins |
| `presentation` | Related to presentation mode |
| `priority-A` | Highest priority |
| `props` | Related to properties or metadata |
| `props:alias` | Related to alias property |
| `props:tags` | Related to tags property |
| `props:title` | Related to title property |
| `proxy` | Related to proxy settings or functionality |
| `publishing` | Related to publishing feature |
| `query` | Related to Logseq queries |
| `right-sidebar` | Related to the right sidebar |
| `search` | Related to search functionality |
| `settings` | Related to settings or configuration |
| `shortcuts` | Related to keyboard shortcuts |
| `stale-PR` | PRs that need attention from maintainers |
| `template` | Related to templates feature |
| `themes` | Related to themes or styling |
| `timestamp` | Related to timestamps or time-related functionality |
| `touch` | Related to touch input or touchscreen compatibility |
| `translation-required` | Translation is required. Please attach the translation in English. Or, the ticket will be closed at will |
| `upstream` | Blocked by dependencies that are not maintained by the Logseq team |
| `url scheme` | Related to URL schemes or links |
| `ux` | Related to user experience or usability |
| `with-FAQ` | The question is added to the Logseq Forum's FAQ section |
| `wontfix` | This issue or PR will not be fixed |
| `🎨 :feat/whiteboard` | Related to whiteboard functionality |
+108
View File
@@ -0,0 +1,108 @@
# Logseq Markdown Syntax
This document describes the Markdown syntax used by Logseq Markdown Mirror for
DB graphs.
## Page Identity
Mirror files start with an internal page id marker:
```markdown
id:: 11111111-1111-4111-8111-111111111111
```
The marker associates a mirror file with the DB page. It is not a normal page
property.
## Blocks
Blocks are Markdown list items that use `-`.
```markdown
- Parent
- Child
- Another child
- Sibling
```
Indentation defines block nesting. Markdown Mirror writes two spaces per nested
level.
## Properties
Properties are Markdown list items that use `*` and keep the Logseq property
marker `key::`.
```markdown
* page-property:: [[Page value]]
- Block
* block-property:: 42
```
Page properties appear before the first block. Block properties appear under the
block they belong to.
Open `:default` property values are represented by nested value blocks:
```markdown
- Oscar Wilde
* description::
- Irish poet and playwright
* books::
- The Picture of Dorian Gray
* year:: 1891
- The Importance of Being Earnest
* year:: 1895
```
Closed values stay inline with the property key, including many-value
properties:
```markdown
- Entry
* mood:: Joy, Sad
```
Non-default scalar values and node values also stay inline:
```markdown
- Lewis Carroll
* books:: [[Alice in Wonderland]]
* rating:: 5
```
Property value blocks can have nested blocks:
```markdown
- Book list
* notes::
- Alice
- Draft
```
## References
Page and node references use Logseq page reference syntax:
```markdown
- Read [[Project Plan]]
* owner:: [[Alice]]
```
Node property values are exported as `[[Node title]]`. Mirror export does not
use `((uuid))` for node property values.
## Tags
Tags are exported on block lines when they are normal user tags:
```markdown
- Call customer #sales
- Review #[[Quarterly plan]]
```
## Task Status
Task status is encoded on the block line:
```markdown
- TODO Write draft
- DONE Publish note
```
Task status is not exported as a separate `* Status::` property list item.
+101
View File
@@ -0,0 +1,101 @@
# OG Import Graph Cases
This file tracks file-graph-to-DB import issue classes and the regression cases fixed or covered by tests.
## db-test Import Issue Classes
GitHub `logseq/db-test` issues with the `import` label were audited on 2026-06-24. The file-graph importer cases fall into these classes:
- Block identity and references: #213, #226, #340, #426, #525, #641, #679, #684, #748, #927, #931.
- Journal and page references: #61, #77, #191, #192, #588, #906.
- Legacy properties, tasks, queries, and config: #176, #193, #195, #198, #220, #250, #289, #290, #300, #318, #341, #406, #446, #521, #537, #539, #540, #601, #732, #733, #936.
- Markdown and Org parsing fidelity: #434, #523, #582.
- Assets, PDFs, and highlights: #196, #358, #923.
- Tags, namespaces, aliases, and backlinks: #7, #134, #136, #197, #210, #460, #680, #724.
- Import UX, graph lifecycle, or non-file-graph import paths: #177, #216, #827.
## Fixed and Covered Cases
### Legacy journal filename refs
- Source issue: #906.
- Case: an OG page links to an imported journal file by file-style names such as `[[2026_04_01]]`, including when the source file is processed before the target journal file.
- Expected import behavior: resolve the file-style name to the DB journal page for that imported file, point `:block/refs` at the journal entity, and avoid creating an ordinary page named `2026_04_01`.
- Regression test: `logseq.graph-parser.exporter-test/import-legacy-journal-file-name-refs-as-journals`.
### Missing block refs
- Source issues: #213, #340, #679, #748, #927.
- Case: imported content contains block refs whose target block is absent from the selected file graph.
- Expected import behavior: remove the missing block ref from imported content and `:block/refs`, preserve blocks whose title becomes empty, and do not leave placeholder entities.
- Regression tests: `logseq.graph-parser.exporter-test/import-removes-pre-block-marker-and-missing-block-refs` and `logseq.graph-parser.exporter-test/export-doc-files-propagates-missing-block-ref-cleanup-report`.
### Forward block refs
- Source issues: #850, #927.
- Case: a block references a target block that appears in a later imported file.
- Expected import behavior: preserve the reference after all files import.
- Regression test: `logseq.graph-parser.exporter-test/import-removes-pre-block-marker-and-missing-block-refs`.
### Duplicated block ids
- Generated edge case.
- Case: two imported blocks contain the same `id::` value.
- Expected import behavior: keep the first block id, assign a new id to later duplicates, and keep the imported graph valid.
- Regression test: `logseq.graph-parser.exporter-test/import-repairs-duplicated-block-ids`.
### Generated Markdown file graphs
- Generated edge case.
- Case: deterministic random Markdown graphs contain multiple pages and journals with mixed task markers, page refs, missing page refs, block refs, missing block refs, duplicated ids, broken ids, temporal markers, tags, page properties, block properties, namespaces, aliases, missing asset links, tables, code fences, and nested blocks.
- Expected import behavior: import the whole file graph without throwing, keep the generated block corpus, repair invalid identity/ref data through the normal import path, and keep the imported DB valid.
- Regression tests: `logseq.graph-parser.exporter-test/import-generated-markdown-file-graph` and the local `^:integration` fuzz test `logseq.graph-parser.exporter-test/import-generated-markdown-file-graph-fuzz`.
### Recursive block refs
- Generated edge case.
- Case: a block title references the same block id.
- Expected import behavior: rebuild refs without adding a recursive self-reference.
- Regression test: `logseq.outliner.pipeline-test/db-rebuild-block-refs-removes-recursive-self-ref`.
### Missing pages
- Generated edge case.
- Case: imported content references a page that is not otherwise present in the selected file graph.
- Expected import behavior: create the referenced ordinary page once and point refs at it. Legacy journal filename refs resolve to journal pages only when the corresponding journal file is part of the import set.
- Regression tests: `logseq.graph-parser.exporter-test/import-creates-missing-ordinary-page-refs` and `logseq.graph-parser.exporter-test/import-legacy-journal-file-name-refs-as-journals`.
### Mixed repeated deadline and scheduled timestamps
- Source issue: #318.
- Case: one imported task has both `DEADLINE` and `SCHEDULED`, with a repeat cookie on one of them.
- Expected import behavior: keep both temporal dates, keep the repeat metadata attached to the repeated temporal property, and ensure the `repeat-type` built-in property exists so the imported DB validates.
- Regression test: `logseq.graph-parser.exporter-test/import-repeated-deadline-and-scheduled`.
### Linked external PDF annotations
- Source issue: #923.
- Case: an OG graph links a PDF with a `file:///...pdf` URL instead of copying the PDF under `assets/`, while the annotation EDN and `hls__*.md` files are stored under the graph by decoded filename.
- Expected import behavior: create an external Asset node for the linked PDF, keep the `file://` URL in asset metadata, import the PDF annotations, and point annotation blocks at the external Asset.
- Regression test: `logseq.graph-parser.exporter-test/import-linked-file-pdf-annotations`.
### Missing local PDF asset links
- Generated edge case.
- Case: imported Markdown links a local PDF under `assets/`, but the target file is absent from the selected file graph.
- Expected import behavior: report the unresolved link through `ignored-assets`, continue importing without noisy stderr output, and keep the imported DB valid.
- Regression test: `logseq.graph-parser.exporter-test/import-missing-local-pdf-asset-link-is-ignored-quietly`.
### Large flat files
- Source issue: #931.
- Case: a large imported file has tens of thousands of top-level blocks.
- Expected import behavior: build block txs and tx indexes eagerly enough to avoid lazy-sequence stack overflows, transact the file, and validate the imported graph.
- Regression test: `logseq.graph-parser.exporter-test/import-large-flat-file-without-stack-overflow`.
### Empty imported files
- Source issue: #582.
- Case: an Org or Markdown file graph contains an empty or one-byte journal/doc file, as in the `org-import.zip` fixture attached to #582.
- Expected import behavior: omit absent `:block/refs` values instead of transacting nil, continue importing the rest of the graph, and keep the imported DB valid.
- Regression test: `logseq.graph-parser.exporter-test/import-empty-journal-file`.
+129
View File
@@ -0,0 +1,129 @@
# Recurring Tasks
Logseq supports recurring tasks with three scheduling semantics, modeled
on org-mode's three repeater cookies. Picking the right one lets you
say exactly how the next occurrence should be computed when you mark
a task DONE.
This document is the reference for contributors working on the
scheduler and for users who want the full behavior specification. The
short, user-facing version lives in
[logseq/docs `Tasks.md`](https://github.com/logseq/docs/blob/master/pages/Tasks.md).
## The three semantics
### `.+` — Advance from completion
> *Repeats from the last time you marked the block done.*
The next occurrence is one interval after the moment you marked the
task DONE, regardless of what the original scheduled date was.
**Best for:** habits and cadence-driven recurrences — things where the
clock restarts the moment you finish.
**Example:** A weekly task scheduled for 2026-04-01, completed on
2026-04-05, will next appear on 2026-04-12. If you'd forgotten and
completed it on 2026-04-20, it would next appear on 2026-04-27. The
interval is anchored to your completion, not to the calendar.
### `++` — Advance from scheduled, skip to future
> *Keeps it on the same day of the week.*
The next occurrence starts at *original + one interval* and keeps
advancing in whole intervals until the result is strictly in the
future. Because the arithmetic is in UTC and advances by whole weeks
(or months, or years), weekly recurrences naturally land on the same
day-of-week as the original.
**Best for:** calendar-anchored recurrences where completion is a side
event and the anchor matters — "every Monday standup," "monthly review
on the first of the month."
**Example:** A weekly standup scheduled for Monday, 2026-04-06:
- Completed Wednesday, 2026-04-08 → next occurrence Monday, 2026-04-13.
- Completed Friday, 2026-04-17 → next occurrence Monday, 2026-04-20.
**This is the default** when a recurring task has no explicit cookie.
### `+` — Advance from scheduled, stacking
> *Repeats in X y/m/w/d/h from when you originally scheduled it.*
The next occurrence is exactly *original + one interval*. If
completion was much later than the original date, the next occurrence
may land in the past — which causes the task to appear overdue
immediately. Org-mode calls this "stacking."
**Best for:** obligations tied to an exact calendar date that should
not shift when you're late — monthly rent, annual renewals, fixed
billing cycles.
**Example:** Rent due 2026-04-01, paid 2026-04-05 → next reminder
2026-05-01. Paid 2026-04-25 → next reminder still 2026-05-01.
## Choosing the right cookie
A decision table for picking the right semantic:
| Intent | Cookie |
|---|---|
| "Every 7 days from when I last did it" | `.+` |
| "Every Monday" | `++` |
| "The 1st of every month" | `+` |
## Default and backward compatibility
Recurring tasks without an explicit `repeat-type` default to `++`.
This preserves the behavior that existed before the three cookies were
honored independently; no existing task changes on upgrade. Users who
want `.+` or `+` semantics can pick them via the repeat-setting
popover on the task.
## Implementation reference
### Scheduler
The scheduler lives in `src/main/frontend/worker/commands.cljs`. It
dispatches on `repeat-type` via `repeat-next-timestamp`:
- `advance-from-completion` implements `.+`
- `advance-from-scheduled` implements `+`
- `advance-until-future` implements `++`
The dispatch falls back to `++` for `nil` or unknown values, so the
scheduler is safe against missing or future-added cookie types.
Frequencies of zero or less short-circuit to `nil` before dispatch to
avoid infinite loops.
### Property
`:logseq.property.repeat/repeat-type` is a closed-values property
declared in `deps/db/src/logseq/db/frontend/property.cljs`. Its closed
values are:
- `:logseq.property.repeat/repeat-type.dotted-plus` — `.+`
- `:logseq.property.repeat/repeat-type.plus` — `+`
- `:logseq.property.repeat/repeat-type.double-plus` — `++` (default)
### UI
The repeat-setting popover in
`src/main/frontend/components/property/value.cljs` exposes a "Next date"
selector bound to the `repeat-type` property. It appears whenever the
task's repeat checkbox is enabled.
### Tests
Scheduler tests live in
`src/test/frontend/worker/commands_test.cljs`. Each of the three
semantics has a dedicated `deftest`; the preexisting
`get-next-time-test` exercises the default (`++`) path. Time is pinned
via `with-redefs [t/now ...]` for determinism.
## Related reading
- End-user docs: [logseq/docs `Tasks.md`](https://github.com/logseq/docs/blob/master/pages/Tasks.md)
- Org-mode spec: [Repeated tasks](https://orgmode.org/manual/Repeated-tasks.html)
- Tracking issues: [#7731](https://github.com/logseq/logseq/issues/7731), [#11260](https://github.com/logseq/logseq/issues/11260), [#6715](https://github.com/logseq/logseq/issues/6715), [#8531](https://github.com/logseq/logseq/issues/8531)
+612
View File
@@ -0,0 +1,612 @@
# Sync Stress Failed Cases
## Recording rule for CLI sync stress failures
- Date added: 2026-07-01
- Scope: `scripts/cli-concurrent-edit-stress.mjs`, local `db-sync` server runs, and multi-client CLI sync stress graphs.
- Rule: every hard failure or suspicious no-op from the stress harness must get an entry in this file before the issue is considered handled.
- Required fields for each entry: graph, command or log path, symptom, root cause, fix, regression test or stress verification, and current status.
- Do not mark a case fixed from a retry alone. A fixed case needs a concrete root cause and a post-fix run or targeted test that covers the same path.
## CLI tag-name resolution failed during expanded stress
- Date: 2026-07-01
- Graph: `cli-test-5`
- Command: `node scripts/cli-concurrent-edit-stress.mjs --graph cli-test-5 --concurrency 3 --sync --offline --offline-ms 800 --timeout-ms 20000 --max-ops 80 --extra-pages 2 --journal-pages 2 --journal-start 2026-07-01`
- Symptom: `upsert block --update-tags '["cli-stress-tag-a"]'` failed with `Cannot parse :find, expected: (find-rel | find-coll | find-tuple | find-scalar)`.
- Root cause: OCaml CLI tag-name resolution used a duplicated Datascript class query path for tag names. Numeric tag ids worked, but string tag names failed before the outliner mutation was applied.
- Regression test: `cli/test/test_cases.ml` now covers `upsert block --update-tags '["Tag A"]'` resolving through `thread-api/cli-list-tags`.
- Fix: tag-name resolution in `cli/lib/upsert.ml`, `cli/lib/add.ml`, and `cli/lib/update.ml` now uses the existing tag list endpoint instead of the broken query path.
- Sync status after the failed stress smoke: local and remote tx both reached `71`, pending queues were zero, and checksums matched (`b18d36f60f52de7e`).
## CLI sync stress failed cases from multi-client expansion
### Fresh 5000-op stress verification after sync fixes
- Date: 2026-07-01
- Graphs:
- `cli-sync-stress-assert-20260701-1`
- `cli-sync-stress-5000-20260701-13`
- `cli-sync-stress-5000-20260701-15`
- `cli-sync-stress-5000-20260701-snapshot-last-error-1`
- Commands:
- Assertion run: `DB_SYNC_CHECKSUM_ASSERT=true LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-assert-20260701-1 --config tmp/cli-sync-stress-assert-20260701-1/cli.edn --root-dir tmp/cli-sync-stress-assert-20260701-1/root --log-file tmp/cli-sync-stress-assert-20260701-1/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Normal run: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-13 --config tmp/cli-sync-stress-multi-5000-20260701-13/cli.edn --root-dir tmp/cli-sync-stress-multi-5000-20260701-13/root --log-file tmp/cli-sync-stress-multi-5000-20260701-13/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Reject rollback run: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-15 --config tmp/cli-sync-stress-multi-5000-20260701-15/cli.edn --root-dir tmp/cli-sync-stress-multi-5000-20260701-15/root --log-file tmp/cli-sync-stress-multi-5000-20260701-15/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Snapshot-last-error run: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-snapshot-last-error-1 --config tmp/cli-sync-stress-snapshot-last-error-5000-1/cli.edn --root-dir tmp/cli-sync-stress-snapshot-last-error-5000-1/root --log-file tmp/cli-sync-stress-snapshot-last-error-5000-1/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Result:
- `cli-sync-stress-assert-20260701-1` completed `5001` started ops, all clients settled at tx `6074`, final recomputed/local/remote checksum was `75663df27432e5c6`, and final `graph validate` passed on all three clients.
- `cli-sync-stress-5000-20260701-13` completed `5001` started ops, final recomputed/local/remote checksum was `f3b46db99d7293d1` on all three clients, and final `graph validate` passed on all three clients.
- `cli-sync-stress-5000-20260701-15` completed `5001` started ops after the rejected-local-tx rollback fix, final recomputed/local/remote checksum was `7c746bd7fb4ba9b3` on all three clients, and final `graph validate` passed on all three clients.
- `cli-sync-stress-5000-20260701-snapshot-last-error-1` completed `5001` started ops after the snapshot-last-error fix and bundle rebuild, final recomputed/local/remote checksum was `5790fdbc975a6b36` on all three clients, and final `graph validate` passed on all three clients.
- `cli-sync-stress-5000-20260701-20` completed `5001` started ops after the property-batch stale target fix and bundle rebuild, final recomputed/local/remote checksum was `fc3492f6c370efe4` on all three clients, and final `graph validate` passed on all three clients.
- The snapshot-last-error run's event log had no `sync-start-runtime-error`, `pending-tx-snapshot-changed`, `apply-remote-txs-failed`, fatal event, error-level event, checksum mismatch marker, or `prev-checksum-not-match` entry.
- The db-sync server log for the normal run had no `:before-checksum-error`, `server checksum doesn't match`, `prev-checksum-not-match`, `last-error`, or exception entries.
- Non-fatal anomalies:
- `cli-sync-stress-5000-20260701-15` had one recovered `:db-sync/apply-remote-txs-failed` worker log on client 3. The run later converged and validated; the transient failure is tracked in the open recovered remote-apply case below.
- `cli-sync-stress-5000-20260701-18` completed `5001` started ops, final recomputed/local/remote checksum `3cce9543989a7855` on all three clients, and final `graph validate` passed on all three clients. It still logged a recovered severe `:db-sync/apply-remote-txs-failed` after exhausting the immediate snapshot-drift retry budget; that is tracked in the delayed snapshot retry case below and this run is not counted as final verification for that later fix.
- `cli-sync-stress-5000-20260701-20` had three local `http-set-block-property` operations classified as `race-conflict` because their target blocks were deleted concurrently. Those HTTP handler exceptions are documented below and are not remote apply, checksum, or validation failures.
- Status: five fresh 5000-op runs passed after rebuilding `static/db-worker-node.js`; the latest run also verified the property-batch stale target fix at event/final-state and worker-log remote-apply level.
### Fresh 10000-op stress verification after sync fixes
- Date: 2026-07-01
- Graph: `cli-sync-stress-10000-20260701-1`
- Command: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-10000-20260701-1 --config tmp/cli-sync-stress-multi-10000-20260701-1/cli.edn --root-dir tmp/cli-sync-stress-multi-10000-20260701-1/root --log-file tmp/cli-sync-stress-multi-10000-20260701-1/events.jsonl --clients 3 --concurrency 8 --max-ops 10000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 90 --settle-ms 1000`
- Result:
- Completed `10001` started ops with 3 clients, offline windows, offline today-journal races, HTTP outliner ops, undo/redo, recycle/delete, and multi-client offline rebase operations.
- Final `thread-api/recompute-checksum-diagnostics` returned recomputed/local/remote checksum `6a1402088d63be44` for all three clients.
- Final `graph validate` passed on all three clients.
- Post-run `sync status` on all three clients reported `last-error nil`, `ws-state "open"`, `local-tx 12134`, `remote-tx 12134`, all pending queues `0`, and local/remote checksum `6a1402088d63be44`.
- The db-sync server log had no `:before-checksum-error`, `server checksum doesn't match`, `prev-checksum-not-match`, `last-error`, or exception entries.
- Non-fatal anomalies:
- `http-delete-restore-page` still returned HTTP 200 with `resultTransit false` four times. This is tracked in the open page-delete no-op case below.
- One `tag-delete-recreate` delete phase returned `tag-not-found`. The run still converged and validated. Root cause: the stress harness uses a shared volatile tag name, so another worker can delete the tag before the current worker's delete phase runs. Fix: classify `tag-not-found` during `tag-delete-recreate` delete as an expected race, matching the existing volatile property delete classification. Regression test: `scripts/cli-concurrent-edit-stress.test.mjs` covers this classifier path.
- Status: passed. This did not reproduce reverse-local-tx, apply-remote-tx, or checksum divergence failures.
### Final 1000-op smoke verification after classifier update
- Date: 2026-07-01
- Graph: `cli-sync-stress-1000-20260701-final`
- Command: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-1000-20260701-final --config tmp/cli-sync-stress-multi-1000-20260701-final/cli.edn --root-dir tmp/cli-sync-stress-multi-1000-20260701-final/root --log-file tmp/cli-sync-stress-multi-1000-20260701-final/events.jsonl --clients 3 --concurrency 8 --max-ops 1000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Result:
- Completed `1001` started ops with 3 clients and offline simulation.
- Final recomputed/local/remote checksum was `628f67429199e958` on all three clients.
- Final `graph validate` passed on all three clients.
- Post-run `sync status` on client 1 reported `last-error nil`, `ws-state "open"`, `local-tx 1087`, `remote-tx 1087`, all pending queues `0`, and local/remote checksum `628f67429199e958`.
- Status: passed after the volatile tag delete race classifier update.
### Targeted test verification after final stress updates
- Date: 2026-07-01
- Commands and results:
- `rtk node --test scripts/cli-concurrent-edit-stress.test.mjs scripts/cli-sync-stress-workflow.test.mjs`: 30 tests, 0 failures.
- `rtk bb dev:test -v frontend.worker.db-sync-test/validated-transact-retries-when-live-conn-changes-before-commit-test -v frontend.worker.db-sync-test/prepare-upload-tx-entries-drops-empty-txs-test -v frontend.worker.db-sync-test/apply-remote-txs-reverses-parent-insert-with-existing-child-without-orphaning-test -v frontend.worker.db-sync-test/sync-counts-refreshes-idle-stale-local-checksum-test -v frontend.worker.db-sync-test/apply-remote-txs-rechecks-local-txs-when-local-delete-races-temp-snapshot-test -v frontend.worker.db-sync-test/apply-remote-txs-rechecks-local-txs-when-local-delete-races-temp-commit-test -v frontend.worker.db-sync-test/apply-remote-txs-delays-retry-when-local-txs-keep-changing-test -v frontend.worker.db-sync-test/apply-remote-txs-retries-snapshot-drift-even-if-pending-list-stabilizes-test -v frontend.worker.db-sync-test/apply-remote-txs-local-delete-parent-remote-move-then-delete-parent-test -v frontend.worker.db-sync-test/apply-remote-txs-overlap-out-of-order-parent-delete-then-move-repairs-test`: 10 tests, 48 assertions, 0 failures.
- `rtk bb dev:test -v frontend.worker.db-sync-test/temp-conn-batch-preserves-cardinality-one-schema-test -v frontend.worker.db-sync-test/rebase-local-insert-then-save-keeps-cardinality-one-values-test -v frontend.worker.db-sync-test/apply-remote-txs-skips-stale-move-before-later-delete-test -v frontend.worker.db-sync-test/apply-remote-txs-skips-stale-move-to-target-before-later-target-delete-test -v frontend.worker.db-sync-test/apply-remote-txs-with-local-changes-rejects-invalid-final-rebase-test -v frontend.worker.db-sync-test/receive-queue-failure-updates-last-sync-error-test -v frontend.worker.db-sync-test/sync-counts-refreshes-idle-stale-local-checksum-test`: 7 tests, 21 assertions, 0 failures.
- `rtk bb dev:test -v frontend.worker.db-sync-test/apply-remote-txs-repairs-missing-block-lookup-ref-test -v frontend.worker.db-sync-test/apply-remote-txs-repairs-missing-block-retract-lookup-ref-test -v frontend.worker.db-sync-test/apply-remote-txs-with-local-changes-repairs-missing-block-lookup-ref-test -v frontend.worker.db-sync-test/apply-remote-txs-with-local-changes-repairs-missing-block-datoms-test`: 4 tests, 16 assertions, 0 failures.
- `rtk pnpm --dir deps/db test-v logseq.db-test/batch-transact-with-temp-conn-preserves-cardinality-one-schema-test logseq.db-test/batch-transact-with-temp-conn-preserves-retracts-test`: completed the deps/db suite, 114 tests, 418 assertions, 0 failures.
- `rtk pnpm --dir deps/db test-v logseq.db-test/batch-transact-with-temp-conn-before-commit-can-abort-live-commit-test logseq.db-test/batch-transact-with-temp-conn-preserves-cardinality-one-schema-test logseq.db-test/batch-transact-with-temp-conn-preserves-retracts-test logseq.db-test/transact-sync-retries-when-live-conn-changes-before-commit-test`: the targeted assertions printed as passing, but the full deps/db runner later stopped producing output in `gc-kvs-table-test` and was interrupted, so this invocation is not counted as a completed pass.
- `rtk bb dev:test -v frontend.worker.pipeline-test/recycle-ops-return-apply-result-test`: 1 test, 4 assertions, 0 failures.
- `rtk pnpm --dir cli test`: full CLI parity suite passed.
- Status: completed commands passed; the latest deps/db retry was interrupted after target assertions printed as passing and is not counted as a completed pass.
### Latest PR 12842 verification
- Date: 2026-07-01
- Commands and results:
- `rtk pnpm cljs:run-test -n frontend.worker.db-sync-test -e fix-me`: 206 tests, 750 assertions, 0 failures.
- `rtk clojure -M:clj-kondo --parallel --lint src/main/frontend/worker/sync/apply_txs.cljs src/test/frontend/worker/db_sync_test.cljs`: 0 errors, 0 warnings.
- `rtk node --test scripts/cli-concurrent-edit-stress.test.mjs scripts/cli-sync-stress-workflow.test.mjs`: 32 tests, 0 failures.
- `rtk bb dev:lint-and-test`: 1090 tests, 4730 assertions, 0 failures, with lint and translation checks passing.
- CLI stress verification:
- `cli-sync-stress-10000-20260701-6` completed `10001` started ops with 3 clients, offline windows, offline today-journal races, HTTP outliner ops, undo/redo, recycle/delete, and multi-client offline rebase operations. Final recomputed/local/remote checksum was `43da786afaaf37a8` on all three clients, and final `graph validate` passed on all three clients.
- `cli-sync-stress-1000-20260701-230737` completed `1001` started ops with 3 clients and offline simulation. Final recomputed/local/remote checksum was `dc4de34b2c9d2d8d` on all three clients, final `graph validate` passed on all three clients, and the event log had no hard `error`, `fatal`, `failed`, or `no-op` entries. Expected stale-id races were classified as `race-conflict`.
- Status: passed.
### Duplicate local and remote `create-page` rebase could remove remote children
- Date: 2026-07-01
- Graph: reproduced by worker tests while investigating multi-client offline today-page creation.
- Symptom: when one client had a pending local `create-page` and remote txs contained the same page plus new child blocks, rebasing the local `create-page` could treat the page as absent or create a duplicate path instead of preserving the remote page entity and its children.
- Root cause: `rebase-local-op!` only looked up an existing page by the local page UUID from the outliner op options. If the same title had already arrived from remote, the rebase path could miss it and run `outliner-page/create!` again instead of turning the local create into an idempotent page resolution.
- Fix: `:create-page` rebase now resolves an existing active page by UUID first and then by title. If it finds one, it returns the existing page title and UUID instead of creating another page.
- Regression tests:
- `frontend.worker.db-sync-test/rebase-create-page-keeps-page-uuid-test`
- `frontend.worker.db-sync-test/rebase-duplicate-create-page-keeps-remote-children-test`
- `frontend.worker.db-sync-test/apply-remote-txs-rebases-create-delete-page-as-recycled-test`
- Status: fixed and covered by the latest 1000-op and 10000-op multi-client offline stress runs.
### Remote recreate in the same batch was misclassified as a missing block repair
- Date: 2026-07-01
- Graph: reproduced by worker test from a local-delete and remote-recreate race.
- Symptom: if remote txs deleted a block and recreated the same `:block/uuid` in the same batch while the client had a local delete pending, the apply path could ask server repair for that UUID as if it were missing before applying the remote recreate tx.
- Root cause: missing-block preflight looked for absent lookup refs in the current DB and after local reversal, but it did not exclude block UUIDs that the incoming remote batch itself creates. Vector tx data was handled, but Datascript Datom tx data from remote apply was not part of the temp-id to UUID extraction path.
- Fix: remote apply now extracts created block UUIDs from both vector tx items and Datascript Datoms, subtracts UUIDs that are also retracted in the same batch, and excludes those remote-created UUIDs from missing-block repair preflight.
- Regression test: `frontend.worker.db-sync-test/apply-remote-tx-local-delete-remote-recreate-does-not-leave-local-only-delete-test`.
- Status: fixed and covered by latest stress verification.
### Delayed snapshot retry returned an inconsistently awaitable result
- Date: 2026-07-01
- Graph: reproduced by `frontend.worker.db-sync-test` full namespace run after adding snapshot-drift retry tests.
- Symptom: full namespace execution could see a delayed remote-apply retry continue after fixture cleanup, producing `missing-db` from `apply-remote-txs!`. Focused tests were easier to pass because the async cleanup race was narrower.
- Root cause: the snapshot-drift retry path returned nested or mixed native/Promesa promise values. The delayed retry branch could be observed as complete before the recursive retry finished, so callers and tests could clean up the repo connection while retry work was still scheduled.
- Fix: retry construction now uses one explicit Promesa chain via `<retry-apply-remote-txs!` and `p/then` for delayed retry. The tests' Datascript fixture cleanup also treats any thenable through `js/Promise.resolve(...).finally(...)` so native and Promesa promise values share one lifecycle.
- Regression tests:
- `frontend.worker.db-sync-test/apply-remote-txs-rechecks-local-txs-when-local-delete-races-temp-snapshot-test`
- `frontend.worker.db-sync-test/apply-remote-txs-rechecks-local-txs-when-local-delete-races-temp-commit-test`
- `frontend.worker.db-sync-test/apply-remote-txs-delays-retry-when-local-txs-keep-changing-test`
- `frontend.worker.db-sync-test/apply-remote-txs-retries-snapshot-drift-even-if-pending-list-stabilizes-test`
- Status: fixed; `frontend.worker.db-sync-test` full namespace passes.
### Volatile property delete became ambiguous during 10000-op retry
- Date: 2026-07-01
- Graph: `cli-sync-stress-10000-20260701-2`
- Command: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-10000-20260701-2 --config tmp/cli-sync-stress-multi-10000-20260701-2/cli.edn --root-dir tmp/cli-sync-stress-multi-10000-20260701-2/root --log-file tmp/cli-sync-stress-multi-10000-20260701-2/events.jsonl --clients 3 --concurrency 8 --max-ops 10000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 90 --settle-ms 1000`
- Symptom: the retry was interrupted after `1588` started ops because `property-delete-recreate` delete returned `ambiguous-property-name` for `cli-stress-volatile-prop`; the CLI reported two matching candidate property ids.
- Root cause: the stress harness intentionally uses one shared volatile property name while multiple workers concurrently delete and recreate it. Under that race, more than one property entity with the same display name can exist, and `remove property --name` is correctly ambiguous. This is the same volatile-resource race class as `property-not-found`, not evidence of sync divergence by itself.
- Fix: classify `ambiguous-property-name` during `property-delete-recreate` delete as an expected race conflict so the harness keeps stressing sync convergence instead of failing on an invalid name selector.
- Regression test: `scripts/cli-concurrent-edit-stress.test.mjs` covers both `property-not-found` and `ambiguous-property-name` for concurrent volatile property delete.
- Status: fixed in the stress harness; the interrupted run is not counted as final stress verification.
### Local sync server was not started for `--sync`
- Date: 2026-06-30
- Graph: `pi-memory`
- Command: `node scripts/cli-concurrent-edit-stress.mjs --graph pi-memory --concurrency 8 --sync --timeout-ms 20000`
- Symptom: fatal preflight error: `Local db-sync server is not healthy at http://127.0.0.1:18080/health`.
- Root cause: the stress harness required a local `db-sync` server for `--sync` but only checked health; it did not start the local server itself.
- Fix: the harness now starts `cli-e2e/scripts/db_sync_server.py` automatically for local `--sync` runs unless `--no-start-sync-server` is passed, and it rejects non-local `--sync-base` values.
- Regression test: `scripts/cli-concurrent-edit-stress.test.mjs` covers local sync server start args.
- Status: fixed in the stress harness.
### Sync start tried to refresh auth against the wrong local endpoint
- Date: 2026-06-30
- Graph: `pi-memory`
- Command: `node scripts/cli-concurrent-edit-stress.mjs --graph pi-memory --concurrency 8 --sync --timeout-ms 20000`
- Symptom: `sync start` failed with `auth-refresh-failed`, `Run logseq login first`, and a local HTTP 404 response.
- Root cause: the graph was not initialized/uploaded to the local sync server before `sync start`, so the CLI entered the normal auth-refresh path instead of the local stress upload path.
- Fix: `ensureLocalServers` now checks `sync status`; when the graph is uninitialized it sets local graph E2EE metadata when requested, runs `sync ensure-keys` when needed, uploads the graph to the local sync server, and only then starts sync.
- Regression test: `scripts/cli-concurrent-edit-stress.test.mjs` covers local sync upload/ensure-key argument construction.
- Status: fixed in the stress harness.
### Concurrent edit used stale block ids after another worker deleted the target
- Date: 2026-06-30
- Graph: `pi-memory`
- Example failure:
- `upsert block --graph pi-memory --id 1911 --target-id 1902 --pos last-child`
- Error: `source-not-found`, `source block uuid not found`
- Another example: `target-not-found`, `target block uuid not found`
- Root cause: the stress harness intentionally lets workers delete, recycle, move, and update from a shared live-id pool. Under concurrency, an id can be selected and then deleted by another worker before the mutation runs. That is a valid race for the harness, not by itself a sync corruption signal.
- Fix: CLI `source-not-found`, `target-not-found`, `block-not-found`, `page-not-found`, `recycled-page`, and `upsert-id-not-found` are classified as `race-conflict`; stale ids are dropped from the live pool and the pool is refreshed from the graph.
- Regression test: `scripts/cli-concurrent-edit-stress.test.mjs` covers stale id extraction and expected race classification.
- Status: fixed as a harness classification issue. A final checksum mismatch or graph validation failure after these race conflicts would still be treated as a real sync failure.
### Sync runtime kept last-error after duplicate `:block/uuid`
- Date: 2026-06-30
- Graph: `pi-memory`
- Command: `node scripts/cli-concurrent-edit-stress.mjs --graph pi-memory --concurrency 8 --sync --timeout-ms 20000`
- Symptom: `sync start` reached an open websocket but failed because `sync status` had `last-error`:
`Cannot add #datascript/Datom [... :block/uuid #uuid "06ef6144-c02c-469c-8296-7fc8e2220782" ...] because of unique constraint`.
- Root cause: remote tx application with local changes used the live Datascript connection while reversing local txs, applying remote txs, and replaying local txs. An exception during that pipeline could leave the live connection in an intermediate state even though `batch-transact!` resets the conn on a single failed batch.
- Fix: `apply-remote-tx-with-local-changes!` now uses `batch-transact-with-temp-conn!`, so reverse/apply/replay happens against a temporary connection and only the final successful result is committed to the live connection.
- Regression tests:
- `frontend.worker.db-sync-test/apply-remote-txs-with-local-changes-rejects-invalid-final-rebase-test`
- `frontend.worker.db-sync-test/rebase-local-insert-then-save-keeps-cardinality-one-values-test`
- Status: fixed in sync remote tx application.
### Receive queue failures were invisible to `sync status`
- Date: 2026-07-01
- Graph: reproduced by worker test, originally found while investigating CLI stress failures.
- Symptom: a receive-loop exception could stop remote application while `sync status` did not expose the failure through `last-error`, making a yellow/stuck sync indicator hard to diagnose.
- Root cause: `enqueue-receive-message!` logged the exception but did not update the client sync error state.
- Fix: the receive queue catch path now calls `sync-util/set-last-sync-error!` before logging.
- Regression test: `frontend.worker.db-sync-test/receive-queue-failure-updates-last-sync-error-test`.
- Status: fixed in sync worker error reporting.
### Release CLI failed to reuse a starting db-worker-node server
- Date: 2026-07-01
- Graphs:
- `cli-sync-stress-1000-20260701-1`
- earlier `5000` stress attempt before the release CLI fix
- Symptom: stress run failed with `server-start-failed`, `failed to publish health`, or transient `fetch failed` when many CLI commands started while db-worker-node was still starting or temporarily busy.
- Root cause: the release CLI discovered servers only through successful `/healthz` responses, treated HTTP 503 `starting` health payloads as absent, and did a one-shot final health lookup after spawning. Under concurrent CLI startup this could spawn duplicate workers or fail while the existing worker was almost ready.
- Fix: `cli/lib/server_runtime.ml` now accepts 200 and 503 health payloads for discovery, waits up to 30 seconds for published/ready servers, respects a live db-worker lock before spawning another worker, and retries final health discovery until ready.
- Regression tests:
- `CLI parity server start reuses starting db-worker-node`
- `CLI parity ensure server retries final health discovery`
- Post-fix stress verification: `cli-sync-stress-1000-20260701-2` completed with 3 clients, `1001` started ops, all final checksums equal to `94e75da4b4bf1f78`, and all three final `graph validate` checks passing.
- Status: fixed in release CLI server lifecycle handling.
### Recycle restore/permanent-delete returned no observable apply result
- Date: 2026-07-01
- Graph: reproduced by outliner pipeline test while expanding HTTP `apply-outliner-ops` stress coverage.
- Symptom: `thread-api/apply-outliner-ops` could return HTTP 200 with a nil/false result for recycle restore or permanent delete, so the stress harness could not distinguish a successful operation from a silent no-op.
- Root cause: `logseq.outliner.op/apply-op!` did not set `*result` for `:restore-recycled` and `:recycle-delete-permanently`.
- Fix: both op branches now return their mutation result through `*result`.
- Regression test: `frontend.worker.pipeline-test/recycle-ops-return-apply-result-test`.
- Status: fixed in outliner op result reporting.
### Remote move before later remote delete failed after local reversal removed the moved block
- Date: 2026-07-01
- Graph: `cli-sync-stress-5000-20260701-1`
- Command: `LOGSEQ_BIN=static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-1 --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Log evidence:
- `tmp/cli-sync-stress-multi-5000-20260701-1/events.jsonl`, line `6052`
- `tmp/cli-sync-stress-multi-5000-20260701-1/clients/client-2/root/graphs/cli-sync-stress-5000-20260701-1/db-worker-node-20260701.log`
- Symptom: client 2 got stuck with `last-error`:
`Nothing found for entity id [:block/uuid #uuid "912166d7-e42f-400b-bb8d-b1b120d44a66"]`.
- Runtime evidence: client 2 had `ws-state "open"`, `local-tx 1776`, `remote-tx 2425`, `pending-local 327`, `pending-server 649`, and checksum mismatch; clients 1 and 3 had settled at `local-tx 2425`, `remote-tx 2425`, checksum `c3635870ab8ca030`. Client 2 `graph validate` still passed, so this was sync apply/rebase failure, not local DB validation corruption.
- Root cause: while applying remote txs with local changes, repair preflight checked missing remote lookup refs against the live DB before reversing local pending txs. The block UUID existed at that point, so no repair was fetched. The isolated rebase then reversed local pending txs and removed the same block. The next remote tx `t=1779` tried to move that now-missing block, and a later remote tx `t=1788` deleted the same block. Datascript threw before the later delete could make the stale move irrelevant. The same class can happen when the moved block still exists but the move target is removed by local reversal and later deleted by the remote batch.
- Fix: remote tx application now drops stale operation datoms when a block ref used by that operation is already missing in the current apply DB and the current or later remote tx batch contains `:db/retractEntity` for that same `:block/uuid`. This keeps delete-wins ordering without masking missing blocks that are not actually deleted by the remote batch.
- Regression tests:
- `frontend.worker.db-sync-test/apply-remote-txs-skips-stale-move-before-later-delete-test`
- `frontend.worker.db-sync-test/apply-remote-txs-skips-stale-move-to-target-before-later-target-delete-test`
- Adjacent repair/rebase tests still pass:
`apply-remote-txs-repairs-missing-block-lookup-ref-test`,
`apply-remote-txs-repairs-missing-block-retract-lookup-ref-test`,
`apply-remote-txs-with-local-changes-repairs-missing-block-lookup-ref-test`,
`apply-remote-txs-with-local-changes-repairs-missing-block-datoms-test`,
`apply-remote-txs-with-local-changes-rejects-invalid-final-rebase-test`,
`apply-remote-txs-local-delete-parent-remote-move-then-delete-parent-test`,
`apply-remote-txs-overlap-out-of-order-parent-delete-then-move-repairs-test`.
- Post-fix stress verification: `cli-sync-stress-5000-20260701-13` and `cli-sync-stress-10000-20260701-1` both completed with 3 clients, offline windows, matching final checksums, and final `graph validate` passing on all clients.
- Status: fixed and verified in fresh 5000-op and 10000-op stress runs.
### Open: all clients settled locally but final remote checksum differed
- Date: 2026-07-01
- Graph: `cli-sync-stress-5000-20260701-8`
- Command: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-8 --config tmp/cli-sync-stress-multi-5000-20260701-8/cli.edn --root-dir tmp/cli-sync-stress-multi-5000-20260701-8/root --log-file tmp/cli-sync-stress-multi-5000-20260701-8/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Symptom: after 5000 requested ops, final sync settle failed on client 1 with `local-tx 6130`, `remote-tx 6130`, all pending queues at `0`, `last-error nil`, `ws-state "open"`, local checksum `d497a453c0029f4d`, and remote checksum `755f4eb4fee7ed74`.
- Current evidence:
- All three clients reported the same sync status values and the same local checksum, but all disagreed with the remote checksum.
- Final `graph validate` passed on all clients, but datom counts differed: client 1 had `8762` datoms, client 2 had `8779`, and client 3 had `8770`.
- The event log includes one transient `fetch failed` followed by server port refreshes, and an earlier `http-delete-restore-page` HTTP 200 no-op with `resultTransit false`.
- Follow-up diagnostics:
- Client-side `thread-api/recompute-checksum-diagnostics` recomputed `d497a453c0029f4d` on all three clients, matching each client's local checksum and disagreeing with the remote checksum reported by `sync status`.
- Direct server checksum diagnostics for graph id `e54e9868-e4c9-47b1-8f40-d3974e0cefc9` recomputed `d497a453c0029f4d`, matching the clients. The server SQLite `sync_meta.checksum` row still stored the stale value `755f4eb4fee7ed74`.
- The server tx log had rows from `t=1` through `t=6130`, and `sync_meta.t` was also `6130`, so the mismatch was isolated to stored checksum metadata rather than missing tx rows.
- `find-checksum-drift` could not replay this server DB from an empty DB because the tx log depends on the initial uploaded graph snapshot and built-in entities. That tool needs a snapshot-aware replay path before it can locate checksum drift for upload-created graphs.
- Additional verification:
- Added an opt-in server assertion path guarded by `DB_SYNC_CHECKSUM_ASSERT=true` that recomputes the server checksum after each appended tx and throws with `prev-tx`, `prev-checksum`, recomputed checksum, tx meta, DB-before, and tx data when stored incremental metadata drifts.
- Diagnostic run `cli-sync-stress-assert-20260701-1` completed `5001` started ops with 3 clients, offline mode, final tx `6074`, final checksum `75663df27432e5c6` on all clients, and final `graph validate` passing on all clients.
- The diagnostic server log had no `:before-checksum-error`, `server checksum doesn't match`, or `prev-checksum-not-match` entries.
- Root cause: still pending for the original stale `sync_meta.checksum` write. The direct server recompute shows the graph content itself matched clients in this run, but the stored checksum metadata had drifted. The assertion run did not reproduce the drift, so this case must stay open.
- Fix: pending. The assertion path is diagnostic only and must not be counted as the root-cause fix.
- Regression test or stress verification: pending. Do not mark fixed from a retry alone; first identify why `sync_meta.checksum` could stay stale while `sync_meta.t` and server graph contents reached the final tx.
- Status: open.
### Idle sync status exposed stale cached local checksum
- Date: 2026-07-01
- Graphs:
- `cli-sync-stress-5000-20260701-11`
- `cli-sync-stress-1000-20260701-snapshot-race-1`
- Commands:
- `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-11 --config tmp/cli-sync-stress-multi-5000-20260701-11/cli.edn --root-dir tmp/cli-sync-stress-multi-5000-20260701-11/root --log-file tmp/cli-sync-stress-multi-5000-20260701-11/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-1000-20260701-snapshot-race-1 --config tmp/cli-sync-stress-snapshot-race-1000-1/cli.edn --root-dir tmp/cli-sync-stress-snapshot-race-1000-1/root --log-file tmp/cli-sync-stress-snapshot-race-1000-1/events.jsonl --clients 3 --concurrency 8 --max-ops 1000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Symptom: the 5000-op run completed `5001` started ops, but final settle failed on client 2. `sync status` reported `last-error nil`, `ws-state "open"`, `local-tx 6035`, `remote-tx 6035`, all pending queues at `0`, local checksum `759e50784194968c`, and remote checksum `a661d1ec5864f400`. The later 1000-op regression run hit the same idle synced shape with `local-tx 1098`, `remote-tx 1098`, all pending queues at `0`, remote checksum `d4ce1df5e969232b`, but `local-checksum nil`.
- Evidence:
- Client 1 and client 3 already matched the remote checksum `a661d1ec5864f400`.
- Client 2 `graph validate` passed with no invalid entities.
- Calling `thread-api/recompute-checksum-diagnostics` on client 2 immediately returned recomputed/local/remote checksum `a661d1ec5864f400`, and the following `sync status` also reported the matching checksum.
- In `cli-sync-stress-1000-20260701-snapshot-race-1`, client 1 recomputed and validated with checksum `d4ce1df5e969232b`; client 2 also passed `graph validate`, but final settle checked `sync status` before recompute diagnostics and saw `local-checksum nil` for all 60 attempts.
- Root cause: sync status and RTC presence read the cached local checksum from client-ops metadata directly. Under these stress runs, that cache was stale or missing even though the Datascript graph itself could recompute to the remote checksum and there were no pending local/server queues. The first fix only refreshed when the cached local checksum was a string, so it handled stale string values but skipped a nil cache. Because no later tx arrived, the stale or nil cache stayed visible and final settle treated the graph as divergent.
- Fix: `frontend.worker.sync.presence/sync-counts` now detects the idle mismatch state (`pending-local`, `pending-asset`, and `pending-server` are zero; `local-tx == remote-tx`; cached local checksum is nil or differs from remote checksum), recomputes the checksum from the live Datascript DB, updates the cached local checksum, and returns the recomputed value. A real DB divergence still remains visible because the recomputed checksum will continue to differ from the remote checksum.
- Regression test: `frontend.worker.db-sync-test/sync-counts-refreshes-idle-stale-local-checksum-test` covers both stale string and nil cached local checksums.
- Post-fix stress verification: `cli-sync-stress-5000-20260701-13`, `cli-sync-stress-10000-20260701-1`, `cli-sync-stress-1000-20260701-final`, and `cli-sync-stress-5000-20260701-snapshot-last-error-1` all ended with `local-tx == remote-tx`, all pending queues at `0`, and matching local/remote/recomputed checksums. The latest fresh 5000-op run used the rebuilt worker bundle and did not reproduce stale or nil checksum status.
- Status: fixed by targeted test and fresh stress verification.
### Open: sync start timed out with RTC closed and pending local changes
- Date: 2026-07-01
- Graph: `cli-sync-stress-5000-20260701-12`
- Command: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-12 --config tmp/cli-sync-stress-multi-5000-20260701-12/cli.edn --root-dir tmp/cli-sync-stress-multi-5000-20260701-12/root --log-file tmp/cli-sync-stress-multi-5000-20260701-12/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Symptom: during `offline-today-journal-race`, several `sync start` calls timed out before the websocket reached `open`. The status had `last-error nil`, `ws-state "closed"`, `pending-local` greater than `0`, `pending-server 0`, `local-tx == remote-tx`, and differing local/remote checksums.
- Evidence:
- One failure reported `local-tx 3319`, `remote-tx 3319`, `pending-local 89`, `local-checksum "1a69e8c09ac59ca6"`, and `remote-checksum "f6b91e5ab46a8394"`.
- A manual status check while the run was still active reported `ws-state "closed"`, `local-tx 3287`, `remote-tx 3287`, `pending-local 208`, `pending-server 0`, `local-checksum "2c50d29e2e5a8fde"`, and `remote-checksum "f0bc605965fec2f1"`.
- This matches the user-reported stuck-yellow shape: local changes are pending, the RTC state is closed, and a restart or refresh is needed before syncing resumes.
- The fresh rollback verification run `cli-sync-stress-5000-20260701-15` reproduced the same transient shape. Examples: line `15748` had `ws-state "closed"`, `local-tx 5392`, `remote-tx 5392`, `pending-local 76`, local checksum `7525b61b47be8cd3`, and remote checksum `bcba6bfda0e2af3f`; line `15863` had `ws-state "closed"`, `local-tx 5458`, `remote-tx 5458`, `pending-local 64`, local checksum `43bf131651448414`, and remote checksum `d2c8e8cc0ddf768a`.
- In `cli-sync-stress-5000-20260701-15`, final settle eventually recovered without manual restart: all three clients ended with recomputed/local/remote checksum `7c746bd7fb4ba9b3`, and final `graph validate` passed. This keeps the case open as a reconnect/retry issue, not a final convergence failure in that run.
- Root cause: pending. The next diagnostic step is to determine whether `sync start` is racing an explicit stop/offline transition, reusing a closed client without scheduling reconnect, or leaving inflight state uncleared.
- Fix: pending.
- Regression test or stress verification: pending.
- Status: open.
### Post-fix 5000-op run ended with zero-pending checksum mismatch on one client
- Date: 2026-07-01
- Graph: `cli-sync-stress-5000-20260701-14`
- Command: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-14 --config tmp/cli-sync-stress-multi-5000-20260701-14/cli.edn --root-dir tmp/cli-sync-stress-multi-5000-20260701-14/root --log-file tmp/cli-sync-stress-multi-5000-20260701-14/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Symptom: the run reached `5001` started ops with no non-race errors during operation execution, then final settle failed on client 2. The final status had `last-error nil`, `ws-state "open"`, `local-tx 6138`, `remote-tx 6138`, all pending queues at `0`, local checksum `5a14c02ae03a8ea4`, and remote checksum `caa4a33469ac5576`.
- Evidence:
- Final settle retried `sync status` 60 times for client 2 before failing.
- The failure happened after rebuilding `static/db-worker-node.js` with the remote repair-after-local-reversal fix, so it is not the stale-code run from `cli-sync-stress-5000-20260701-12`.
- No `last-error`, `apply remote tx fail`, or missing entity error appeared before final settle.
- `thread-api/recompute-checksum-diagnostics` showed a real local divergence, not a stale checksum cache: client 1 and client 3 recomputed to `caa4a33469ac5576` with `801` checksum-visible blocks, while client 2 recomputed to `5a14c02ae03a8ea4` with `797` checksum-visible blocks.
- Final `graph validate` still passed on client 2 (`1040` entities, `808` blocks, `9609` datoms), so the divergent DB shape is internally valid.
- Comparing checksum block sets showed client 2 was missing exactly four blocks that client 1, client 3, and the server kept:
- `d959db93-2cb2-4054-980c-106f5b67e708`: `http insert stress-1782899803902 worker=4 seq=380 op=http-insert-blocks`
- `35b5799f-f2e9-49b8-be1b-7324cf676c18`: `http undo redo stress-1782899803902 worker=8 seq=328 op=http-insert-undo-redo`
- `f13cc3da-b879-4e41-93c6-01a23ee0a5ee`: `child stress-1782899803902 worker=4 seq=442 op=create-child parent=3812`
- `6a44e88b-c7dd-4e91-aa4d-0097fd768289`: `http batch stress-1782899803902 worker=6 seq=496 op=http-batch-set-property`
- Server tx evidence for graph id `f1ba1b2c-995c-45a0-8fbf-d1ce1a23b786`:
- `t=3219` created `d959db93-2cb2-4054-980c-106f5b67e708` under parent `fd0cd77a-4daf-4c45-981e-8153a6694fdf`.
- `t=3434` inserted `35b5799f-f2e9-49b8-be1b-7324cf676c18`, `t=3435` deleted it, and `t=3436` reinserted the same UUID.
- `t=3843` moved the parent chain from the journal page to page `6a44e51d-bf4e-4b30-96d2-4580dd316905`.
- `t=3937` added `f13cc3da-b879-4e41-93c6-01a23ee0a5ee` under `35b5799f-f2e9-49b8-be1b-7324cf676c18`.
- `t=4619` added `6a44e88b-c7dd-4e91-aa4d-0097fd768289`.
- Later txs recycled and restored page `6a44e51d-bf4e-4b30-96d2-4580dd316905`, but no later server tx deleted these four blocks.
- Client 2 `client_ops` had one failed local tx:
- tx id `1e43b525-dd7e-4bd8-9eca-67bce986db48`, `outliner_op=delete-blocks`, `pending=0`, `failed=1`.
- The normalized tx deleted `35b5799f-f2e9-49b8-be1b-7324cf676c18` and `d959db93-2cb2-4054-980c-106f5b67e708`.
- Its reverse tx contained the exact four missing blocks, including `f13cc3da-b879-4e41-93c6-01a23ee0a5ee` and `6a44e88b-c7dd-4e91-aa4d-0097fd768289`.
- Client 2 log line `1796` showed the server rejected that tx with `tx/reject`, `reason "db transact failed"`, `t 4753`, and the same failed tx id.
- Root cause: when the server rejected a local tx as non-recoverable, the client marked the tx `failed=1` and `pending=0` but did not roll back the local Datascript mutation that had already been applied optimistically. The failed delete therefore remained in client 2's local graph while the server and other clients never accepted it. Because the tx was no longer pending, final sync status reached `local-tx == remote-tx`, all pending queues at `0`, and no `last-error`, but the local checksum stayed permanently different.
- Fix: `tx/reject` handling now rolls back rejected pending txs before marking them failed. The rollback reverses the rejected tx and any later pending local txs in a temporary connection, commits only a successful result to the live DB, and rebases later non-rejected pending txs so unrelated local edits remain queued.
- Regression test: `frontend.worker.db-sync-test/tx-reject-db-transact-failed-rolls-back-rejected-local-delete-test`.
- Adjacent verification: the focused `tx/reject` suite passed, including `tx-reject-db-transact-failed-surfaces-rejected-tx-test`, `tx-reject-db-transact-failed-marks-inflight-op-failed-test`, `tx-reject-db-transact-failed-rolls-back-rejected-local-delete-test`, `tx-reject-db-transact-failed-selectively-updates-inflight-ops-test`, `tx-reject-missing-blocks-keeps-failed-tx-pending-and-retries-with-repair-test`, and `tx-reject-stale-keeps-inflight-op-pending-test`.
- Post-fix stress verification: after rebuilding `static/db-worker-node.js`, `cli-sync-stress-5000-20260701-15` completed `5001` started ops with final checksum `7c746bd7fb4ba9b3` on all three clients and final `graph validate` passing on all three clients. Earlier fresh stress runs `cli-sync-stress-5000-20260701-13`, `cli-sync-stress-10000-20260701-1`, and `cli-sync-stress-1000-20260701-final` also converged and validated.
- Status: fixed and verified in fresh 5000-op, 10000-op, and 1000-op stress runs.
### Remote apply failed on a missing block UUID after offline journal races
- Date: 2026-07-01
- Graph: `cli-sync-stress-5000-20260701-12`
- Command: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-12 --config tmp/cli-sync-stress-multi-5000-20260701-12/cli.edn --root-dir tmp/cli-sync-stress-multi-5000-20260701-12/root --log-file tmp/cli-sync-stress-multi-5000-20260701-12/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Symptom: after several offline start/stop windows and auto-created journal races, client 2 could reopen the websocket but stayed stuck with `last-error`:
`Nothing found for entity id [:block/uuid #uuid "cb874a9d-e87a-4427-99d8-f6cacb931381"]`.
- Evidence:
- Event log line `10118` shows `sync start` returning `sync-start-runtime-error` with `ws-state "open"`, `local-tx 3545`, `remote-tx 3836`, `pending-local 265`, and `pending-server 291`.
- A later manual status check showed the same missing UUID with `local-tx 3545`, `remote-tx 3868`, `pending-local 279`, and `pending-server 323`.
- The primary client and client 3 continued past this point, so the failure is isolated to applying/rebasing remote txs on one client, not to server availability alone.
- Root cause: the failing client had local pending txs, so remote apply first reversed those local txs in an isolated rebase connection. The live DB still had enough data before reversal, so the existing pre-repair scan did not fetch the block. After local reversal, the block `cb874a9d-e87a-4427-99d8-f6cacb931381` was gone, and remote tx `t=3700` tried to move that same block with no later remote delete for it. The earlier stale move-before-delete fix correctly handled remote batches where the same missing block would be deleted later, but this case needed repair, not dropping.
- Fix: remote apply now does an additional isolated dry-run of local reversal before fetching server repair data. Any remote block refs that become missing only after local reversal are fetched from the server and applied after reversal but before remote tx application. UUIDs that the same remote batch later retracts are excluded so the previous delete-wins stale behavior is preserved.
- Regression test: `frontend.worker.db-sync-test/apply-remote-txs-repairs-block-made-missing-by-local-reversal-test`.
- Adjacent verification: the repair/rebase suite passed, including `apply-remote-txs-repairs-missing-block-lookup-ref-test`, `apply-remote-txs-repairs-missing-block-retract-lookup-ref-test`, `apply-remote-txs-with-local-changes-repairs-missing-block-lookup-ref-test`, `apply-remote-txs-with-local-changes-repairs-missing-block-datoms-test`, `apply-remote-txs-skips-stale-move-before-later-delete-test`, `apply-remote-txs-skips-stale-move-to-target-before-later-target-delete-test`, and `apply-remote-txs-with-local-changes-rejects-invalid-final-rebase-test`.
- Post-fix stress verification: `cli-sync-stress-5000-20260701-13`, `cli-sync-stress-10000-20260701-1`, and `cli-sync-stress-1000-20260701-final` all completed without `apply remote tx fail`, missing block UUID runtime errors, or final checksum divergence.
- Status: fixed and verified in fresh stress runs.
### Reversing queued parent insert orphaned existing children during sync rebase
- Date: 2026-07-01
- Source: user report from `2.0.1-alpha+nightly.20260629`; reproduced by targeted DB worker test on current branch before the fix.
- Symptom: after a stale websocket gap and reconnect, sync replay/rebase reversed an earlier `insert-blocks` transaction that deleted a parent block while children still referenced it. DB validation rejected the write with `DB write failed with invalid data`; the validation error included `:block/parent` missing required key, and sync could freeze with queued server txs still pending.
- Reproduction: `frontend.worker.db-sync-test/apply-remote-txs-reverses-parent-insert-with-existing-child-without-orphaning-test` seeds a local graph with a queued inserted parent and an existing child under it, then leaves only the parent insert reverse in the pending queue. Before the fix, remote apply failed with `DB write failed with invalid data`; the tx data retracted the parent entity while the child still referenced the old parent entity id.
- Root cause: raw reverse tx-data for `:insert-blocks` can be narrower than the current local subtree. During remote apply with local changes, `reverse-local-txs!` applies reverse tx-data with validation skipped because intermediate rebase states may be temporarily invalid. If an `insert-blocks` reverse contains `[:db/retractEntity parent]` but the current DB has children under that parent which are not also reversed, the final batch can leave those children pointing at a retracted parent. Rebase may then create a new parent entity with the same UUID, but the existing children still point at the old empty entity id, so final validation fails.
- Fix: `reverse-history-action!` now expands `:insert-blocks` reverse `:db/retractEntity` operations to include current descendant blocks before retracting the parent. This keeps the reverse phase subtree-consistent even if later child txs were dropped or are missing from the current pending slice.
- Regression test: `frontend.worker.db-sync-test/apply-remote-txs-reverses-parent-insert-with-existing-child-without-orphaning-test` failed before the fix and passes after the fix.
- Follow-up: add a reason to `:db-sync/drop-tx-ids` logs so empty tx-data drops can be distinguished from other queue changes.
- Stress verification: after rebuilding `static/db-worker-node.js`, `cli-sync-stress-5000-20260701-snapshot-last-error-1` completed `5001` started ops, reached matching final checksum `5790fdbc975a6b36` on all three clients, passed final `graph validate` on all three clients, and had no event-log `DB write failed with invalid data` or `:block/parent` validation failure.
- Status: fixed by targeted test and fresh 5000-op stress verification.
### Recovered remote apply failure after local tx snapshot drift
- Date: 2026-07-01
- Graph: `cli-sync-stress-5000-20260701-15`
- Command: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-15 --config tmp/cli-sync-stress-multi-5000-20260701-15/cli.edn --root-dir tmp/cli-sync-stress-multi-5000-20260701-15/root --log-file tmp/cli-sync-stress-multi-5000-20260701-15/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Log path: `tmp/cli-sync-stress-multi-5000-20260701-15/clients/client-3/root/graphs/cli-sync-stress-5000-20260701-15/db-worker-node-20260701.log`
- Symptom: client 3 logged a transient severe `:db-sync/apply-remote-txs-failed` while applying remote txs with local changes. The failing tx was remote `t=818`, `:outliner-op :rebase`, which tried to update the order of block UUID `f0754dfd-6c36-4657-857a-181551579fdd`; Datascript reported `Nothing found for entity id [:block/uuid #uuid "f0754dfd-6c36-4657-857a-181551579fdd"]`.
- Evidence:
- Worker log line `568` has the failed tx data: retract `:block/order "b0mzz"` and add `:block/order "b0yV"` for `f0754dfd-6c36-4657-857a-181551579fdd`.
- Worker log line `591` records `:db-sync/apply-remote-txs-failed` with `:has-local-changes? true`, `:remote-tx-count 36`, and `:local-tx-count 16`.
- Event log line `1643` shows the same UUID was selected as the target of an earlier successful HTTP `insert-blocks` operation, so the remote tx referenced a block that should have existed or been repaired before applying the order update.
- Client 3 `client_ops` showed the block create tx at row `397`, a child insert at row `412`, and a later local delete at row `633`.
- The failed worker log's `local-txs` list contained rows `617` through `632`, but did not include row `633`.
- Unlike `cli-sync-stress-5000-20260701-12`, this run recovered: final recomputed/local/remote checksum was `7c746bd7fb4ba9b3` on all three clients, and final `graph validate` passed on all three clients.
- Root cause: remote apply used an inconsistent pair of snapshots. It read `pending-txs` first and built repair/rebase context from that list, then later `batch-transact-with-temp-conn!` copied the live Datascript DB. A local delete of `f0754dfd-6c36-4657-857a-181551579fdd` was applied and persisted as a pending tx after the `pending-txs` snapshot but before the temp DB snapshot. The temp DB therefore no longer had the block, but the apply attempt did not reverse that new delete because it was not in `local-txs`. Remote tx `t=818` then tried to update `:block/order` for the missing block and failed. This is different from the earlier missing-block-after-local-reversal repair case: the repair preflight was not simply incomplete; it was based on a stale pending queue snapshot.
- Fix: when remote apply fails and the current pending tx id list differs from the list captured for that apply attempt, the worker discards the stale attempt and restarts `apply-remote-txs!` from fresh pending txs and the current DB. Snapshot-drift retries are treated as a retryable race; unrelated remote apply failures still surface normally.
- Regression tests:
- `frontend.worker.db-sync-test/apply-remote-txs-rechecks-local-txs-when-local-delete-races-temp-snapshot-test`: failed before the fix with `Nothing found for entity id [:block/uuid ...]`; passes after the fix.
- `frontend.worker.db-sync-test/apply-remote-txs-delays-retry-when-local-txs-keep-changing-test`: forces more snapshot drifts than the immediate retry budget and verifies remote apply delays, retries from a fresh pending-tx snapshot, and does not report a remote apply failure.
- Adjacent verification passed: `apply-remote-txs-local-delete-parent-remote-move-then-delete-parent-test`, `apply-remote-txs-overlap-out-of-order-parent-delete-then-move-repairs-test`, `apply-remote-txs-repairs-order-only-block-made-missing-by-local-reversal-test`, and `apply-remote-txs-delete-parent-with-child-without-local-changes-test`.
- Stress verification: after rebuilding `static/db-worker-node.js`, `cli-sync-stress-5000-20260701-snapshot-last-error-1` completed `5001` started ops, reached matching final checksum `5790fdbc975a6b36` on all three clients, and passed final `graph validate` on all three clients. Its event log had no `apply-remote-txs-failed`, `sync-start-runtime-error`, or error-level entries; the run did not produce db-worker log files, so worker-log-level severe entries are not separately asserted for this run.
- Status: root cause fixed by targeted worker tests and verified by fresh 5000-op stress at event/final-state level.
### Remote apply exhausted immediate retries while local txs kept changing
- Date: 2026-07-01
- Graph: `cli-sync-stress-5000-20260701-18`
- Command: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-18 --config tmp/cli-sync-stress-multi-5000-20260701-18/cli.edn --root-dir tmp/cli-sync-stress-multi-5000-20260701-18/root --log-file tmp/cli-sync-stress-multi-5000-20260701-18/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Symptom: the run completed and converged, but the primary worker log had a recovered severe `:db-sync/apply-remote-txs-failed` at line `131`. The error was `pending local tx snapshot changed during remote apply`; the attempt had `:remote-tx-count 5` and `:local-tx-count 23`.
- Evidence:
- Lines `95`, `107`, and `119` in `tmp/cli-sync-stress-multi-5000-20260701-18/root/graphs/cli-sync-stress-5000-20260701-18/db-worker-node-20260701.log` show three immediate `:db-sync/retry-remote-apply-after-local-tx-snapshot-drift` warnings. Each retry observed additional pending local tx ids.
- Line `131` then logged severe `:db-sync/apply-remote-txs-failed` because the fourth consecutive drift exceeded `max-remote-apply-snapshot-retries`.
- The event log later showed final recomputed/local/remote checksum `3cce9543989a7855` on all three clients and final `graph validate` passed on all three clients. This proves the failure was recoverable, but still produced a false severe apply failure during normal concurrent editing.
- Root cause: the first snapshot-drift fix only retried immediately and capped the in-call retry count at three. Under continuous CLI writes, remote apply could see a valid snapshot drift four times in a row. That is not a corrupt remote tx or invalid DB state; it just means local edits are still arriving while remote apply is trying to take a consistent pending-tx and DB snapshot.
- Fix: snapshot drift now remains a retryable path after the immediate retry budget. When the budget is exhausted, remote apply logs `:db-sync/delay-remote-apply-after-local-tx-snapshot-drift`, yields briefly, and restarts from a fresh pending-tx snapshot instead of reporting `:db-sync/apply-remote-txs-failed`. Actual apply errors without pending snapshot drift still go through the severe failure/reporting path.
- Regression test: `frontend.worker.db-sync-test/apply-remote-txs-delays-retry-when-local-txs-keep-changing-test`.
- Test evidence: `rtk bb dev:test -v frontend.worker.db-sync-test/apply-remote-txs-delays-retry-when-local-txs-keep-changing-test -v frontend.worker.db-sync-test/apply-remote-txs-rechecks-local-txs-when-local-delete-races-temp-snapshot-test -v frontend.worker.db-sync-test/apply-remote-txs-rechecks-local-txs-when-local-delete-races-temp-commit-test -v frontend.worker.db-sync-test/apply-remote-txs-repairs-order-only-block-made-missing-by-local-reversal-test -v frontend.worker.db-sync-test/apply-remote-txs-local-delete-parent-remote-move-then-delete-parent-test -v frontend.worker.db-sync-test/apply-remote-txs-overlap-out-of-order-parent-delete-then-move-repairs-test`: 6 tests, 29 assertions, 0 failures.
- Stress verification: after rebuilding `static/db-worker-node.js`, `cli-sync-stress-5000-20260701-snapshot-last-error-1` completed `5001` started ops, reached matching final checksum `5790fdbc975a6b36` on all three clients, and passed final `graph validate` on all three clients. Its event log had no `pending-tx-snapshot-changed`, `sync-start-runtime-error`, `apply-remote-txs-failed`, or error-level entries.
- Status: fixed by targeted test and fresh 5000-op stress verification.
### Property batch remote apply referenced blocks already missing on another client
- Date: 2026-07-01
- Graph: `cli-sync-stress-5000-20260701-19`
- Command: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-19 --config tmp/cli-sync-stress-multi-5000-20260701-19/cli.edn --root-dir tmp/cli-sync-stress-multi-5000-20260701-19/root --log-file tmp/cli-sync-stress-multi-5000-20260701-19/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Symptom: the run completed `5001` started ops, all three clients converged to checksum `b82c6db876ec2c36`, and final `graph validate` passed, but client 3 logged a severe recovered `:db-sync/apply-remote-txs-failed`.
- Evidence:
- Event log line `3488` shows worker 8 seq 168 applying `http-batch-set-property` to ids `[1453,1398,1368]`.
- `tmp/cli-sync-stress-multi-5000-20260701-19/clients/client-3/root/graphs/cli-sync-stress-5000-20260701-19/db-worker-node-20260701.log`, line `76`, shows the remote tx `t=1557` failing with `Nothing found for entity id [:block/uuid #uuid "6b495b02-2a45-4bcc-82d6-ef3684e7053c"]`.
- The same log line shows the failing tx adds `:block/refs`, `:user.property/cli-http-prop`, and a property value child whose `:block/parent` is the same missing UUID. Line `99` records `:has-local-changes? false`, `:remote-tx-count 41`, and `:local-tx-count 0`, so this is not the pending snapshot drift retry path.
- Client 2 also logged a stale reverse failure for a later `http-batch-set-property` pending tx, where reversing the batch tried to retract property value blocks and parent property refs for target blocks that no longer existed.
- Root cause: property batch txs can include side-effect datoms for several target blocks. Under concurrent delete/rebase, one client may receive a remote property batch after a target block has already been removed locally and is also absent from the server repair endpoint. Existing repair handles missing block lookup refs when the server can still return the block. Existing stale-drop logic handles missing refs only when the same remote batch later contains `:db/retractEntity` for that block. This case had neither condition: repair returned no block, and the tx still tried to add refs/properties and a property value child under the missing target, so Datascript aborted the whole remote batch before unrelated txs could apply.
- Fix: remote tx application now carries the repair-requested missing block UUIDs into `transact-remote-txs!`. After repair has had a chance to populate those blocks, any still-missing repair target that is not created by the current remaining remote batch is treated as stale. The sanitizer drops datoms directly targeting that stale block and drops newly-created side-effect blocks whose datoms point at the stale block, while preserving unrelated txs in the same remote batch.
- Regression test: `frontend.worker.db-sync-test/apply-remote-txs-drops-stale-property-batch-side-effects-for-unrepaired-missing-target-test`.
- Test evidence: `rtk bb dev:test -v frontend.worker.db-sync-test/apply-remote-txs-drops-stale-property-batch-side-effects-for-unrepaired-missing-target-test -v frontend.worker.db-sync-test/apply-remote-txs-repairs-missing-block-lookup-ref-test -v frontend.worker.db-sync-test/apply-remote-txs-repairs-missing-block-ref-value-test -v frontend.worker.db-sync-test/apply-remote-txs-with-local-changes-repairs-missing-block-lookup-ref-test`: 4 tests, 16 assertions, 0 failures.
- Stress verification: after rebuilding `static/db-worker-node.js`, `cli-sync-stress-5000-20260701-20` completed `5001` started ops, reached matching final checksum `fc3492f6c370efe4` on all three clients, and passed final `graph validate` on all three clients. Its event log had no `apply-remote-txs-failed`, no error-level entries, no failed/no-op events, and no fatal event. Worker logs had no `:db-sync/apply-remote-txs-failed`; the only severe entries were expected local HTTP stale-target exceptions for `http-set-block-property`, documented below.
- Status: fixed by targeted test and fresh 5000-op stress verification at event/final-state and worker-log remote-apply level.
### Local HTTP set-block-property raced with deleted targets
- Date: 2026-07-01
- Graph: `cli-sync-stress-5000-20260701-20`
- Command: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-20 --config tmp/cli-sync-stress-multi-5000-20260701-20/cli.edn --root-dir tmp/cli-sync-stress-multi-5000-20260701-20/root --log-file tmp/cli-sync-stress-multi-5000-20260701-20/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Symptom: the stress event log completed successfully, but client worker logs contained severe `:db-worker-node-invoke-failed` entries for local HTTP `thread-api/apply-outliner-ops` requests. The HTTP response was `Set block property failed: block or property doesn't exist`.
- Evidence:
- Event log lines `920`, `2627`, and `11809` classify the corresponding `http-set-block-property` calls as `outcome:"race-conflict"`, `level:"info"`, status `500`.
- The three target block UUIDs were `9a7111f9-0c4f-4876-ab46-e779117b459f`, `9136b835-8f30-4557-a24a-8ef94f8a1abf`, and `6a451423-a7ac-4b79-9a20-ba87efb04d81`.
- Final settle on all clients returned recomputed/local/remote checksum `fc3492f6c370efe4`, and final `graph validate` passed on all clients.
- The event log had no `level:"error"`, no `outcome:"failed"`, no `outcome:"no-op"`, and no fatal event. Worker logs had no `:db-sync/apply-remote-txs-failed`.
- Root cause: the stress harness intentionally chooses IDs from a shared live block pool while concurrent workers delete and recycle blocks. A block can be selected for local `set-block-property`, then deleted before the HTTP outliner op reaches the worker. In that case the local mutation is correctly rejected because its target no longer exists. This does not indicate remote tx corruption or sync divergence.
- Fix: no product sync fix is required for this case. The harness already classifies the response as an expected `race-conflict`, keeps the run alive, and validates final convergence. Worker-log review for stress runs must distinguish local HTTP handler exceptions for expected stale-target operations from sync worker remote-apply failures.
- Regression test or stress verification: `cli-sync-stress-5000-20260701-20` completed `5001` started ops with matching checksums and graph validation passing on all three clients despite these expected local race conflicts.
- Status: documented expected race signal; not counted as a failed sync case unless it is accompanied by final checksum mismatch, graph validation failure, fatal event, failed/no-op event, or `:db-sync/apply-remote-txs-failed`.
### Retryable pending snapshot drift polluted `last-error`
- Date: 2026-07-01
- Graph: `cli-sync-stress-5000-20260701-cas-rebase-1`
- Command: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-cas-rebase-1 --config tmp/cli-sync-stress-cas-rebase-5000-1/cli.edn --root-dir tmp/cli-sync-stress-cas-rebase-5000-1/root --log-file tmp/cli-sync-stress-cas-rebase-5000-1/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Symptom: the run completed `5001` started ops and final validation passed on all three clients, but during `multi-client-offline-rebase`, `sync start` on client 3 failed with `sync-start-runtime-error` because `sync status` contained `last-error` code `pending-tx-snapshot-changed`.
- Evidence:
- Event log around `2026-07-01T12:32:47Z` shows `sync start reached open websocket but runtime sync error is present`.
- The `last-error` payload had `:code :pending-tx-snapshot-changed`, a captured `local-tx-ids` list, and a `current-local-tx-ids` list with one extra pending tx id.
- Final settle later succeeded: all clients recomputed local/remote checksum `e3da05c1ead3bf6b`, and final `graph validate` passed on all three clients.
- Root cause: `:pending-tx-snapshot-changed` is an internal retry/control signal, not a durable sync error. The previous retry condition re-read the mutable pending queue in the catch path. That handled ordinary missing-entity errors while the queue still differed, but it could expose the control exception as a real error if the queue changed again before the catch path or if `sync start` inspected `last-error` before the retry cleared it.
- Fix: remote apply now treats `:pending-tx-snapshot-changed` itself as retryable, regardless of what a second pending-queue read returns. It still also retries non-control apply errors when the pending tx snapshot is currently different, preserving the original missing-entity retry path.
- Regression tests:
- `frontend.worker.db-sync-test/apply-remote-txs-retries-snapshot-drift-even-if-pending-list-stabilizes-test` failed before the fix by surfacing `pending local tx snapshot changed during remote apply`; it passes after the fix.
- Adjacent retry tests passed: `apply-remote-txs-rechecks-local-txs-when-local-delete-races-temp-snapshot-test`, `apply-remote-txs-rechecks-local-txs-when-local-delete-races-temp-commit-test`, and `apply-remote-txs-delays-retry-when-local-txs-keep-changing-test`.
- Stress verification: after rebuilding `static/db-worker-node.js`, `cli-sync-stress-5000-20260701-snapshot-last-error-1` completed `5001` started ops, reached matching final checksum `5790fdbc975a6b36` on all three clients, passed final `graph validate` on all three clients, and had no event-log `pending-tx-snapshot-changed` or `sync-start-runtime-error` entries.
- Status: fixed by targeted tests and fresh 5000-op stress verification.
### Remote apply committed over a local page delete before permanent recycle delete
- Date: 2026-07-01
- Graph: `cli-sync-stress-5000-20260701-17`
- Command: `LOGSEQ_BIN=/Users/tiensonqin/Codes/projects/logseq/static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-17 --config tmp/cli-sync-stress-multi-5000-20260701-17/cli.edn --root-dir tmp/cli-sync-stress-multi-5000-20260701-17/root --log-file tmp/cli-sync-stress-multi-5000-20260701-17/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Symptom: the run was interrupted after `1498` started ops because `http-recycle-delete-page` phase `permanent-delete` returned HTTP 200 with `{"ok":true,"resultTransit":"[\"~#'\",null]"}` for page UUID `6a450134-0e3d-4025-ae1f-b802dab67185`.
- Evidence:
- Event log line `3463` created page `CLI HTTP Recycle stress-1782906831598 177`.
- Line `3495` applied raw `delete-page` to UUID `6a450134-0e3d-4025-ae1f-b802dab67185` and returned ok.
- Line `3500` applied raw `recycle-delete-permanently` to the same UUID and got `resultTransit null`.
- A post-stop query of the same client graph found the page still present with no `:logseq.property/deleted-at`, so the soft delete had been lost before permanent delete ran.
- The worker log shows sync reconnect/remote-apply activity in the same window, including `pending-txs-count 15` at `2026-07-01T11:59:48.677Z`.
- The same run also showed a harness weakness: `http-recycle-delete-page` generated page titles from `runId + seq` only, and different workers produced duplicate titles for sequences `68`, `85`, and `110`.
- Root cause: remote apply with local changes protected only the exception path from pending-local snapshot drift. It captured pending local txs, ran remote apply/rebase in a temp conn, and could then commit that temp result to the live conn even if a new local tx was added after the snapshot and before the final commit. In this case a local `delete-page` tx was applied after the remote-apply snapshot, then a successful temp remote apply committed an older DB view over it. `recycle-delete-permanently` correctly returned nil because the page was no longer recycled. Separately, sequence-only stress page titles made raw page operations vulnerable to name lookup ambiguity under concurrent workers.
- Fix:
- `logseq.db/batch-transact-with-temp-conn!` now accepts a `:before-commit` hook that runs after temp work and before live conn commit.
- `frontend.worker.sync.apply-txs/apply-remote-tx-with-local-changes!` uses that hook to abort and retry remote apply when the pending local tx id list changed since the snapshot, before the temp result can overwrite the live conn.
- The stress harness now uses operation-owned unique page titles for raw create-page, delete/restore-page, and recycle/delete-page operations.
- Regression tests:
- `frontend.worker.db-sync-test/apply-remote-txs-rechecks-local-txs-when-local-delete-races-temp-commit-test`.
- `logseq.db-test/batch-transact-with-temp-conn-before-commit-can-abort-live-commit-test`.
- JavaScript harness test `raw page delete/restore uses unique operation-owned page titles` covers uniqueness for repeated worker/sequence inputs.
- Test evidence:
- `rtk bb dev:test -v frontend.worker.db-sync-test/apply-remote-txs-delays-retry-when-local-txs-keep-changing-test -v frontend.worker.db-sync-test/apply-remote-txs-rechecks-local-txs-when-local-delete-races-temp-snapshot-test -v frontend.worker.db-sync-test/apply-remote-txs-rechecks-local-txs-when-local-delete-races-temp-commit-test -v frontend.worker.db-sync-test/apply-remote-txs-repairs-order-only-block-made-missing-by-local-reversal-test -v frontend.worker.db-sync-test/apply-remote-txs-local-delete-parent-remote-move-then-delete-parent-test -v frontend.worker.db-sync-test/apply-remote-txs-overlap-out-of-order-parent-delete-then-move-repairs-test`: 6 tests, 29 assertions, 0 failures.
- `rtk pnpm --dir deps/db test-v logseq.db-test/batch-transact-with-temp-conn-before-commit-can-abort-live-commit-test logseq.db-test/batch-transact-with-temp-conn-preserves-cardinality-one-schema-test logseq.db-test/batch-transact-with-temp-conn-preserves-retracts-test`: deps/db suite completed, 115 tests, 420 assertions, 0 failures.
- `rtk node --test scripts/cli-concurrent-edit-stress.test.mjs scripts/cli-sync-stress-workflow.test.mjs`: 30 tests, 0 failures.
- Stress verification: after rebuilding `static/db-worker-node.js`, `cli-sync-stress-5000-20260701-snapshot-last-error-1` completed `5001` started ops, reached matching final checksum `5790fdbc975a6b36` on all three clients, passed final `graph validate` on all three clients, and had no event-log `http-recycle-delete-page` nil/false failure, `sync-start-runtime-error`, or `pending-tx-snapshot-changed` entry.
- Status: root cause fixed by targeted tests and fresh 5000-op stress verification.
### `http-delete-restore-page` reused mutable shared page targets
- Date: 2026-07-01
- Graphs:
- `cli-sync-stress-1000-20260701-2`
- `cli-sync-stress-5000-20260701-1`
- `cli-sync-stress-5000-20260701-8`
- `cli-sync-stress-assert-20260701-1`
- `cli-sync-stress-5000-20260701-13`
- `cli-sync-stress-10000-20260701-1`
- `cli-sync-stress-5000-20260701-15`
- `cli-sync-stress-5000-20260701-16`
- Log examples:
- `tmp/cli-sync-stress-multi-1000-20260701-2/events.jsonl`, line `859`
- `tmp/cli-sync-stress-multi-5000-20260701-1/events.jsonl`, line `991`
- `tmp/cli-sync-stress-multi-5000-20260701-8/events.jsonl`, line `2154`
- `tmp/cli-sync-stress-assert-20260701-1/events.jsonl`, examples around `2026-07-01T09:14:19Z`, `2026-07-01T09:14:33Z`, `2026-07-01T09:16:02Z`, and `2026-07-01T09:17:24Z`
- `tmp/cli-sync-stress-multi-5000-20260701-13/events.jsonl`, lines `3388`, `5869`, `8289`, and `11521`
- `tmp/cli-sync-stress-multi-10000-20260701-1/events.jsonl`, lines `3680`, `5095`, `5741`, and `6407`
- `tmp/cli-sync-stress-multi-5000-20260701-15/events.jsonl`, lines `1312`, `3090`, `4340`, and `15852`
- `tmp/cli-sync-stress-multi-5000-20260701-16/events.jsonl`, line `7213`
- Symptom: `thread-api/apply-outliner-ops` returns HTTP 200 with `{"ok":true,"resultTransit":"[\"~#'\",false]"}` for `http-delete-restore-page` phase `delete`.
- Current evidence:
- Earlier 1000-op, 5000-op, assertion 5000-op, and 10000-op runs completed with matching checksums and final graph validation, so this no-op alone has not reproduced sync divergence.
- In `cli-sync-stress-5000-20260701-16`, the run failed fast on the no-op because the stress harness started requiring truthy raw apply results. The same page `CLI Concurrent Stress page 2` was repeatedly selected as a mutable shared page target. Line `7059` deleted it through CLI `page-delete-restore`, line `7071` restored it, line `7114` hit a concurrent `recycled-page` race while creating blocks on it, and line `7213` then got the raw HTTP `delete-page` result `false` for page UUID `6a44fc1f-ef7f-4085-8449-1adfbf325b1b`.
- Root cause: the stress harness used `mutablePage(state)` for raw `http-delete-restore-page`. That let multiple workers delete/restore the same stable page concurrently while other workers were also creating or moving blocks on the same page. `delete-page` can correctly return false when the selected page is already recycled or otherwise not a valid deletion target at apply time, so the harness was not isolating the raw outliner op it was trying to verify.
- Fix: `http-delete-restore-page` now creates a unique operation-owned page through raw `create-page`, resolves that page UUID, and then applies raw `delete-page` and `restore-recycled` to that UUID. The operation still exercises create/delete/restore sync traffic, but a false `delete-page` result is no longer hidden by shared-page target races.
- Regression test: `scripts/cli-concurrent-edit-stress.test.mjs` covers `uniqueOperationPageTitle`, including repeated calls with the same worker and sequence. The full JavaScript harness test command now passes with 30 tests.
- Stress verification: `cli-sync-stress-5000-20260701-18` completed `5001` started ops with no `http-delete-restore-page` false/no-op events, final recomputed/local/remote checksum `3cce9543989a7855` on all three clients, and final `graph validate` passed on all three clients. A separate remote-apply retry-budget issue was found in the same run and is tracked above.
- Status: fixed in the stress harness and verified by fresh 5000-op stress for this operation class; 10000-op stress still pending.
### Stress retry reused an already-invalid graph root
- Date: 2026-07-01
- Graph: `cli-sync-stress-5000-20260701-2`
- Command: `LOGSEQ_BIN=static/logseq-cli.js node scripts/cli-concurrent-edit-stress.mjs --graph cli-sync-stress-5000-20260701-2 --config tmp/cli-sync-stress-multi-5000-20260701-2/cli.edn --root-dir tmp/cli-sync-stress-multi-5000-20260701-2/root --log-file tmp/cli-sync-stress-multi-5000-20260701-2/events.jsonl --clients 3 --concurrency 8 --max-ops 5000 --sync --offline --no-e2ee --timeout-ms 20000 --settle-attempts 60 --settle-ms 1000`
- Symptom: the retry failed at `sync start` with a stale `last-error` reporting invalid reverse tx data for `move-blocks`, including multi-valued `:block/parent` and `:block/order`.
- Evidence:
- `tmp/cli-sync-stress-multi-5000-20260701-2/events.jsonl` contains an earlier run starting at `2026-07-01T07:11:50Z`, before the retry at `2026-07-01T08:29:35Z`.
- `graph validate` on that root reports the graph is already invalid, with 25 invalid entities.
- The failing `sync start` reused `local-tx 65`, `pending-local 65`, and `pending-server 99` from that existing graph state instead of starting from an empty post-fix graph.
- Root cause: the verification command reused a graph/root/log path from an earlier failed run. The retry therefore exercised stale pre-fix graph state and stale sync error state, not the newly rebuilt sync code.
- Fix: long-run verification must use a unique graph name and root directory, and the root must be checked for absence before treating the run as fresh.
- Regression test or stress verification: not a product-code regression. The next valid evidence must come from a new graph/root, starting from no existing local graph files.
- Status: invalid test run; superseded by the next fresh 5000-op run.
### Temp rebase conn lost Datascript schema for cardinality-one replacement
- Date: 2026-07-01
- Graph: observed while investigating invalid sync-start state in `cli-sync-stress-5000-20260701-2`; the graph/root was later classified as contaminated test evidence, but the helper bug was real and independently reproduced.
- Symptom: applying local pending reverse txs during remote rebase could produce invalid entities with multiple `:block/parent` or `:block/order` values. Example last-error:
`DB write failed with invalid data`, `tx-meta {:outliner-op "move-blocks" :reverse? true}`, with validation errors showing `:block/parent [264 222]` and `:block/order ["a6" "a0"]`.
- Root cause: `logseq.db/batch-transact-with-temp-conn!` built its temporary connection with `d/create-conn` and then swapped in the source `:db`. The temp connection could read the source DB, but its connection metadata did not preserve the source Datascript schema. Inner temp transacts therefore did not reliably emit replacement retractions for cardinality-one attrs, so the final replay into the live conn could accumulate values for attrs such as `:block/order` and `:block/parent`.
- Fix: the temp connection constructor now creates the isolated conn with `(:schema db)` before swapping in the source db state. This preserves Datascript cardinality and uniqueness behavior while keeping the temp conn isolated from storage writes.
- Regression tests:
- `logseq.db-test/batch-transact-with-temp-conn-preserves-cardinality-one-schema-test`
- `frontend.worker.db-sync-test/temp-conn-batch-preserves-cardinality-one-schema-test`
- Rebase adjacency still passes:
`frontend.worker.db-sync-test/rebase-local-insert-then-save-keeps-cardinality-one-values-test`,
`frontend.worker.db-sync-test/apply-remote-txs-skips-stale-move-before-later-delete-test`,
`frontend.worker.db-sync-test/apply-remote-txs-skips-stale-move-to-target-before-later-target-delete-test`,
`frontend.worker.db-sync-test/apply-remote-txs-with-local-changes-rejects-invalid-final-rebase-test`.
- Test evidence:
- `rtk pnpm --dir deps/db test-v logseq.db-test/batch-transact-with-temp-conn-preserves-cardinality-one-schema-test` completed the deps/db suite: 114 tests, 418 assertions, 0 failures.
- `rtk bb dev:test -v frontend.worker.db-sync-test/temp-conn-batch-preserves-cardinality-one-schema-test ...` completed 5 worker tests, 15 assertions, 0 failures.
- Post-fix stress verification: fresh 5000-op and 10000-op stress runs completed with final graph validation passing on all clients and no cardinality-one validation errors.
- Status: fixed and verified in targeted tests plus fresh stress runs.
## Recent db-test sync-stuck issue cluster
- Date checked: 2026-07-01
- Issues:
- `logseq/db-test#937`: existing browser graphs do not sync; console reports `Invalid local tx` with `local-tx nil`.
- `logseq/db-test#947`: browser reports `0 pending server changes` while desktop and CLI changes are already on the server.
- `logseq/db-test#969`: after suspend/resume, the app is online but RTC is stopped with `rtc-state :close`, `pending-local-ops 1`, and `local-tx == remote-tx`; clicking `Start Sync` resumes sync.
- `logseq/db-test#898`: graph stays yellow and only recovers after deleting the local graph and re-downloading.
- `logseq/db-test#890`: graph stays in `Preparing`; opening from remote graphs works but no sync indicator appears.
### Repro path: missing client-ops `local-tx`
- Target symptom: `Invalid local tx` on server `hello`, or a silent `db-sync/start-skipped` because `client-op-ready?` is false.
- State to create: graph DB and client-ops DB are both open, but `sync_meta.local-tx` is missing from the client-ops DB.
- Why this matches the issues: existing local graphs affected by old cache/migration state can have remote graph ids and pending local rows, while `local-tx` is absent. Missing `local-tx` must not be treated as `0`, because that would force the client to pull too many server txs from the beginning.
- Existing fix: `:thread-api/db-sync-start` opens DBs before starting sync, and `sync/start!` skips with `:client-op-not-ready` until client-op metadata has a real integer `local-tx`.
- Regression test: `frontend.worker.sync.restart-test/start-skips-when-client-op-local-tx-is-missing-test`.
- Expected fixed behavior: no websocket connection is opened when `local-tx` is missing, and no code initializes missing `local-tx` to `0` outside the explicit new-remote-graph/upload paths.
### Repro path: stale RTC after resume
- Target symptom: online app with `rtc-state :close`, pending local changes, and no automatic retry until manual `Start Sync`.
- State to create: current RTC client still targets the active repo/graph, but its websocket is already closed or stale after sleep/offline/resume.
- Relevant issue evidence: `logseq/db-test#969` reports `pending-local-ops 1`, `local-tx 1244`, `remote-tx 1244`, `rtc-state :close`; `logseq/db-test#780` reports stale websocket timeout after network returns.
- Regression tests:
- `frontend.handler.db-based.rtc-flows-test/resume-restart-events-do-not-depend-on-cached-rtc-lock-test`
- `frontend.worker.sync.restart-test/start-reconnects-closed-ws-with-stale-open-state-test`
- `frontend.worker.sync.restart-test/stale-loop-marks-non-open-ws-closed-test`
- `frontend.worker.sync.restart-test/ws-close-clears-inflight-before-reconnect-test`
- Expected fixed behavior: network-visible/resume triggers can restart RTC, and stale/closed websockets clear inflight state, broadcast `:closed`, and schedule reconnect instead of leaving the graph permanently stopped.