diff --git a/.agents/skills/logseq-cli/SKILL.md b/.agents/skills/logseq-cli/SKILL.md index e3f94b85d30e..3342bc5068e6 100644 --- a/.agents/skills/logseq-cli/SKILL.md +++ b/.agents/skills/logseq-cli/SKILL.md @@ -14,7 +14,7 @@ Use `logseq` to inspect and edit graph entities, run Datascript queries, and con - Run `logseq --help` to see top-level commands and global flags. - Run `logseq --help` to see command-specific options. - Use `--graph` to target a specific graph. -- Omit `--output` for human output. Set `--output json` or `--output edn` only when machine-readable output is required. +- Omit `--output` for human output. Use `--output json` or `--output edn` for structured command results. `skill show` prints raw Markdown in every output mode. ## Command groups (from `logseq --help`) @@ -27,7 +27,7 @@ Use `logseq` to inspect and edit graph entities, run Datascript queries, and con - `graph list|create|switch|remove|validate|info|export|import|backup list|backup create|backup restore|backup remove` - `server list|cleanup|start|stop|restart` - `doctor` -- `sync status|start|stop|upload|download|remote-graphs|ensure-keys|grant-access|config set|get|unset` +- `sync status|start|stop|upload|download|asset download|remote-graphs|ensure-keys|grant-access|config set|get|unset` - Authentication: `login|logout` - Utilities: `agent bridge`, `completion`, `debug`, `example`, `skill` @@ -43,10 +43,7 @@ Use `logseq` to inspect and edit graph entities, run Datascript queries, and con ## Command option policy -- Do not memorize or hardcode command options in this skill. -- Before running any command, always check live options with: -- `logseq --help` -- `logseq --help` +- Check the full command path with `logseq --help` before using its options; for example, `logseq upsert block --help`. ## Task command preference @@ -59,11 +56,7 @@ Use `logseq` to inspect and edit graph entities, run Datascript queries, and con ## Examples policy - Do not maintain long static command examples in this skill. -- Use `logseq example` as the source of truth for runnable examples. -- Before proposing runnable commands, always inspect live examples with: - - `logseq example` - - `logseq example ` - - `logseq example --help` +- Use `logseq example ` for starting points, then check the command's help and input format before using an example. - Prefer exact selectors when possible (for example, `logseq example upsert page`). - Use prefix selectors when grouped examples are needed (for example, `logseq example upsert`). - Replace placeholder ids/uuids in retrieved examples with real entities from the target graph. @@ -77,6 +70,9 @@ Use `logseq` to inspect and edit graph entities, run Datascript queries, and con - Preserve the source structure as sibling and child blocks. Each logical bullet, row, or subsection should usually become its own block. - Reserve `--content` for true single-block writes or targeted updates to one existing block. - If the user asks to write notes, lists, outlines, imported data, or any content that already has structure, do not flatten it into one long `--content` string. +- Create multiple sibling or child blocks with `upsert block --blocks ` or `--blocks-file `. Use Markdown list indentation for the hierarchy; for example, `--blocks $'- Parent\n - Child\n- Sibling'` in Bash or Zsh. +- Specify `--target-page`, `--target-id`, or `--target-uuid` when the destination matters. Create mode defaults to the current journal if no target is given. `--pos sibling` requires a block target. +- `--blocks` and `--blocks-file` are create-mode inputs. With `--id` or `--uuid`, `upsert block` updates one existing block and rejects those options. Use `--dry-run` in create mode to inspect planned operations without writing. ## Tag association semantics @@ -86,7 +82,7 @@ Use `logseq` to inspect and edit graph entities, run Datascript queries, and con - Tag values may be tag title/name strings, db/id, UUID, or `:db/ident` values. - String tag values may include a leading `#`, but they should still be passed inside `--update-tags`. - If the user asks to tag a block or page, prefer explicit tag association. -- Tags must already exist and be public. If needed, create the tag first with `upsert tag --name ""`. +- Tags must already exist. If needed, create the tag first with `upsert tag --name ""`. Do not assume a tag's public property controls whether it can be associated; tag resolution does not check that property. ## Anti-patterns and correct usage @@ -108,19 +104,15 @@ Use `logseq` to inspect and edit graph entities, run Datascript queries, and con - Anti-pattern: pass tag updates as a comma-separated string, for example `--update-tags "AI-GENERATED,CLI"`. - Correct usage: pass an EDN vector, for example `--update-tags '["AI-GENERATED" "CLI"]'`. -### Missing or private tags +### Missing tags - Anti-pattern: retry the same tag association command after a tag association failure without checking tag state. -- Correct usage: verify the tag exists and is public; create it first when needed with `upsert tag --name ""`. +- Correct usage: verify the tag exists; create it first when needed with `upsert tag --name ""`. ## Tips - `query list` returns both built-ins and `custom-queries` from `cli.edn`. -- `agent bridge --dry-run` checks the local bridge setup, resolves `:agent-name` or hostname, registers the AgentBridge name in the graph, finds routable `#Task` TODO blocks assigned to that AgentBridge name, and prints the Codex commands it would run without starting Codex or writing `agent-session-id`. -- `agent bridge` starts/reuses db-worker-node, listens to db-worker-node events, scans routable tasks on startup and each event, starts `codex exec --json` for matched tasks, stores the Codex session/thread id in `agent-bridge-sessions.edn`, and writes it to the task's `agent-session-id` property. -- `show --id` accepts either one db/id or an EDN vector of ids. -- `remove block --id` also accepts one db/id or an EDN vector. +- `agent bridge` starts/reuses db-worker-node, listens to db-worker-node events, scans routable tasks on startup and each event, starts one in-process master Codex session, and dispatches matched task/comment requests to that session. +- `show --id` and `remove block --id` accept one positive db/id or a bracketed list such as `'[123,456]'`. Their id parser splits integers on commas or whitespace; it does not parse EDN. - `upsert block` enters update mode when `--id` or `--uuid` is provided. -- Always verify command flags with `logseq --help` and `logseq <...> --help` before execution. - If `logseq` reports that it doesn’t have read/write permission for `root-dir`, then check filesystem permissions or set `LOGSEQ_CLI_ROOT_DIR`. -- In sandboxed environments, `graph create` may print a process-scan warning to stderr; if command status is `ok`, the graph is still created. diff --git a/.agents/skills/logseq-rest-api/SKILL.md b/.agents/skills/logseq-rest-api/SKILL.md new file mode 100644 index 000000000000..2226db5077bc --- /dev/null +++ b/.agents/skills/logseq-rest-api/SKILL.md @@ -0,0 +1,131 @@ +--- +name: logseq-rest-api +description: Call the Logseq semantic REST API (db-sync worker) with a graph-scoped personal access token, including E2EE-encrypted graphs. Use when writing integrations, scripts, or agent tooling that read or write Logseq DB graphs over HTTP, when working with `logseq_pat_` tokens, or when debugging API behavior on encrypted vs plain graphs. +--- + +# Logseq Semantic REST API + +Use this skill to operate the semantic REST API served by the db-sync Cloudflare +worker (local dev: `node deps/db-sync/worker/dist/node-adapter.js`). The API +surface is defined by `GET /openapi.json`; handler code lives in +`deps/db-sync/src/logseq/db_sync/worker/handler/semantic.cljs`, routes in +`.../worker/routes/semantic.cljs`. + +## Auth + +```bash +curl -H "Authorization: Bearer logseq_pat_..." /api/v1/graphs +``` + +- Personal access tokens are graph-scoped (`logseq_pat_` prefix) with `read`, + `write`, or `read+write` permission. A token only works on its own graph — + requests against another graph return `403 forbidden`; a write-scoped token on + a read op returns `403 insufficient scope`. +- Creating PATs and creating graphs (`POST /graphs`, body `{"graph-name": ..., + "graph-e2ee?": true}`) require a user JWT, not a PAT. +- Rate limits (Cloudflare, per PAT or user): **read 120/min, write 20/min** → + `429 {"error":"rate limit exceeded"}`; limiter down → `503`. The local node + adapter stubs limiters to unlimited. + +## Operations + +39 ops under `/api/v1/graphs/{graph-id}/...` plus `/api/v1/graphs` +(`listGraphs`, includes `graph-e2ee?` flag). Groups: pages, blocks (get, +update, delete, move, insert-children, insert-tree), block-properties (set, +delete, batch-set, batch-delete), tags (+ `/objects`), tasks, capture, +properties, assets, search, and 3 E2EE helpers. Non-`/api/v1` endpoint: +`GET /e2ee/graphs/{graph-id}/aes-key` (PAT allowed). + +Request-shape gotchas (verified locally): +- `insertBlockChildren`: body `{"position":"append|prepend","blocks":[{title,children?}]}`, block-id in path. +- `insertBlockTree`: body `{"target-id":uuid,"position":"append","blocks":[...]}`. +- `moveBlocks`: `{"block-ids":[uuid],"target-id":uuid,"position":"before|after|first-child|last-child"}`. +- `batchSetBlockProperty`/`batchDeleteBlockProperty`: `{"entries":[{"block-id","property-id","value"?}]}`. +- `createAsset`: query `file-name` (needs a known extension), `size`, `checksum` + (64-hex SHA-256), optional `title`, `page-id`, `encoding=base64`; body is raw + bytes (octet-stream). +- **Path params are UUIDs only.** Passing an ident like `user.property/x` + URL-encoded 404s on every graph — resolve UUIDs via `listProperties`/`listTags`. + +## E2EE graphs + +Text encryption covers `:block/title` and `:block/name`; orders, tags, property +values, and refs remain plaintext to the server. Asset file bytes are also encrypted. + +**Title write rule**: every `title` field on a write op must be an *encrypted +package* — a transit string. Plaintext → `400 "content must be an encrypted +package on e2ee graphs"`. Gated ops: pages create/update, blocks update, +tags create/update, tasks create, properties create/update, +blocks-insert-children, blocks-insert-tree, capture, assets-create (the `title` +query param — effectively required on e2ee since a missing title fails the +gate; `file-name` stays plaintext). + +**Producing ciphertext** — `POST /api/v1/graphs/:id/e2ee/encrypt` +`{"key":,"texts":["..."]}` requires the graph's base64 raw 32-byte +AES-GCM key and returns canonical Transit `[iv ciphertext]` packages. The helper +receives both the key and plaintext; integrations can instead encrypt locally. +RSA-envelope content is rejected, preserving the existing client storage format. + +**Names**: creating or renaming a page, tag, or property requires a separate +`name` field containing the encrypted normalized lowercase name. This also applies +to `updateBlock` when its target is one of those named entities. For example, +encrypt `"Project Alpha"` and `"project alpha"` separately, then send +`{"title":,"name":}`. Never lowercase ciphertext. + +**Assets**: encrypt the original file bytes with the graph's AES-GCM key and a +fresh 12-byte IV, then send the canonical Transit `[iv ciphertext]` package as the +body, optionally base64-encoding that whole package for transport. `size` is the +original plaintext byte length; `checksum` is its SHA-256. The title must also be +encrypted. Plaintext bodies and malformed packages return 400 without creating an +Asset block. The `upload_asset` and `get_asset_image` MCP tools support plain graphs; +use client encryption/decryption with the REST API for encrypted graphs. + +**Getting the AES key** (agent holds the user's RSA private key): +`GET /e2ee/graphs/:id/aes-key` → `encrypted-aes-key-base64` (RSA-OAEP wrapped); +unwrap with the user's pkcs8 private key → base64 raw key. + +**Reading back**: `POST .../e2ee/decrypt {"texts":[],"key":}` → +plaintext. `GET .../e2ee/public-keys` lists member RSA keys. + +**Verified unusable / degraded on E2EE graphs** (probed on local server): + +| Op | Behavior on e2ee | +|---|---| +| `searchGraph` | Runs, but only matches **ciphertext** substrings — plaintext keyword search is impossible (server can't read titles) | +| `listPageReferences` | Only returns client-authored refs — ref extraction is skipped for API writes on e2ee (`[[name]]` can't exist in ciphertext titles), and the API has no way to supply ref UUIDs, so agents cannot create references on e2ee | +| Property values on `:db.type/ref` props | Plaintext titles can't resolve (`:block/title` holds ciphertext) → 400. Pass the entity **UUID** or the **ciphertext title** instead — both resolve | +| `decryptE2eeText` | Requires the graph AES key and canonical `[iv ct]` packages | +| Plaintext titles on any gated write | 400 by design | + +Also verified working on e2ee (ciphertext titles): every CRUD op for pages, +blocks (incl. move + nested tree inserts), tags, tasks, capture, properties, +assets (`file-name` + ciphertext `title` + encrypted body), `listGraphs`, all three +e2ee helpers. + +## Generic API semantics (same on plain graphs) + +- `default`-type properties are `:db.type/ref`: `setBlockProperty` expects the + value to resolve to a **text block** entity (uuid/ident/title) — a bare string + fails resolution (400) or validation. `node`-type props take entity refs. +- Deletes return `204` with empty body. Errors: `{"error": "..."}` (400/403/404/409/429/500). +- Pagination: list ops return `{"": [...], "cursor"?}`. + +## MCP endpoint + +`POST /mcp` (Streamable HTTP) on the same server exposes tools/list with the 4 +code-mode tools (`search`, `execute`, `upload_asset`, `get_asset_image`) plus +one tool per OpenAPI operationId (39 ops). `search`/`execute` run code-mode JS +against the spec; the per-op tools map arguments to path params + query + body. + +## Testing locally + +```bash +cd deps/db-sync && pnpm install --ignore-workspace +DB_SYNC_PORT=8787 DB_SYNC_DATA_DIR=/tmp/dbsync DB_SYNC_ALLOW_UNVERIFIED_JWT_CLAIMS=true \ + COGNITO_ISSUER=x COGNITO_CLIENT_ID=x COGNITO_JWKS_URL=x \ + node worker/dist/node-adapter.js +``` + +Rebuild after cljs changes: `clojure -M:cljs compile db-sync-node`. +Tests: `bb dev:db-sync-test` (cljs handler tests) and +`pnpm test:chatgpt-app` in `deps/db-sync` (MCP/tools node tests). diff --git a/.agents/skills/logseq-review-workflow/SKILL.md b/.agents/skills/logseq-review-workflow/SKILL.md index 97aebd0e94ec..ed4127b346e3 100644 --- a/.agents/skills/logseq-review-workflow/SKILL.md +++ b/.agents/skills/logseq-review-workflow/SKILL.md @@ -9,7 +9,7 @@ description: Review Logseq code changes, PRs, patches, commit ranges, or impleme The main agent drives the review. It identifies scope, loads routing rules, launches independent read-only subagents for each review pass, collects candidate findings, validates the actionable ones, deduplicates overlap, and writes the final conclusion. -Each pass subagent only collects issues. It must not edit files, stage changes, commit, push, or rewrite code. It returns candidate findings, evidence, checks already run, and unresolved questions to the main agent. +Each pass subagent collects review evidence. It must not edit files, stage changes, commit, push, or rewrite code. It returns candidate findings, evidence, checks already run, and unresolved questions to the main agent. The System Additions pass also assesses necessity, maintenance cost, and simpler alternatives, returning an inventory with dispositions separate from findings. Review every pass through three layers: @@ -108,8 +108,9 @@ Passes: | Performance | [`rules/passes/performance.md`](./rules/passes/performance.md) | | Test coverage | [`rules/passes/test-coverage.md`](./rules/passes/test-coverage.md) | | Repository convention | [`rules/passes/repository-convention.md`](./rules/passes/repository-convention.md) | +| System Additions | [`rules/passes/system-additions.md`](./rules/passes/system-additions.md) | -Ask each subagent to inspect only its assigned pass and return only candidate findings, supporting evidence, checks already run, and unresolved questions. While up to 4 subagents run in parallel, the main agent may prepare aggregation and validation steps but must keep launching pending passes as slots open and must wait for every pass report before the final review. If subagents are unavailable or concurrent launch is not possible, run each pass locally with the same rule files and state that delegation or concurrency was unavailable in the verification summary. +Ask each subagent to inspect only its assigned pass and return candidate findings, supporting evidence, checks already run, and unresolved questions, plus the inventory and simplification assessments for System Additions. While up to 4 subagents run in parallel, the main agent may prepare aggregation and validation steps but must keep launching pending passes as slots open and must wait for every pass report before the final review. If subagents are unavailable or concurrent launch is not possible, run each pass locally with the same rule files and state that delegation or concurrency was unavailable in the verification summary. ### 4. Aggregate pass results @@ -120,6 +121,7 @@ Wait for all pass subagents before writing the final review. Then: 3. Discard findings without concrete evidence or turn them into questions. 4. Preserve the originating pass name for each retained finding. 5. Validate every actionable finding before including it. +6. Preserve the System Additions inventory and its necessity assessments separately from findings. An addition alone is not an issue, but supported simplification findings must not be discarded merely because the code works or has no measured runtime regression. For executable behavior paths, validate with an appropriate Logseq interaction path: - `logseq-repl` for ClojureScript functions, DataScript state, importer/exporter behavior, renderer state, Electron, or worker runtime behavior. @@ -156,7 +158,7 @@ Each finding should include: ```markdown - **Severity:** Blocking | Important | Minor | Question -- **Category:** Correctness | Data contract | Regression | Failure mode | Migration validation | Performance | Test coverage | Repository convention +- **Category:** Correctness | Data contract | Regression | Failure mode | Migration validation | Performance | Test coverage | Repository convention | System Additions - **Location:** `path/to/file.cljs:line` - **Issue:** What is wrong. - **Impact:** Concrete user, data, runtime, or maintenance impact. @@ -167,6 +169,8 @@ Separate findings with a horizontal rule (`---`) when reporting more than one fi If there are no findings, say what was reviewed and which rule modules were applied. +Include a compact System Additions inventory with Retain / Simplify / Question conclusions even when there are no findings, following the pass rule's output requirements. Report supported cleanup findings alongside other findings; explain rejected alternatives when no simplification is supported. State when no additions were found. + Add a short verification summary after findings or after the no-findings statement. Include the CLI commands, REPL probes, Chrome/browser scenarios, Desktop UI actions, static evidence, and any relevant checks that could not be run. ## Review checklist before final response @@ -174,7 +178,7 @@ Add a short verification summary after findings or after the no-findings stateme - Did you apply `rules/common.md`? - Did you route every touched library/module to its rule file? - Did you launch one read-only subagent for each independent pass with at most 4 running concurrently, starting new pass subagents as slots opened, or state why delegation or concurrency was unavailable? -- Did each subagent only collect issues and avoid modifying code? +- Did each subagent stay within its review pass and avoid modifying code? - Did you wait for all pass reports before writing the final review? - Did you deduplicate and validate actionable findings before including them? - Did you run targeted runtime verification after static inspection for every affected web-app, desktop-app, and Logseq CLI surface? @@ -182,6 +186,7 @@ Add a short verification summary after findings or after the no-findings stateme - Did you distinguish proven issues from questions? - Did you check persisted data, migrations, or protocol compatibility when relevant? - Did you run the migration validation pass and explicitly decide whether the reviewed change requires `frontend.worker.db.migrate/schema-version->updates`, migration `migrate-updates`, a `logseq.db.frontend.schema/version` bump, or migration tests? +- Did System Additions assess actual consumers, benefit versus maintenance cost, and simpler alternatives across all ten categories, with dispositions and actionable cleanup findings rather than only an inventory? - Did you check tests and name exact missing test coverage? - Did every actionable finding have applicable validation evidence, using `logseq-repl`, `logseq-cli`, `chrome`, or `computer-use` for executable behavior paths and static/protocol/build evidence for non-executable findings? - Did you avoid asking for broad rewrites when a targeted fix is enough? diff --git a/.agents/skills/logseq-review-workflow/rules/modules/db-model.md b/.agents/skills/logseq-review-workflow/rules/modules/db-model.md index f103d9893e50..c4a1dca84b4d 100644 --- a/.agents/skills/logseq-review-workflow/rules/modules/db-model.md +++ b/.agents/skills/logseq-review-workflow/rules/modules/db-model.md @@ -10,6 +10,7 @@ Apply when a change touches built-in properties, common keywords, DB schema, mig - Built-in property changes require matching migrations in `frontend.worker.db.migrate/schema-version->updates`. - Persisted data shape changes require migration, import/export, and sync review. - DB graph and file graph behavior should be intentionally different only when documented by the domain model. +- DB graphs do not support `((uuid))` block refs; blocks and pages are both nodes, and node refs uniformly use `[[uuid]]`. Do not add `(())` handling. ## Red flags diff --git a/.agents/skills/logseq-review-workflow/rules/passes/subagent-output.md b/.agents/skills/logseq-review-workflow/rules/passes/subagent-output.md index 620a76afb983..38ddf119e869 100644 --- a/.agents/skills/logseq-review-workflow/rules/passes/subagent-output.md +++ b/.agents/skills/logseq-review-workflow/rules/passes/subagent-output.md @@ -18,7 +18,7 @@ Use this output contract for every `logseq-review-workflow` pass subagent. ### Candidate findings - **Severity:** Blocking | Important | Minor | Question -- **Category:** Correctness | Data contract | Regression | Failure mode | Migration validation | Performance | Test coverage | Repository convention +- **Category:** Correctness | Data contract | Regression | Failure mode | Migration validation | Performance | Test coverage | Repository convention | System Additions - **Location:** `path/to/file.cljs:line` - **Issue:** What is wrong. - **Evidence:** Code path, invariant, test, runtime observation, contract, or command output inspected. @@ -36,3 +36,5 @@ Use this output contract for every `logseq-review-workflow` pass subagent. ``` If there are no findings, state the files and behavior areas inspected and why they passed this pass. + +For System Additions, also include a separate `### Additions inventory` section with Retain / Simplify / Question assessments as defined in [`system-additions.md`](./system-additions.md), even when there are no candidate findings. Compare demonstrated benefit with ongoing maintenance obligations and investigate smaller alternatives. Inventory dispositions are not severity ratings; evidence-backed unnecessary complexity must also appear under candidate findings, not only in the inventory. diff --git a/.agents/skills/logseq-review-workflow/rules/passes/system-additions.md b/.agents/skills/logseq-review-workflow/rules/passes/system-additions.md new file mode 100644 index 000000000000..973e57188d92 --- /dev/null +++ b/.agents/skills/logseq-review-workflow/rules/passes/system-additions.md @@ -0,0 +1,55 @@ +# System Additions Pass + +Identify what the reviewed change adds to the system and investigate whether each addition earns its ongoing maintenance cost. Look for unnecessary additions and additions whose narrow benefit could be provided by a substantially simpler design. Inspect additions inside existing files as well as newly added files. For implementation plans, assess proposed additions and distinguish stated requirements from unresolved design choices. An inventory alone does not complete this pass. + +## Addition categories + +| Category | Checks | +|---|---| +| Files and modules | Identify new responsibilities and whether a separate file or module is justified. Compare with existing implementations for duplicated logic or unnecessary configuration and abstraction. Distinguish genuine additions from moves, renames, and generated files. | +| DB schema | Identify new attributes, properties, classes, tables, indexes, and other persistent structures. Check whether the existing model can express the requirement and whether derived or temporary state needs persistence. Include schema additions in existing files. | +| Long-running code | Identify background tasks, polling, timers, subscriptions, listeners, workers, and persistent loops. Check why continuous execution is needed, who starts and owns it, when it stops, and whether repeated initialization or missing cleanup can leave duplicate work active. | +| Dependencies | Identify new npm/Maven packages and external services. Compare with existing capabilities and inspect the additional build, packaging, and runtime requirements. | +| Configuration and flags | Identify new settings, environment variables, and feature flags. Check whether the choice needs to be exposed and which additional behavior combinations must be maintained and tested. | +| Global state and caches | Identify new atoms, registries, caches, and singletons. Trace ownership, invalidation, and cleanup, including graph switches and window boundaries. | +| Exposed contracts | Identify new APIs, CLI commands, IPC messages, events, and extension points. Check why each interface must be exposed and which consumers require it. | +| Persisted artifacts | Identify new disk files, localStorage or IndexedDB entries, temporary directories, and log storage. Check ownership, retention, cleanup, and capacity limits beyond the DB schema itself. | +| Execution boundaries | Identify new processes, threads, workers, and network services. Check why the boundary is necessary and what communication, deployment, and failure-handling responsibilities it introduces. | +| Abstractions and implementation branches | Identify new adapters, framework-like wrappers, platform branches, and parallel implementations. Check for a concrete requirement and whether an existing clear path can satisfy it without compatibility layers or speculative generalization. | + +## Necessity and simplification assessment + +For each addition or cohesive group: + +1. Establish the concrete requirement and actual consumers. Trace production callers, indirect registration, persisted readers/writers, and supported external contracts. Distinguish these from tests, fixtures, generated references, and hypothetical future use; reference counts alone do not prove necessity or disuse. +2. Describe the benefit and the ongoing obligations it introduces: state synchronization, cleanup and retention, failure recovery, platform branches, deployment or dependency updates, configuration combinations, and tests or documentation that must remain in sync. Consider the whole dependent surface, not only lines added. +3. Investigate a smaller way to meet the same requirement. Consider deleting an unused surface, deriving duplicated state, merging an artifact or interface into its existing owner, keeping a one-off operation local, or replacing custom machinery with an existing capability. Identify what code, state, files, flags, tests, or maintenance obligations actually disappear; moving complexity elsewhere is not a simplification. +4. Compare the candidate with the strongest reason to retain the addition. A small feature can justify substantial machinery when it protects data integrity, security, recovery, or a supported platform. Conversely, working code is not sufficient justification for maintaining an unused table, duplicated field, speculative extension point, or separate subsystem for a minor convenience. +5. Conclude **Retain**, **Simplify**, or **Question**, with evidence. For Simplify, name the smallest cleanup, the behavior and contracts preserved, and the check that can demonstrate preservation. For Question, name the missing evidence or product decision instead of assuming the addition is necessary. + +Separate behavior-preserving cleanup from proposals to drop a feature or guarantee. If the only meaningful reduction gives up supported behavior, report the benefit/cost tradeoff as a product or architecture question; do not present it as safe cleanup or implement it during review. + +## Review boundaries and evidence + +- Inventory every applicable category; an addition is not inherently a problem. Do not demand removal merely because something is new or because a rationale is undocumented. +- Base necessity concerns on consumer evidence, concrete duplication, an existing simpler capability, or identifiable maintenance obligations disproportionate to the demonstrated benefit. Explain the comparison; vague claims of overengineering or a preference for fewer files are insufficient. A supported structural cleanup need not wait for a runtime failure or a measured performance regression to become a finding. +- Focus on the need for new persistent structures and exposed interfaces. Data contract and Migration validation own detailed contract correctness, migration requirements, and schema-version checks. +- Focus on the need for ongoing work, state ownership, and lifecycle boundaries. Note related failure or performance concerns for the corresponding passes; the main agent deduplicates shared findings. +- Follow the main workflow's validation requirements. Runtime claims such as duplicate workers, leaked subscriptions, or state surviving a graph switch require an applicable Logseq interaction. Structural concerns can use static evidence when no executable behavior path applies; explain why. + +## Output + +Return results using [`subagent-output.md`](./subagent-output.md), plus a separate additions inventory with necessity assessments even when there are no findings. Report evidence-backed unnecessary complexity as System Additions candidate findings using the normal severity guidance; do not bury actionable cleanup solely in the inventory. Deduplicate cleanup that also fixes a bug with the corresponding pass. + +For each addition, record: + +- category and location, including the symbol or artifact where useful +- what was added and its purpose, supported by code, tests, or a documented requirement; label inferences and unknowns +- the owning module and lifecycle or ongoing maintenance responsibility, as applicable +- actual consumers, demonstrated benefit, and the main ongoing maintenance obligations +- Retain / Simplify / Question, with the reason; for a simplification, name the surface removed or reduced and the preservation check +- related finding or unresolved question, if any + +Group related additions to keep the inventory compact. An item spanning categories, such as a worker that adds an execution boundary and ongoing work, may occupy one entry tagged with both categories. List categories with no additions in one short line; distinguish uninspected categories from confirmed absence. Mark moves, renames, and generated artifacts as such rather than treating them as new architectural responsibilities. For plans, label entries as proposed rather than implemented. + +If no simplifications are supported, briefly identify the alternatives investigated and the concrete requirements that ruled them out. Do not substitute “no correctness bug found” for this assessment. diff --git a/.carve/ignore b/.carve/ignore index d1e0a986063d..604526d30bab 100644 --- a/.carve/ignore +++ b/.carve/ignore @@ -11,67 +11,31 @@ frontend.debug/defn frontend.debug/print ;; Lazily loaded frontend.extensions.code/editor -;; Referenced in commented TODO -frontend.extensions.pdf.utils/get-page-bounding ;; Protocol fn wrapper that could be used frontend.fs/readdir -;; Referenced in TODO -frontend.handler.metadata/update-properties! +;; Used in macro frontend.handler.user/ on). Set "false" only for plain-HTTP +# access on a LAN. +#HYPHA_COOKIE_SECURE= # Issued-JWT lifetime. jose duration string ("30d", "12h", "60m"). HYPHA_JWT_TTL=30d # Host port to publish hypha-server on. Default 3000. HYPHA_HOST_PORT=3000 + +# Host address the port is published on. Default 127.0.0.1: reachable only +# from this machine, i.e. through a reverse proxy running here. Set 0.0.0.0 +# for LAN access without a proxy, or when the proxy runs on another host. +#HYPHA_BIND=0.0.0.0 diff --git a/.github/pr-labeler.yml b/.github/pr-labeler.yml index 5431e79a0aea..1753e5726d20 100644 --- a/.github/pr-labeler.yml +++ b/.github/pr-labeler.yml @@ -1,4 +1,9 @@ -:type/feature: ['feature/*', 'feat/*', '*:feat/*'] -:type/enhancement: ['enhancement/*', 'enh/*', 'enhance/*', 'improve/*', '*:enhance/*'] -:type/bug-fix: ['fix/*', 'fix*', 'bug/*', 'bug-fix/*', 'bugfix/*', 'bug-fixes/*', 'bugfixes/*', '*:fix/*'] -:type/dev: ['chore/*', 'test/*', 'docs/*', 'build/*', 'ci/*', 'misc/*', 'dev/*', '*:dev/*', '*:chore/*', '*:test/*'] +# actions/labeler (v5+) format: regexps matched against the pull request's head branch name. +':type/feature': + - head-branch: ['^feature/', '^feat/', ':feat/'] +':type/enhancement': + - head-branch: ['^enhancement/', '^enh/', '^enhance/', '^improve/', ':enhance/'] +':type/bug-fix': + - head-branch: ['^fix', '^bug/', '^bug-fix/', '^bugfix/', '^bug-fixes/', '^bugfixes/', ':fix/'] +':type/dev': + - head-branch: ['^chore/', '^test/', '^docs/', '^build/', '^ci/', '^misc/', '^dev/', ':dev/', ':chore/', ':test/'] diff --git a/.github/scripts/hypha-patch-anchors.sh b/.github/scripts/hypha-patch-anchors.sh index 2b5ae052fb2b..f896e0530d18 100755 --- a/.github/scripts/hypha-patch-anchors.sh +++ b/.github/scripts/hypha-patch-anchors.sh @@ -19,9 +19,11 @@ check() { local expected="$3" local result result=$(bash -c "$cmd" 2>&1) - # Numerical comparison: -eq tolerates trailing whitespace (rg -c "1\n"), - # and falls through to FAIL when result is non-numeric (e.g. rg error). - if [[ "$result" -eq "$expected" ]] 2>/dev/null; then + # rg -c prints nothing when there is no match. Anything that is not a plain + # count (e.g. an rg error for a missing file) is a FAIL; it must not reach + # the arithmetic comparison, where a syntax error aborts the whole script. + result="${result:-0}" + if [[ "$result" =~ ^[0-9]+$ ]] && (( result == expected )); then echo "PASS: $name" else echo "FAIL: $name (expected '$expected', got '$result')" @@ -30,8 +32,8 @@ check() { } # === Patch #1 === -check "patch-1: :user/login multimethod exists" \ - "rg -c 'defmethod events/handle :user/login' src/main/frontend/handler/events/ui.cljs" \ +check "patch-1: :user/login event exists" \ + "rg -c 'defevent! :user/login' src/main/frontend/handler/events/ui.cljs" \ "1" # === Patch #2 === @@ -46,7 +48,7 @@ check "patch-3: logged-in? defn exists in handler/user.cljs" \ # === Patch #4 === check "patch-4: new-db-graph-inner component exists in components/repo.cljs" \ - "rg -c 'rum/defc new-db-graph-inner' src/main/frontend/components/repo.cljs" \ + "rg -c '(rum|hsx)/defc new-db-graph-inner' src/main/frontend/components/repo.cljs" \ "1" # === Patch #5 === @@ -90,6 +92,34 @@ check "patch-9: local-uploadable-graph? defends against stale :remote? flag" \ "rg -c 'HYPHA-PATCH-009' src/main/frontend/components/repo.cljs" \ "1" +# === Patches #10-#22 (counts measured 2026-11-14) === +check "patch-10: e2ee password persistence secret" "rg -c 'HYPHA-PATCH-010' src/main/frontend/worker/sync/crypt.cljs" "1" +check "patch-11: back/forward buttons in installed PWA" "rg -c 'HYPHA-PATCH-011' src/main/frontend/components/header.cljs" "1" +check "patch-12a: Hypha token refresh + logout in handler/user" "rg -c 'HYPHA-PATCH-012' src/main/frontend/handler/user.cljs" "2" +check "patch-12b: worker refresh via ui-request" "rg -c 'HYPHA-PATCH-012' src/main/frontend/worker/sync/auth.cljs" "1" +check "patch-12c: :hypha-refresh-id-token ui-action" "rg -c 'HYPHA-PATCH-012' src/main/frontend/handler/worker.cljs" "1" +check "patch-13a: enriched graph-already-exists error" "rg -c 'HYPHA-PATCH-013' src/main/frontend/worker/sync/upload.cljs" "1" +check "patch-13b: name-collision catch + take-over handler" "rg -c 'HYPHA-PATCH-013' src/main/frontend/handler/db_based/sync.cljs" "2" +check "patch-13c: resolve dialog event" "rg -c 'HYPHA-PATCH-013' src/main/frontend/handler/events/rtc.cljs" "1" +check "patch-14a: no demo graph in Hypha mode" "rg -c 'HYPHA-PATCH-014' src/main/frontend/handler.cljs" "1" +check "patch-14b: name-collision banner" "rg -c 'HYPHA-PATCH-014' src/main/frontend/components/repo.cljs" "3" +check "patch-15a: literal-slash define" "rg -c 'HYPHA-LITERAL-SLASH' deps/common/src/logseq/common/util/namespace.cljs" "3" +check "patch-15b: literal-slash in outliner validate" "rg -cF 'literal-slash?' deps/outliner/src/logseq/outliner/validate.cljs" "2" +check "patch-15c: literal-slash in bin/hypha-build" "rg -c 'HYPHA-LITERAL-SLASH' bin/hypha-build" "2" +check "patch-16a: upsert page --parent in OCaml CLI" "rg -c 'HYPHA-PATCH-016' cli/lib/upsert.ml" "3" +check "patch-16b: parent fields in the upsert spec" "rg -c 'remove_parent' cli/spec/commands/upsert.mli" "2" +check "patch-18: :date by journal-day in OCaml CLI" "rg -c 'HYPHA-PATCH-018' cli/lib/upsert.ml" "1" +check "patch-20: enable-history toggle" "rg -c ':property.built-in/enable-history' src/main/frontend/components/property/config.cljs" "1" +check "patch-21a: property-history viewer" "rg -c 'property-history-cp' src/main/frontend/components/content.cljs" "2" +check "patch-21b: property-history i18n" "rg -c ':block/property-history' src/resources/dicts/en.edn" "1" +check "patch-22: web download binds runtime" "rg -c 'HYPHA-PATCH-022' src/main/frontend/handler/db_based/sync.cljs" "1" + +check "patch-25a: server confirms journaled tx-ids" "rg -c 'HYPHA-PATCH-025' deps/db-sync/src/logseq/db_sync/worker/handler/sync.cljs" "1" +check "patch-25b: client acks its own tx-ids in pull/ok" "rg -c 'HYPHA-PATCH-025' src/main/frontend/worker/sync/apply_txs.cljs" "1" + +check "patch-26a: server pages the pull" "rg -c 'HYPHA-PATCH-026' deps/db-sync/src/logseq/db_sync/worker/handler/sync.cljs" "1" +check "patch-26b: client pulls the next page" "rg -c 'HYPHA-PATCH-026' src/main/frontend/worker/sync/handle_message.cljs" "1" + # Future patches: add new check() lines here, parallel to HYPHA_PATCHES.md. exit $exit_code diff --git a/.github/workflows/build-android.yml b/.github/workflows/build-android.yml index 30e0191a7e13..0e87efeb7f76 100644 --- a/.github/workflows/build-android.yml +++ b/.github/workflows/build-android.yml @@ -134,8 +134,12 @@ jobs: - name: Sync public to Android Project run: pnpm exec cap sync android + # Google stopped serving the obsolete `tools` package; the action default + # (`tools platform-tools`) now fails with "Failed to find package 'tools'". - name: Setup Android SDK uses: android-actions/setup-android@v3.2.2 + with: + packages: platform-tools - name: Build Android run: | diff --git a/.github/workflows/build-desktop-release.yml b/.github/workflows/build-desktop-release.yml index ba9d405eb03c..9f3c9319498b 100644 --- a/.github/workflows/build-desktop-release.yml +++ b/.github/workflows/build-desktop-release.yml @@ -10,6 +10,8 @@ on: type: choice required: true options: + # NOTE: For now, we only have beta channel to be released on GitHub + # - stable - beta - nightly - non-release @@ -43,6 +45,11 @@ on: type: boolean required: true default: true + publish-linux-stores: + description: 'Publish Flathub and Snap' + type: boolean + required: true + default: false # schedule: # Every workday at the 2 P.M. (UTC) we run a scheduled nightly build # - cron: '0 14 * * MON-FRI' @@ -50,15 +57,16 @@ env: CLOJURE_VERSION: '1.12.4.1618' NODE_VERSION: '24' JAVA_VERSION: '21' + OCAML_VERSION: '5.1.1' jobs: compile-cljs: runs-on: ubuntu-22.04 steps: - name: Check build options - if: ${{ github.event_name == 'workflow_dispatch' && (github.event.inputs.build-target == 'nightly' || github.event.inputs.build-target == 'beta') && github.event.inputs.git-ref != 'master' }} + if: ${{ github.event_name == 'workflow_dispatch' && (github.event.inputs.build-target == 'nightly' || github.event.inputs.build-target == 'beta' || github.event.inputs.build-target == 'stable') && github.event.inputs.git-ref != 'master' }} run: | - echo "::error title=CheckFail::Nightly and Beta Release MUST be built from master" + echo "::error title=CheckFail::Nightly, Beta and Stable Release MUST be built from master" exit 1 - name: Check out Git repository @@ -108,6 +116,18 @@ jobs: with: cli: ${{ env.CLOJURE_VERSION }} + - name: Set up OCaml + uses: ocaml/setup-ocaml@v3 + with: + ocaml-compiler: ${{ env.OCAML_VERSION }} + + - name: Fetch OCaml deps + working-directory: cli + run: opam install . --deps-only --with-test --yes + + - name: Fetch CLI pnpm deps + run: pnpm --dir cli install --frozen-lockfile --ignore-workspace + - name: Retrieve tag version id: ref run: | @@ -115,7 +135,7 @@ jobs: echo "version=$pkgver" >> $GITHUB_OUTPUT - name: Do Not Overwrite Existing Release - if: ${{ github.event.inputs.build-target == 'beta' }} + if: ${{ github.event.inputs.build-target == 'beta' || github.event.inputs.build-target == 'stable' }} run: | if curl -f "https://api.github.com/repos/${{ github.repository }}/releases/tags/${{ steps.ref.outputs.version }}" &>/dev/null; then echo "::error title=CheckFail::Release already exists" @@ -135,7 +155,14 @@ jobs: echo "ENABLE_FILE_SYNC_PRODUCTION=${{ github.event_name == 'schedule' || github.event.inputs.enable-file-sync-production == 'true' }}" >> $GITHUB_ENV - name: Compile CLJS - run: pnpm install --frozen-lockfile && gulp build && pnpm cljs:release-electron && pnpm db-worker-node:bundle && pnpm webpack-app-build && pnpm desktop:prepare-runtime-js + run: | + pnpm install --frozen-lockfile + gulp build + pnpm cljs:release-electron + pnpm db-worker-node:bundle + opam exec -- pnpm cli:release + pnpm webpack-app-build + pnpm desktop:prepare-runtime-js env: LOGSEQ_SENTRY_DSN: ${{ secrets.LOGSEQ_SENTRY_DSN }} LOGSEQ_POSTHOG_TOKEN: ${{ secrets.LOGSEQ_POSTHOG_TOKEN }} @@ -191,7 +218,10 @@ jobs: uses: actions/upload-artifact@v4 with: name: static - path: static + path: | + static + deps/graph-lifecycle + sidecar include-hidden-files: true build-linux-x64: @@ -202,7 +232,7 @@ jobs: uses: actions/download-artifact@v4 with: name: static - path: static + path: . - name: Retrieve tag version id: ref @@ -231,6 +261,9 @@ jobs: run: pnpm install --frozen-lockfile && pnpm electron:make working-directory: ./static + - name: Verify packaged embedding sidecar + run: test -f static/dist/linux-unpacked/resources/sidecar/embedding_server.py + - name: Save artifacts run: | mkdir -p builds @@ -259,7 +292,7 @@ jobs: uses: actions/download-artifact@v4 with: name: static - path: static + path: . - name: Retrieve tag version id: ref @@ -289,6 +322,9 @@ jobs: run: pnpm electron:make-linux-arm64 working-directory: ./static + - name: Verify packaged embedding sidecar + run: test -f static/dist/linux-arm64-unpacked/resources/sidecar/embedding_server.py + - name: Save artifacts run: | mkdir -p builds @@ -317,7 +353,7 @@ jobs: uses: actions/download-artifact@v4 with: name: static - path: static + path: . - name: Retrieve tag version id: ref @@ -369,6 +405,10 @@ jobs: AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + - name: Verify packaged embedding sidecar + run: | + if (-not (Test-Path "static/dist/win-unpacked/resources/sidecar/embedding_server.py")) { exit 1 } + - name: Save Artifact run: | mkdir builds @@ -391,7 +431,7 @@ jobs: uses: actions/download-artifact@v4 with: name: static - path: static + path: . - name: Retrieve tag version id: ref @@ -443,6 +483,10 @@ jobs: AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + - name: Verify packaged embedding sidecar + run: | + if (-not (Test-Path "static/dist/win-arm64-unpacked/resources/sidecar/embedding_server.py")) { exit 1 } + - name: Save Artifact run: | mkdir builds @@ -465,7 +509,7 @@ jobs: uses: actions/download-artifact@v4 with: name: static - path: static + path: . - name: Retrieve tag version id: ref @@ -525,6 +569,9 @@ jobs: APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_ID_PASSWORD }} APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + - name: Verify packaged embedding sidecar + run: test -f static/dist/mac/Logseq.app/Contents/Resources/sidecar/embedding_server.py + - name: Save x64 artifacts run: | mkdir -p builds @@ -548,7 +595,7 @@ jobs: uses: actions/download-artifact@v4 with: name: static - path: static + path: . - name: Retrieve tag version id: ref @@ -609,6 +656,9 @@ jobs: APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_ID_PASSWORD }} APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + - name: Verify packaged embedding sidecar + run: test -f static/dist/mac-arm64/Logseq.app/Contents/Resources/sidecar/embedding_server.py + - name: Save arm64 artifacts run: | mkdir -p builds @@ -696,7 +746,7 @@ jobs: run: ls -rl - name: Update Nightly Release - uses: andelf/nightly-release@main + uses: andelf/nightly-release@5834076edc55cc05975561c9722043f072ac5c26 # main env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: @@ -718,10 +768,11 @@ jobs: ./*.apk release: - # NOTE: For now, we only have beta channel to be released on GitHub - if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.build-target == 'beta' }} + if: ${{ github.event_name == 'workflow_dispatch' && (github.event.inputs.build-target == 'beta' || github.event.inputs.build-target == 'stable') }} needs: [ build-macos-x64, build-macos-arm64, build-linux-x64, build-linux-arm64, build-windows-x64, build-windows-arm64 ] runs-on: ubuntu-22.04 + outputs: + version: ${{ steps.ref.outputs.version }} steps: - name: Download MacOS x64 Artifacts uses: actions/download-artifact@v4 @@ -789,7 +840,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: ${{ steps.ref.outputs.version }} - name: Desktop APP ${{ steps.ref.outputs.version }} (Beta Testing) + name: ${{ github.event.inputs.build-target == 'beta' && format('Desktop APP {0} (Beta Testing)', steps.ref.outputs.version) || format('Desktop APP {0}', steps.ref.outputs.version) }} body: "TODO: Fill this changelog. Sorry for the inconvenience!" draft: ${{ github.event.inputs.is-draft }} prerelease: ${{ github.event.inputs.is-pre-release }} @@ -803,3 +854,101 @@ jobs: ./*.blockmap ./*.AppImage ./*.apk + + trigger-flathub-release: + runs-on: ubuntu-22.04 + needs: [ release ] + if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.publish-linux-stores == 'true' && (github.event.inputs.build-target == 'beta' || github.event.inputs.build-target == 'stable') }} + steps: + - name: Trigger Flathub release + run: | + if [ -z "${FLATHUB_WORKFLOW_TOKEN:-}" ]; then + echo "::error title=CheckFail::FLATHUB_WORKFLOW_TOKEN is required to trigger Flathub release" + exit 1 + fi + + if [ "${BUILD_TARGET}" = "stable" ]; then + flathub_ref=master + else + flathub_ref=beta + fi + + payload=$(jq -n \ + --arg ref "$flathub_ref" \ + --arg version "$VERSION" \ + '{ref: $ref, inputs: {force: true, version: $version}}') + + response=$(mktemp) + status=$(curl -sS -o "$response" -w "%{http_code}" -X POST \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: Bearer ${FLATHUB_WORKFLOW_TOKEN}" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + https://api.github.com/repos/flathub/com.logseq.Logseq/actions/workflows/update.yml/dispatches \ + -d "$payload") || status=000 + + echo "Flathub dispatch returned HTTP ${status}" + if [ -s "$response" ]; then + cat "$response" + fi + + if [ "$status" != "204" ]; then + echo "::error title=FlathubDispatchFailed::Failed to trigger Flathub release workflow" + exit 1 + fi + env: + BUILD_TARGET: ${{ github.event.inputs.build-target }} + VERSION: ${{ needs.release.outputs.version }} + FLATHUB_WORKFLOW_TOKEN: ${{ secrets.FLATHUB_WORKFLOW_TOKEN }} + + publish-linux-snap: + runs-on: ubuntu-22.04 + needs: [ release ] + if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.publish-linux-stores == 'true' && (github.event.inputs.build-target == 'beta' || github.event.inputs.build-target == 'stable') }} + steps: + - name: Download The Static Asset + uses: actions/download-artifact@v4 + with: + name: static + path: . + + - name: Install Node.js + uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + + - name: Set up pnpm + uses: pnpm/action-setup@v4 + with: + version: 10.33.0 + + - name: Publish Snap + run: | + if [ -z "${SNAPCRAFT_STORE_CREDENTIALS:-}" ]; then + echo "::error title=CheckFail::SNAPCRAFT_STORE_CREDENTIALS is required to publish snap" + exit 1 + fi + + if [ "${BUILD_TARGET}" = "stable" ]; then + snap_grade=stable + snap_channel=stable + else + snap_grade=devel + snap_channel=beta + fi + + printf '%s\n' \ + 'extends: ./electron-builder.yml' \ + 'snap:' \ + " grade: ${snap_grade}" \ + ' publish:' \ + ' provider: snapStore' \ + ' channels:' \ + " - ${snap_channel}" \ + > electron-builder.snap.yml + + pnpm install --frozen-lockfile + pnpm electron:publish-snap -- --config electron-builder.snap.yml + working-directory: ./static + env: + BUILD_TARGET: ${{ github.event.inputs.build-target }} + SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }} diff --git a/.github/workflows/build-ios-release.yml b/.github/workflows/build-ios-release.yml index 7022b78dbbaa..f59f7ea41f52 100644 --- a/.github/workflows/build-ios-release.yml +++ b/.github/workflows/build-ios-release.yml @@ -62,7 +62,10 @@ jobs: cli: ${{ env.CLOJURE_VERSION }} - name: Setup build tools - run: brew install fastlane + run: | + sudo gem install bundler -v 2.7.2 --no-document + bundle _2.7.2_ install + working-directory: ./ios/App - name: Set Build Environment Variables run: | @@ -94,7 +97,12 @@ jobs: run: pnpm test:ios-web-fonts - name: Build and upload iOS app - run: fastlane beta + run: | + : "${LOGSEQ_GITHUB_PAT:?LOGSEQ_GITHUB_PAT is required for the certificates repository}" + MATCH_GIT_BASIC_AUTHORIZATION="$(printf '%s' "x-access-token:${LOGSEQ_GITHUB_PAT}" | base64 | tr -d '\n')" + echo "::add-mask::${MATCH_GIT_BASIC_AUTHORIZATION}" + export MATCH_GIT_BASIC_AUTHORIZATION + bundle exec fastlane beta working-directory: ./ios/App env: APP_STORE_CONNECT_API_KEY_KEY_ID: ${{ secrets.APP_STORE_CONNECT_API_KEY_KEY_ID }} @@ -103,7 +111,8 @@ jobs: APP_STORE_CONNECT_API_KEY_IS_KEY_CONTENT_BASE64: true SLACK_URL: ${{ secrets.SLACK_URL }} MATCH_PASSWORD: ${{ secrets.MATCH_PASSWORD }} - MATCH_GIT_BASIC_AUTHORIZATION: ${{ secrets.MATCH_GIT_BASIC_AUTHORIZATION }} + MATCH_GIT_URL: https://github.com/logseq/certificates.git + LOGSEQ_GITHUB_PAT: ${{ secrets.LOGSEQ_GITHUB_PAT }} XCODE_XCARGS: "-allowProvisioningUpdates" - name: Save Static File diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 90a8e6d412d4..806c8f182ef0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -15,6 +15,7 @@ env: JAVA_VERSION: '21' # This is the latest node version we can run. NODE_VERSION: '24' + OCAML_VERSION: '5.1.1' BABASHKA_VERSION: '1.12.215' jobs: @@ -82,7 +83,7 @@ jobs: run: pnpm install --frozen-lockfile - name: Build test asset - run: clojure -M:test compile test + run: pnpm cljs:test - name: Run ClojureScript query tests against basic query type run: DB_QUERY_TYPE=basic pnpm cljs:run-test -r frontend.db.query-dsl-test @@ -112,7 +113,9 @@ jobs: with: node-version: ${{ env.NODE_VERSION }} cache: 'pnpm' - cache-dependency-path: pnpm-lock.yaml + cache-dependency-path: | + pnpm-lock.yaml + cli/pnpm-lock.yaml - name: Set up Java uses: actions/setup-java@v4 @@ -126,6 +129,11 @@ jobs: cli: ${{ env.CLOJURE_VERSION }} bb: ${{ env.BABASHKA_VERSION }} + - name: Set up OCaml + uses: ocaml/setup-ocaml@v3 + with: + ocaml-compiler: ${{ env.OCAML_VERSION }} + - name: Clojure cache uses: actions/cache@v4 id: clojure-deps @@ -140,11 +148,18 @@ jobs: if: steps.clojure-deps.outputs.cache-hit != 'true' run: clojure -A:cljs -P + - name: Fetch OCaml deps + working-directory: cli + run: opam install . --deps-only --with-test --yes + - name: Fetch pnpm deps run: pnpm install --frozen-lockfile + - name: Fetch CLI pnpm deps + run: pnpm --dir cli install --frozen-lockfile --ignore-workspace + - name: Run CLI E2E tests - run: bb dev:cli-e2e --jobs 1 --verbose + run: opam exec -- bb dev:cli-e2e --jobs 1 --verbose lint: runs-on: ubuntu-22.04 @@ -208,6 +223,8 @@ jobs: node-version: ${{ env.NODE_VERSION }} cache: 'pnpm' cache-dependency-path: | + pnpm-lock.yaml + cli/pnpm-lock.yaml deps/db/pnpm-lock.yaml scripts/pnpm-lock.yaml @@ -223,22 +240,60 @@ jobs: cli: ${{ env.CLOJURE_VERSION }} bb: ${{ env.BABASHKA_VERSION }} + - name: Set up OCaml + uses: ocaml/setup-ocaml@v3 + with: + ocaml-compiler: ${{ env.OCAML_VERSION }} + + - name: Install CLI Linux runtime deps + run: sudo apt-get update && sudo apt-get install -y libsecret-1-0 + + - name: Fetch OCaml deps + working-directory: cli + run: opam install . --deps-only --with-test --yes + - name: Fetch scripts pnpm deps - run: cd scripts && pnpm install --frozen-lockfile + run: pnpm --dir scripts install --frozen-lockfile --ignore-workspace + + - name: Fetch root pnpm deps + run: pnpm install --frozen-lockfile + + - name: Fetch CLI pnpm deps + run: pnpm --dir cli install --frozen-lockfile --ignore-workspace - name: Create DB graph with properties - run: cd scripts && pnpm exec nbb-logseq src/logseq/tasks/db_graph/create_graph_with_properties.cljs ./properties-graph + run: cd scripts && pnpm exec nbb-logseq src/logseq/tasks/db_graph/create_graph_with_properties.cljs ./cli-root/graphs/properties-graph - # TODO: Use a smaller, test-focused graph to test classes - name: Create DB graph with classes - run: cd scripts && pnpm exec nbb-logseq src/logseq/tasks/db_graph/create_graph_with_schema_org.cljs ./schema-graph + run: cd scripts && pnpm exec nbb-logseq src/logseq/tasks/db_graph/create_graph_with_schema_org.cljs ./cli-root/graphs/schema-graph - name: Fetch deps/db pnpm deps - run: cd deps/db && pnpm install --frozen-lockfile + run: pnpm --dir deps/db install --frozen-lockfile --ignore-workspace - # Can run from deps/db since all JS deps for this command are available in deps/db - - name: Validate created DB graphs - run: cd deps/db && pnpm exec nbb-logseq -cp src:../cli/src -m logseq.cli validate -g ../../scripts/properties-graph ../../scripts/schema-graph + - name: Build logseq CLI runtime + run: | + opam exec -- pnpm cli:release + pnpm db-worker-node:release:bundle + pnpm --dir deps/db-sync build:node-adapter + node scripts/prepare-cli-package.mjs + pnpm --dir dist/cli-package install --prod --ignore-workspace + pnpm --dir dist/cli-package pack --pack-destination ../ - - name: Export a created DB graph and confirm the export is idempotent - run: cd deps/db && pnpm exec nbb-logseq -cp src:../cli/src -m logseq.cli export-edn -g ../../scripts/properties-graph -f properties.edn --roundtrip + - name: Smoke test packaged CLI + run: node dist/cli-package/dist/logseq.js --version + + - name: Validate created DB graphs + run: | + node dist/cli-package/dist/logseq.js --root-dir scripts/cli-root --graph properties-graph --timeout-ms 3000 --profile --verbose graph validate + node dist/cli-package/dist/logseq.js --root-dir scripts/cli-root --graph schema-graph --timeout-ms 120000 --profile --verbose graph validate + + - name: Print db-worker-node logs on graph validation failure + if: failure() + run: | + find scripts/cli-root/graphs -maxdepth 2 -name 'db-worker-node-*.log' -print -exec tail -n 200 {} \; || true + pgrep -af db-worker-node || true + + - name: Export a created DB graph + run: node dist/cli-package/dist/logseq.js --root-dir scripts/cli-root --graph properties-graph --timeout-ms 3000 graph export --type edn --file scripts/properties.edn + - name: Import an exported graph to confirm the export is working + run: node dist/cli-package/dist/logseq.js --root-dir scripts/cli-root --graph properties-graph-roundtrip --timeout-ms 20000 graph import --type edn --input scripts/properties.edn diff --git a/.github/workflows/cli-sync-stress.yml b/.github/workflows/cli-sync-stress.yml new file mode 100644 index 000000000000..f1a87fe0e79f --- /dev/null +++ b/.github/workflows/cli-sync-stress.yml @@ -0,0 +1,203 @@ +name: CLI sync stress + +on: + push: + branches: [master] + paths: + - 'scripts/cli-concurrent-edit-stress.mjs' + - 'scripts/cli-concurrent-edit-stress.test.mjs' + - 'scripts/cli-sync-stress-workflow.test.mjs' + - 'cli/**' + - 'cli-e2e/**' + - 'deps/db-sync/**' + - 'deps/graph-lifecycle/**' + - 'src/main/frontend/worker/**' + - 'src/test/frontend/worker/**' + - '.github/workflows/cli-sync-stress.yml' + - '!**/*.md' + pull_request: + branches: [master] + paths: + - 'scripts/cli-concurrent-edit-stress.mjs' + - 'scripts/cli-concurrent-edit-stress.test.mjs' + - 'scripts/cli-sync-stress-workflow.test.mjs' + - 'cli/**' + - 'cli-e2e/**' + - 'deps/db-sync/**' + - 'deps/graph-lifecycle/**' + - 'src/main/frontend/worker/**' + - 'src/test/frontend/worker/**' + - '.github/workflows/cli-sync-stress.yml' + - '!**/*.md' + workflow_dispatch: + +env: + CLOJURE_VERSION: '1.12.4.1618' + JAVA_VERSION: '21' + NODE_VERSION: '24' + OCAML_VERSION: '5.1.1' + BABASHKA_VERSION: '1.12.215' + +jobs: + cli-sync-stress: + name: CLI sync/offline stress + runs-on: ubuntu-22.04 + timeout-minutes: 30 + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up pnpm + uses: pnpm/action-setup@v4 + with: + version: 10.33.0 + + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + cache: 'pnpm' + cache-dependency-path: | + pnpm-lock.yaml + cli/pnpm-lock.yaml + deps/db-sync/pnpm-lock.yaml + + - name: Set up Java + uses: actions/setup-java@v4 + with: + distribution: 'zulu' + java-version: ${{ env.JAVA_VERSION }} + + - name: Set up Clojure + uses: DeLaGuardo/setup-clojure@13.5 + with: + cli: ${{ env.CLOJURE_VERSION }} + bb: ${{ env.BABASHKA_VERSION }} + + - name: Set up OCaml + uses: ocaml/setup-ocaml@v3 + with: + ocaml-compiler: ${{ env.OCAML_VERSION }} + + - name: Install CLI Linux runtime deps + run: sudo apt-get update && sudo apt-get install -y libsecret-1-0 + + - name: Fetch OCaml deps + working-directory: cli + run: opam install . --deps-only --with-test --yes + + - name: Fetch pnpm deps + run: pnpm install --frozen-lockfile + + - name: Fetch CLI pnpm deps + run: pnpm --dir cli install --frozen-lockfile --ignore-workspace + + - name: Fetch db-sync pnpm deps + run: pnpm --dir deps/db-sync install --frozen-lockfile --ignore-workspace + + - name: Build stress runtime + run: | + opam exec -- pnpm cli:release + pnpm db-worker-node:release:bundle + pnpm --dir deps/db-sync build:node-adapter + + - name: Verify stress tests + run: | + node --test scripts/cli-concurrent-edit-stress.test.mjs + node --test scripts/cli-sync-stress-workflow.test.mjs + + - name: Prepare stress auth + run: | + mkdir -p tmp/cli-sync-stress/home/logseq + node <<'NODE' + const crypto = require("node:crypto"); + const fs = require("node:fs"); + + const encode = (payload) => Buffer.from(JSON.stringify(payload)).toString("base64url"); + const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", { modulusLength: 2048 }); + const publicJwk = publicKey.export({ format: "jwk" }); + const exp = Math.floor(Date.now() / 1000) + 3600; + const header = encode({ alg: "RS256", kid: "cli-sync-stress", typ: "JWT" }); + const payload = encode({ + sub: "cli-sync-stress-user", + email: "cli-sync-stress@example.com", + iss: "http://127.0.0.1:19091", + aud: "logseq-cli-sync-stress", + client_id: "logseq-cli-sync-stress", + exp, + }); + const signature = crypto.createSign("RSA-SHA256") + .update(`${header}.${payload}`) + .sign(privateKey) + .toString("base64url"); + const token = `${header}.${payload}.${signature}`; + + fs.writeFileSync( + "tmp/cli-sync-stress/jwks.json", + `${JSON.stringify({ + keys: [{ ...publicJwk, alg: "RS256", use: "sig", kid: "cli-sync-stress" }], + })}\n`, + ); + + fs.writeFileSync( + "tmp/cli-sync-stress/home/logseq/auth.json", + `${JSON.stringify({ + "refresh-token": "cli-sync-stress-refresh-token", + "id-token": token, + "access-token": token, + })}\n`, + ); + NODE + + - name: Run CLI sync stress + env: + LOGSEQ_BIN: ${{ github.workspace }}/tmp/cli-sync-stress/logseq + LOGSEQ_CLI_ROOT_DIR: ${{ github.workspace }}/tmp/cli-sync-stress/root + HOME: ${{ github.workspace }}/tmp/cli-sync-stress/home + run: | + mkdir -p tmp/cli-sync-stress + node <<'NODE' & + const fs = require("node:fs"); + const http = require("node:http"); + const jwks = fs.readFileSync("tmp/cli-sync-stress/jwks.json"); + + http.createServer((req, res) => { + if (req.url === "/.well-known/jwks.json") { + res.writeHead(200, { "content-type": "application/json" }); + res.end(jwks); + return; + } + res.writeHead(404, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: "not found" })); + }).listen(19091, "127.0.0.1"); + NODE + JWKS_PID=$! + trap 'kill "$JWKS_PID" 2>/dev/null || true' EXIT + + printf '#!/usr/bin/env sh\nexec node "%s/static/logseq-cli.js" "$@"\n' "$GITHUB_WORKSPACE" > "$LOGSEQ_BIN" + chmod +x "$LOGSEQ_BIN" + + GRAPH="cli-sync-stress-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + "$LOGSEQ_BIN" graph create --graph "$GRAPH" --output json --timeout-ms 20000 + + node scripts/cli-concurrent-edit-stress.mjs \ + --graph "$GRAPH" \ + --config "$GITHUB_WORKSPACE/tmp/cli-sync-stress/cli.edn" \ + --auth-path "$GITHUB_WORKSPACE/tmp/cli-sync-stress/home/logseq/auth.json" \ + --clients 3 \ + --concurrency 8 \ + --sync \ + --offline \ + --no-e2ee \ + --max-ops 3000 \ + --timeout-ms 60000 + + "$LOGSEQ_BIN" graph validate --graph "$GRAPH" --output json --timeout-ms 60000 + + - name: Print stress logs on failure + if: failure() + run: | + tail -n 200 tmp/cli-concurrent-edit-stress/events.jsonl || true + tail -n 200 tmp/cli-concurrent-edit-stress/db-sync-server.log || true + find tmp -name 'db-worker-node-*.log' -print -exec tail -n 200 {} \; || true diff --git a/.github/workflows/clj-e2e.yml b/.github/workflows/clj-e2e.yml index 406f37e59943..27b8c86d06d0 100644 --- a/.github/workflows/clj-e2e.yml +++ b/.github/workflows/clj-e2e.yml @@ -26,8 +26,8 @@ env: BABASHKA_VERSION: '1.12.215' jobs: - e2e-test-build: - name: Test + build: + name: Build runs-on: ubuntu-22.04 steps: - name: Checkout @@ -65,12 +65,14 @@ jobs: path: | ~/.m2/repository ~/.gitlibs - key: ${{ runner.os }}-clojure-deps-${{ hashFiles('deps.edn') }} + key: ${{ runner.os }}-clojure-deps-e2e-${{ hashFiles('deps.edn', 'clj-e2e/deps.edn') }} restore-keys: ${{ runner.os }}-clojure-deps- - name: Fetch Clojure deps if: steps.clojure-deps.outputs.cache-hit != 'true' - run: clojure -A:cljs -P + run: | + clojure -A:cljs -P + cd clj-e2e && clojure -P -M:test - name: Shadow-cljs cache uses: actions/cache@v4 @@ -90,10 +92,117 @@ jobs: # NOTE: require the app to be build with DEV-RELEASE flag - name: Prepare E2E test build run: | - pnpm gulp:build && clojure -M:cljs release app db-worker --config-merge "{:closure-defines {frontend.config/DEV-RELEASE true}}" --debug && pnpm webpack-app-build + pnpm gulp:build && clojure -M:cljs release app db-worker --config-merge "{:closure-defines {frontend.config/DEV-RELEASE true frontend.worker.handler.transaction/OUTLINER-PERF-LOGGING true}}" --debug && pnpm webpack-app-build + + - name: Upload E2E test build + uses: actions/upload-artifact@v4 + with: + name: static-build + path: static/ + retention-days: 1 + + test: + name: Test ${{ matrix.shard }} + needs: build + runs-on: ubuntu-22.04 + timeout-minutes: 12 + strategy: + fail-fast: false + max-parallel: 5 + matrix: + include: + - shard: editor + namespaces: logseq.e2e.editor-basic-test + - shard: commands + namespaces: >- + logseq.e2e.commands-basic-test + logseq.e2e.query-builder-basic-test + logseq.e2e.multi-tabs-basic-test + logseq.e2e.reference-basic-test + - shard: outliner-rtc + namespaces: >- + logseq.e2e.outliner-basic-test + logseq.e2e.library-basic-test + logseq.e2e.rtc-basic-test + logseq.e2e.assets-basic-test + - shard: graph-properties + namespaces: >- + logseq.e2e.graph-navigation-basic-test + logseq.e2e.block-property-basic-test + logseq.e2e.cmdk-scroll-basic-test + - shard: remaining + namespaces: >- + logseq.e2e.view-basic-test + logseq.e2e.property-basic-test + logseq.e2e.plugins-basic-test + logseq.e2e.property-config-basic-test + logseq.e2e.tag-basic-test + logseq.e2e.right-sidebar-basic-test + logseq.e2e.export-basic-test + logseq.e2e.flashcards-basic-test + logseq.e2e.import-basic-test + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Java + uses: actions/setup-java@v4 + with: + distribution: 'zulu' + java-version: ${{ env.JAVA_VERSION }} + + - name: Set up Clojure + uses: DeLaGuardo/setup-clojure@13.5 + with: + cli: ${{ env.CLOJURE_VERSION }} + bb: ${{ env.BABASHKA_VERSION }} + + - name: Clojure cache + uses: actions/cache@v4 + with: + path: | + ~/.m2/repository + ~/.gitlibs + key: ${{ runner.os }}-clojure-deps-e2e-${{ hashFiles('deps.edn', 'clj-e2e/deps.edn') }} + restore-keys: ${{ runner.os }}-clojure-deps- + + - name: Download E2E test build + uses: actions/download-artifact@v4 + with: + name: static-build + path: static + + - name: Set up Node + if: matrix.shard == 'outliner-rtc' + uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + + - name: Set up pnpm + if: matrix.shard == 'outliner-rtc' + uses: pnpm/action-setup@v4 + with: + version: 10.33.0 + + - name: Install db-sync deps + if: matrix.shard == 'outliner-rtc' + run: pnpm --dir deps/db-sync install --frozen-lockfile --ignore-workspace + + # RTC tests sync against a local db-sync server (the node adapter) + # instead of api.logseq.io. Build it only in the shard that uses it. + - name: Build db-sync node adapter for RTC tests + if: matrix.shard == 'outliner-rtc' + run: pnpm --dir deps/db-sync build:node-adapter - name: Run e2e tests - run: cd clj-e2e && timeout 30m bb dev + env: + E2E_NAMESPACES: ${{ matrix.namespaces }} + run: | + read -r -a namespaces <<< "$E2E_NAMESPACES" + for namespace in "${namespaces[@]}"; do + bb dev -n "$namespace" + done + working-directory: clj-e2e # env: # DEBUG: "pw:api" @@ -101,10 +210,15 @@ jobs: if: ${{ failure() }} uses: actions/upload-artifact@v4 with: - name: e2e-screenshots + name: e2e-screenshots-${{ matrix.shard }} path: clj-e2e/e2e-dump/* retention-days: 1 + success: + name: Mark success + needs: test + runs-on: ubuntu-22.04 + steps: - name: Mark success if: ${{ success() }} run: echo "E2E OK" > e2e-success.txt diff --git a/.github/workflows/clj-rtc-e2e.yml b/.github/workflows/clj-rtc-e2e.yml index 125bc4db4dd6..fad5ea058914 100644 --- a/.github/workflows/clj-rtc-e2e.yml +++ b/.github/workflows/clj-rtc-e2e.yml @@ -100,6 +100,20 @@ jobs: path: static/ retention-days: 1 + # RTC tests sync against a local db-sync server (the node adapter) + # instead of api.logseq.io. + - name: Build db-sync node adapter for RTC tests + run: | + pnpm --dir deps/db-sync install --frozen-lockfile --ignore-workspace + pnpm --dir deps/db-sync build:node-adapter + + - name: Upload db-sync node adapter + uses: actions/upload-artifact@v4 + with: + name: db-sync-node-adapter + path: deps/db-sync/worker/dist/node-adapter.js + retention-days: 1 + test: name: Test ${{ matrix.test-task }} needs: build @@ -150,13 +164,22 @@ jobs: name: static-build path: static + - name: Download db-sync node adapter + uses: actions/download-artifact@v4 + with: + name: db-sync-node-adapter + path: deps/db-sync/worker/dist + + - name: Install db-sync deps + run: pnpm --dir deps/db-sync install --frozen-lockfile --ignore-workspace + - name: Prepare public dir run: | rsync -avz --exclude node_modules --exclude android --exclude ios ./static/ ./public/ ls -lR ./public - name: Run e2e tests - run: cd clj-e2e && timeout 30m bb ${{ matrix.test-task }} + run: cd clj-e2e && timeout 40m bb ${{ matrix.test-task }} - name: Collect screenshots if: ${{ failure() }} diff --git a/.github/workflows/deploy-sync-test.yml b/.github/workflows/deploy-sync-test.yml deleted file mode 100644 index 74516f00e4ef..000000000000 --- a/.github/workflows/deploy-sync-test.yml +++ /dev/null @@ -1,83 +0,0 @@ -name: Deploy new sync test - -on: - workflow_dispatch: - inputs: - branch: - description: "Git branch to build & deploy" - required: true - default: "master" - -env: - CLOJURE_VERSION: "1.12.4.1618" - NODE_VERSION: "24" - JAVA_VERSION: "21" - -jobs: - build-and-deploy: - runs-on: ubuntu-latest - - steps: - - name: Checkout selected branch - uses: actions/checkout@v4 - with: - ref: ${{ inputs.branch }} - fetch-depth: 0 - - - name: Setup Java JDK - uses: actions/setup-java@v4 - with: - distribution: "zulu" - java-version: ${{ env.JAVA_VERSION }} - - - name: Set up Node - uses: actions/setup-node@v4 - with: - node-version: ${{ env.NODE_VERSION }} - - - name: Set up pnpm - uses: pnpm/action-setup@v4 - with: - version: 10.33.0 - - - name: Setup Clojure - uses: DeLaGuardo/setup-clojure@13.5 - with: - cli: ${{ env.CLOJURE_VERSION }} - - - name: Install pnpm deps - run: pnpm install --frozen-lockfile - - - name: Set build environment flags - run: | - echo "ENABLE_FILE_SYNC_PRODUCTION=true" >> $GITHUB_ENV - echo "ENABLE_RTC_SYNC_PRODUCTION=true" >> $GITHUB_ENV - - - name: Build web + workers - run: | - pnpm gulp:build - clojure -M:cljs release app db-worker \ - --config-merge '{:compiler-options {:source-map true :source-map-include-sources-content true :source-map-detail-level :symbols}}' - pnpm webpack-app-build - - rsync -avz \ - --exclude node_modules \ - --exclude android \ - --exclude ios \ - --exclude mobile \ - ./static/ ./public/ - - rm ./public/js/*.map - - env: - LOGSEQ_POSTHOG_TOKEN: ${{ secrets.LOGSEQ_POSTHOG_TOKEN }} - - - name: Publish to Cloudflare Pages - uses: cloudflare/pages-action@1 - with: - apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} - accountId: 2553ea8236c11ea0f88de28fce1cbfee - projectName: "test-sync" - directory: "public" - gitHubToken: ${{ secrets.GITHUB_TOKEN }} - branch: ${{ inputs.branch }} diff --git a/.github/workflows/deploy-db-test-pages.yml b/.github/workflows/deploy-web-app.yml similarity index 90% rename from .github/workflows/deploy-db-test-pages.yml rename to .github/workflows/deploy-web-app.yml index fd9429528eaf..c2ef64ea2183 100644 --- a/.github/workflows/deploy-db-test-pages.yml +++ b/.github/workflows/deploy-web-app.yml @@ -1,8 +1,7 @@ -name: Deploy DB Test Version to Cloud +name: Deploy web app to Cloud on: - push: - branches: ["test/db"] + workflow_dispatch: env: CLOJURE_VERSION: "1.12.4.1618" @@ -12,6 +11,10 @@ env: jobs: build-and-deploy: runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + deployments: write steps: - uses: actions/download-artifact@v4 @@ -28,7 +31,7 @@ jobs: # exit 1 # fi - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Setup Java JDK uses: actions/setup-java@v4 @@ -80,11 +83,9 @@ jobs: destination-dir: ./ - name: Publish to Cloudflare Pages - uses: cloudflare/pages-action@1 + uses: cloudflare/wrangler-action@v4 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} accountId: 2553ea8236c11ea0f88de28fce1cbfee - projectName: "logseq-db-test" - directory: "public" gitHubToken: ${{ secrets.GITHUB_TOKEN }} - branch: "main" + command: pages deploy public --project-name logseq-app --branch main diff --git a/.github/workflows/deploy-web-nightly.yml b/.github/workflows/deploy-web-nightly.yml new file mode 100644 index 000000000000..e17e763374ba --- /dev/null +++ b/.github/workflows/deploy-web-nightly.yml @@ -0,0 +1,85 @@ +name: Deploy Nightly Web App to Cloud + +on: + schedule: + - cron: '0 6 * * *' # Daily at 14:00 Asia/Shanghai (06:00 UTC) + workflow_dispatch: + +concurrency: + group: deploy-web-nightly + cancel-in-progress: false + +env: + CLOJURE_VERSION: "1.12.4.1618" + NODE_VERSION: '24' + JAVA_VERSION: "21" + +jobs: + build-and-deploy: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + deployments: write + + steps: + - uses: actions/checkout@v6 + with: + ref: master + + - name: Setup Java JDK + uses: actions/setup-java@v4 + with: + distribution: "zulu" + java-version: ${{ env.JAVA_VERSION }} + + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + + - name: Set up pnpm + uses: pnpm/action-setup@v4 + with: + version: 10.33.0 + + - name: Setup clojure + uses: DeLaGuardo/setup-clojure@13.5 + with: + cli: ${{ env.CLOJURE_VERSION }} + + - name: Fetch pnpm deps + run: pnpm install --frozen-lockfile + + - name: Set Build Environment Variables + run: | + echo "ENABLE_FILE_SYNC_PRODUCTION=true" >> "$GITHUB_ENV" + echo "ENABLE_RTC_SYNC_PRODUCTION=true" >> "$GITHUB_ENV" + + - name: Build Released-Web + run: | + pnpm gulp:build && clojure -M:cljs release app db-worker --config-merge '{:compiler-options {:source-map true :source-map-include-sources-content true :source-map-detail-level :symbols}}' && pnpm webpack-app-build + rsync -avz --exclude node_modules --exclude android --exclude ios --exclude mobile ./static/ ./public/ + ls -lR ./public && mkdir r2 && mv ./public/js/main.js.map ./r2/nightly.main.js.map + sed -i 's/=main.js.map/=https:\/\/assets.logseq.io\/nightly.main.js.map/g' ./public/js/main.js + env: + LOGSEQ_SENTRY_DSN: ${{ secrets.LOGSEQ_SENTRY_DSN }} + LOGSEQ_POSTHOG_TOKEN: ${{ secrets.LOGSEQ_POSTHOG_TOKEN }} + + - name: Upload to R2 + uses: ryand56/r2-upload-action@latest + with: + r2-account-id: 2553ea8236c11ea0f88de28fce1cbfee + r2-access-key-id: ${{ secrets.R2_ACCESS_KEY_ID }} + r2-secret-access-key: ${{ secrets.R2_SECRET_ACCESS_KEY }} + r2-bucket: ${{ secrets.R2_ASSETS_BUCKET }} + source-dir: r2 + destination-dir: ./ + + - name: Publish to Cloudflare Pages + uses: cloudflare/wrangler-action@v4 + with: + apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} + accountId: 2553ea8236c11ea0f88de28fce1cbfee + gitHubToken: ${{ secrets.GITHUB_TOKEN }} + command: pages deploy public --project-name logseq-nightly --branch main diff --git a/.github/workflows/deploy-web-test-app.yml b/.github/workflows/deploy-web-test-app.yml new file mode 100644 index 000000000000..1a1d2353caee --- /dev/null +++ b/.github/workflows/deploy-web-test-app.yml @@ -0,0 +1,92 @@ +name: Deploy Test Version to Cloud + +on: + push: + branches: ["dev"] + +env: + CLOJURE_VERSION: "1.12.4.1618" + NODE_VERSION: '24' + JAVA_VERSION: "21" + +jobs: + build-and-deploy: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + deployments: write + + steps: + - uses: actions/download-artifact@v4 + with: + name: e2e-success + path: . + continue-on-error: true + + # FIXME: download not found for successful e2e + # - name: Check E2E success + # run: | + # if [ ! -f e2e-success.txt ]; then + # echo "❌ E2E tests did not succeed — aborting release." + # exit 1 + # fi + + - uses: actions/checkout@v6 + + - name: Setup Java JDK + uses: actions/setup-java@v4 + with: + distribution: "zulu" + java-version: ${{ env.JAVA_VERSION }} + + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + + - name: Set up pnpm + uses: pnpm/action-setup@v4 + with: + version: 10.33.0 + + - name: Setup clojure + uses: DeLaGuardo/setup-clojure@13.5 + with: + cli: ${{ env.CLOJURE_VERSION }} + + - name: Fetch pnpm deps + run: pnpm install --frozen-lockfile + + - name: Set Build Environment Variables + run: | + echo "ENABLE_FILE_SYNC_PRODUCTION=true" >> $GITHUB_ENV + echo "ENABLE_RTC_SYNC_PRODUCTION=true" >> $GITHUB_ENV + + - name: Build Released-Web + run: | + pnpm gulp:build && clojure -M:cljs release app db-worker --config-merge '{:compiler-options {:source-map true :source-map-include-sources-content true :source-map-detail-level :symbols}}' && pnpm webpack-app-build + rsync -avz --exclude node_modules --exclude android --exclude ios --exclude mobile ./static/ ./public/ + ls -lR ./public && mkdir r2 && mv ./public/js/main.js.map ./r2/db-test.main.js.map + sed -i 's/=main.js.map/=https:\/\/assets.logseq.io\/db-test.main.js.map/g' ./public/js/main.js + env: + LOGSEQ_SENTRY_DSN: ${{ secrets.LOGSEQ_SENTRY_DSN }} + LOGSEQ_POSTHOG_TOKEN: ${{ secrets.LOGSEQ_POSTHOG_TOKEN }} + + - name: Upload to R2 + uses: ryand56/r2-upload-action@latest + with: + r2-account-id: 2553ea8236c11ea0f88de28fce1cbfee + r2-access-key-id: ${{ secrets.R2_ACCESS_KEY_ID }} + r2-secret-access-key: ${{ secrets.R2_SECRET_ACCESS_KEY }} + r2-bucket: ${{ secrets.R2_ASSETS_BUCKET }} + source-dir: r2 + destination-dir: ./ + + - name: Publish to Cloudflare Pages + uses: cloudflare/wrangler-action@v4 + with: + apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} + accountId: 2553ea8236c11ea0f88de28fce1cbfee + gitHubToken: ${{ secrets.GITHUB_TOKEN }} + command: pages deploy public --project-name logseq-db-test --branch dev diff --git a/.github/workflows/deps-cli.yml b/.github/workflows/deps-cli.yml index 1866076cc0be..6a02756b447e 100644 --- a/.github/workflows/deps-cli.yml +++ b/.github/workflows/deps-cli.yml @@ -1,30 +1,50 @@ name: logseq/cli CI on: - # Path filters ensure jobs only kick off if a change is made to cli or - # its local dependencies + # Path filters ensure jobs only kick off if a change is made to the CLI or + # its local dependencies. push: branches: [master] paths: - - 'deps/cli/**' + - 'cli/**' + - 'src/main/logseq/cli/**' + - 'src/test/logseq/cli/**' + - 'cli-e2e/**' + - 'dist/logseq.js' + - 'scripts/prepare-cli-package.mjs' + - 'scripts/stage-cli-runtime.mjs' + - 'scripts/test-cli-release-config.mjs' - '.github/workflows/deps-cli.yml' - - '!deps/cli/**.md' - # Deps that logseq/cli depends on should trigger this workflow + - '!**/*.md' + # Deps that logseq/cli depends on should trigger this workflow. - 'deps/outliner/**' - 'deps/graph-parser/**' - 'deps/db/**' - 'deps/common/**' + - 'deps/db-sync/**' + - 'src/main/frontend/worker/**' + - 'src/main/logseq/db_worker/**' pull_request: branches: [master] paths: - - 'deps/cli/**' + - 'cli/**' + - 'src/main/logseq/cli/**' + - 'src/test/logseq/cli/**' + - 'cli-e2e/**' + - 'dist/logseq.js' + - 'scripts/prepare-cli-package.mjs' + - 'scripts/stage-cli-runtime.mjs' + - 'scripts/test-cli-release-config.mjs' - '.github/workflows/deps-cli.yml' - - '!deps/cli/**.md' - # Deps that logseq/cli depends on should trigger this workflow + - '!**/*.md' + # Deps that logseq/cli depends on should trigger this workflow. - 'deps/outliner/**' - 'deps/graph-parser/**' - 'deps/db/**' - 'deps/common/**' + - 'deps/db-sync/**' + - 'src/main/frontend/worker/**' + - 'src/main/logseq/db_worker/**' workflow_dispatch: inputs: git-ref: @@ -40,16 +60,11 @@ on: - latest default: "latest" -defaults: - run: - working-directory: deps/cli - env: CLOJURE_VERSION: '1.12.4.1618' - # This is the same as 1.8. JAVA_VERSION: '21' - # This is the latest node version we can run. NODE_VERSION: '24' + OCAML_VERSION: '5.1.1' BABASHKA_VERSION: '1.12.215' jobs: @@ -66,68 +81,60 @@ jobs: version: 10.33.0 - name: Set up Node - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: node-version: ${{ env.NODE_VERSION }} cache: 'pnpm' - cache-dependency-path: deps/cli/pnpm-lock.yaml + cache-dependency-path: | + pnpm-lock.yaml + cli/pnpm-lock.yaml - name: Set up Java - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: 'zulu' java-version: ${{ env.JAVA_VERSION }} - # Clojure needed for bb step - name: Set up Clojure uses: DeLaGuardo/setup-clojure@13.5 with: cli: ${{ env.CLOJURE_VERSION }} bb: ${{ env.BABASHKA_VERSION }} - - name: Fetch pnpm deps - run: pnpm install --frozen-lockfile - - - name: Run nbb-logseq tests - run: pnpm test - - # In this job because it depends on an npm package - - name: Load namespaces into nbb-logseq - run: bb test:load-all-namespaces-with-nbb . + - name: Set up OCaml + uses: ocaml/setup-ocaml@v3 + with: + ocaml-compiler: ${{ env.OCAML_VERSION }} - lint: - runs-on: ubuntu-latest + - name: Fetch OCaml deps + working-directory: cli + run: opam install . --deps-only --with-test --yes - steps: - - name: Checkout - uses: actions/checkout@v4 + - name: Fetch pnpm deps + run: pnpm install --frozen-lockfile - - name: Set up Java - uses: actions/setup-java@v3 - with: - distribution: 'zulu' - java-version: ${{ env.JAVA_VERSION }} + - name: Fetch CLI pnpm deps + run: pnpm --dir cli install --frozen-lockfile --ignore-workspace - - name: Set up Clojure - uses: DeLaGuardo/setup-clojure@13.5 - with: - cli: ${{ env.CLOJURE_VERSION }} - bb: ${{ env.BABASHKA_VERSION }} + - name: Run logseq CLI tests + run: opam exec -- pnpm --dir cli test - - name: Run clj-kondo lint - run: clojure -M:clj-kondo --lint src test + - name: Compile query integration worker + run: pnpm db-worker-node:compile - - name: Carve lint for unused vars - run: bb lint:carve + - name: Run shared query integration tests + run: pnpm --dir cli test:query-integration - - name: Lint for vars that are too large - run: bb lint:large-vars + - name: Build logseq CLI + run: | + opam exec -- pnpm cli:release + pnpm db-worker-node:release:bundle - - name: Lint for namespaces that aren't documented - run: bb lint:ns-docstrings + - name: Verify CLI publish config + run: node scripts/test-cli-release-config.mjs - - name: Lint for public vars that are private based on usage - run: bb lint:minimize-public-vars + - name: Smoke test CLI + run: node dist/logseq.js --help release: if: ${{ github.event_name == 'workflow_dispatch' }} @@ -144,38 +151,58 @@ jobs: version: 10.33.0 - name: Set up Node - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 with: node-version: ${{ env.NODE_VERSION }} cache: 'pnpm' - cache-dependency-path: deps/cli/pnpm-lock.yaml + cache-dependency-path: | + pnpm-lock.yaml + cli/pnpm-lock.yaml - name: Set up Java - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: 'zulu' java-version: ${{ env.JAVA_VERSION }} - # Clojure needed for bb step - name: Set up Clojure uses: DeLaGuardo/setup-clojure@13.5 with: cli: ${{ env.CLOJURE_VERSION }} bb: ${{ env.BABASHKA_VERSION }} + - name: Set up OCaml + uses: ocaml/setup-ocaml@v3 + with: + ocaml-compiler: ${{ env.OCAML_VERSION }} + + - name: Fetch OCaml deps + working-directory: cli + run: opam install . --deps-only --with-test --yes + - name: Fetch pnpm deps run: pnpm install --frozen-lockfile - - name: Bundle vendor deps - run: bb build:vendor-nbb-deps + - name: Fetch CLI pnpm deps + run: pnpm --dir cli install --frozen-lockfile --ignore-workspace + + - name: Build logseq CLI + run: | + opam exec -- pnpm cli:release + pnpm db-worker-node:release:bundle + + - name: Prepare npm package + run: node scripts/prepare-cli-package.mjs - # - name: Debug package - # run: pnpm pack && tar -tf logseq-cli-*.tgz + - name: Smoke test npm package + run: node dist/cli-package/dist/logseq.js --help - name: Authenticate with registry + working-directory: dist/cli-package env: NPM_TOKEN: ${{ secrets.NPM_CLI_TOKEN }} run: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > .npmrc - name: Publish package + working-directory: dist/cli-package run: npm publish --tag "${{ github.event.inputs.release-tag || 'alpha' }}" --access public diff --git a/.github/workflows/deps-common.yml b/.github/workflows/deps-common.yml index 20da60c09f02..781caee5695d 100644 --- a/.github/workflows/deps-common.yml +++ b/.github/workflows/deps-common.yml @@ -59,7 +59,7 @@ jobs: bb: ${{ env.BABASHKA_VERSION }} - name: Fetch pnpm deps - run: pnpm install --frozen-lockfile + run: pnpm install --ignore-workspace --frozen-lockfile - name: Run nbb-logseq tests run: pnpm test diff --git a/.github/workflows/deps-db-sync.yml b/.github/workflows/deps-db-sync.yml index 622ce9007ba7..1b25b6c9f29b 100644 --- a/.github/workflows/deps-db-sync.yml +++ b/.github/workflows/deps-db-sync.yml @@ -67,11 +67,17 @@ jobs: bb: ${{ env.BABASHKA_VERSION }} - name: Fetch pnpm deps - run: pnpm install --frozen-lockfile + run: pnpm install --ignore-workspace --frozen-lockfile - name: Run unit tests run: pnpm test:node-adapter + - name: Run MCP helper tests + run: pnpm test:chatgpt-app + + - name: Test MCP in the Workers runtime + run: pnpm test:mcp + lint: runs-on: ubuntu-latest diff --git a/.github/workflows/deps-db.yml b/.github/workflows/deps-db.yml index 3ab8d91ecd20..bb39bc05925e 100644 --- a/.github/workflows/deps-db.yml +++ b/.github/workflows/deps-db.yml @@ -63,7 +63,7 @@ jobs: bb: ${{ env.BABASHKA_VERSION }} - name: Fetch pnpm deps - run: pnpm install --frozen-lockfile + run: pnpm install --frozen-lockfile --ignore-workspace - name: Run nbb-logseq tests run: pnpm test diff --git a/.github/workflows/deps-graph-parser.yml b/.github/workflows/deps-graph-parser.yml index ad8fb53636f0..ffcd4b3b1426 100644 --- a/.github/workflows/deps-graph-parser.yml +++ b/.github/workflows/deps-graph-parser.yml @@ -81,7 +81,7 @@ jobs: run: clojure -A:test -P - name: Fetch pnpm deps - run: pnpm install --frozen-lockfile + run: pnpm install --frozen-lockfile --ignore-workspace - name: Run nbb-logseq tests run: pnpm test diff --git a/.github/workflows/deps-outliner.yml b/.github/workflows/deps-outliner.yml index 83337cb24f28..41ac4c94c77f 100644 --- a/.github/workflows/deps-outliner.yml +++ b/.github/workflows/deps-outliner.yml @@ -70,7 +70,7 @@ jobs: bb: ${{ env.BABASHKA_VERSION }} - name: Fetch pnpm deps - run: pnpm install --frozen-lockfile + run: pnpm install --frozen-lockfile --ignore-workspace - name: Run nbb-logseq tests run: pnpm test diff --git a/.github/workflows/deps-publishing.yml b/.github/workflows/deps-publishing.yml index c30c56ad6b54..40db280696c4 100644 --- a/.github/workflows/deps-publishing.yml +++ b/.github/workflows/deps-publishing.yml @@ -68,7 +68,7 @@ jobs: bb: ${{ env.BABASHKA_VERSION }} - name: Fetch pnpm deps - run: pnpm install --frozen-lockfile + run: pnpm install --frozen-lockfile --ignore-workspace - name: Run nbb-logseq tests run: pnpm test diff --git a/.github/workflows/hypha-build.yml b/.github/workflows/hypha-build.yml index bc77f62eb6b5..bfc58febe146 100644 --- a/.github/workflows/hypha-build.yml +++ b/.github/workflows/hypha-build.yml @@ -25,6 +25,65 @@ env: PNPM_VERSION: '10.33.0' jobs: + # Lint, ClojureScript unit tests, deps/db-sync tests and the patch-anchor + # checks. CI's own build.yml runs the first two only on master, so on + # develop (and in the upstream-sync PRs from hypha-staging) nothing else + # runs them. + hypha-tests: + runs-on: ubuntu-22.04 + timeout-minutes: 45 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up pnpm + uses: pnpm/action-setup@v4 + with: + version: ${{ env.PNPM_VERSION }} + + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: ${{ env.NODE_VERSION }} + cache: pnpm + + - name: Set up Java + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: ${{ env.JAVA_VERSION }} + + - name: Set up Clojure + uses: DeLaGuardo/setup-clojure@13.2 + with: + cli: ${{ env.CLOJURE_VERSION }} + bb: ${{ env.BABASHKA_VERSION }} + + - name: Install ripgrep (patch-anchor checks) + run: sudo apt-get update && sudo apt-get install -y ripgrep + + - name: Patch-anchor checks + run: bash .github/scripts/hypha-patch-anchors.sh + + - name: Fetch pnpm deps + run: pnpm install --frozen-lockfile + + - name: Lint (kondo, carve, large-vars, worker/frontend separation, i18n, docstrings) + run: bb lint:dev + + - name: Build test asset + # db-worker-node too: the electron db-worker-manager tests start a + # real worker (same as upstream's build.yml). + run: pnpm cljs:test + + - name: ClojureScript unit tests + run: pnpm cljs:run-test + + - name: deps/db-sync tests + run: | + pnpm --dir deps/db-sync install --frozen-lockfile --ignore-workspace + pnpm --dir deps/db-sync test + hypha-build: runs-on: ubuntu-22.04 timeout-minutes: 30 diff --git a/.github/workflows/pr-labeler.yml b/.github/workflows/pr-labeler.yml index 2d6add54c300..6f10fad1f414 100644 --- a/.github/workflows/pr-labeler.yml +++ b/.github/workflows/pr-labeler.yml @@ -6,10 +6,13 @@ on: jobs: pr-labeler: runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write steps: - - uses: TimonVS/pr-labeler-action@v3.1.0 + # actions/labeler reads the configuration from this repository (the base) and matches the head branch's name, so it + # also labels pull requests from forks; TimonVS/pr-labeler-action read it at the head branch's name in this + # repository, which a fork's branch does not have ("No commit found for the ref"). + - uses: actions/labeler@v6 with: - # optional, .github/pr-labeler.yml is the default value configuration-path: .github/pr-labeler.yml - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/upstream-sync.yml b/.github/workflows/upstream-sync.yml index 89408fc76fd4..37f35fa63a5f 100644 --- a/.github/workflows/upstream-sync.yml +++ b/.github/workflows/upstream-sync.yml @@ -81,6 +81,7 @@ jobs: if: steps.merge.outputs.result == 'clean' id: anchors run: | + command -v rg >/dev/null || (sudo apt-get update && sudo apt-get install -y ripgrep) bash .github/scripts/hypha-patch-anchors.sh > anchor-report.txt if grep -q "FAIL" anchor-report.txt; then echo "result=fail" >> $GITHUB_OUTPUT diff --git a/.gitignore b/.gitignore index 471d4917a48d..243d3cfc4177 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -/target +target/ /classes /checkouts profiles.clj @@ -12,7 +12,7 @@ pom.xml.asc .hg/ .nbb/ -node_modules/ +node_modules static/** tmp cljs-test-runner-out @@ -28,6 +28,14 @@ cljs-test-runner-out .lein-* .nrepl-* .DS_Store +__pycache__/ +*.pyc +*.pyo +nul +.Rhistory +.RData +.Rproj.user/ +.ipynb_checkpoints/ report.html strings.csv ssl/ @@ -52,6 +60,7 @@ docker android/app/src/main/assets/capacitor.plugin.json ios/App/App/capacitor.config.json ios/App/App/public +ios/App/.bundle/ startup.png @@ -85,6 +94,7 @@ deps/db-sync/data *.map /dist/db-worker-node.js /dist/build/ +/dist/cli-package/ /dist/db-worker-node-assets.json /dist/*.wasm /dist/cljs-runtime/ @@ -105,3 +115,9 @@ clj-e2e/.clj-kondo/imports /hypha-server/test-results/ /hypha-server/playwright-report/ /hypha-server/test/playwright/.state/ +# Assembled clipper add-ons (build.mjs output) +/hypha-clipper/dist/ +_build/ +/cli/_opam +/cli/compile_commands.json +/cli/.eglot-root diff --git a/.i18n-lint.toml b/.i18n-lint.toml index d82123c3f265..ded9fb01cbbf 100644 --- a/.i18n-lint.toml +++ b/.i18n-lint.toml @@ -336,6 +336,9 @@ always_used_key_patterns = [ # Table view keys used dynamically via (for [[option-key _] options] (t option-key)). "^:view\\.table/group-journal-date", "^:view\\.table/group-page", + # Default view title keys resolved dynamically via default-view-title-key-by-feature-type. + "^:view/linked-references", + "^:view/unlinked-references", ] # Key namespace prefixes excluded from unused-key checking. diff --git a/.spec-dev-tool/guides/find-simplifications.md b/.spec-dev-tool/guides/find-simplifications.md new file mode 100644 index 000000000000..fcd48503edd2 --- /dev/null +++ b/.spec-dev-tool/guides/find-simplifications.md @@ -0,0 +1,71 @@ +# Repository-Specific Simplification Rules + +## Production corpus + +- Treat `src/main`, `src/electron`, `deps/*/src`, `deps/*/worker`, + `static`, `resources`, runtime scripts, migrations, and package/build + metadata as production unless a narrower owner document proves otherwise. +- Treat command-line entry points, worker resource renderers, IPC/event + handlers, Datascript schemas, built-in properties/classes, migrations, and + import/export formats as supported contracts. + +## Non-production and ambiguous corpus + +- Treat `src/test`, `deps/*/test`, `clj-e2e`, `cli-e2e`, fixtures, benchmark + helpers, examples, and docs as non-production evidence, not as automatic + deletion targets. +- Treat scripts, generated test artifacts, and development-only helpers as + ambiguous until their call sites and package metadata prove whether they are + shipped, CI-only, or local-only. + +## Excluded edit targets + +- Do not edit generated, vendored, lockfile, build-output, or distribution + artifacts as simplification targets unless the generator or packaging rule is + the actual surface being simplified. +- Do not remove migrations, schema history, translation keys, public command + options, import/export compatibility, or persisted data handling without a + separate behavior-changing decision. + +## Protected surfaces + +- Preserve persisted DB shape, Datascript schema semantics, sync/RTC + protocols, render-resource envelopes, resource watch keys, import/export + output, CLI output/options, Electron IPC contracts, and i18n key semantics. +- Preserve fail-fast behavior and one clear code path; do not replace explicit + validation with silent defaults or compatibility fallbacks. + +## Candidate priorities + +- Prefer simplifications that remove mirrored state, duplicate resource keys, + unused compatibility layers, speculative abstractions, single-use wrappers, + or stale feature residue. +- Prefer local deletion and clearer ownership over broad rewrites. A candidate + should reduce concepts or obligations, not just move complexity. + +## Dependency policy + +- Reuse existing repository libraries and helpers before introducing a new + dependency. +- Replacing hand-rolled code with a dependency is a simplification only when + the dependency is already allowed, maintained, and reduces total code and + contracts. + +## Required evidence + +- Search for Clojure/CLJS symbols, keyword values, resource keys, command names, + event names, config keys, generated references, and dynamic registrations + before calling a surface unused. +- Read both caller and callee paths. Distinguish production use from test-only + coverage and documentation mentions. +- For public or persisted contracts, identify the compatibility promise that is + preserved or explain why no supported external consumer exists. + +## Validation + +- Run the narrowest relevant unit tests first, then broader namespaces when + helper behavior is shared. +- Use `bb dev:test -v ` for frontend/unit targets and + `pnpm --dir deps/db test-v ` for `deps/db` targets. +- Run `spec-dev-tool check --all` before completing work that creates or + updates agent decision documents. diff --git a/AGENTS.md b/AGENTS.md index ae5c393a9f77..6370e6ac11d3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,13 +1,15 @@ # Repository Guidelines -Logseq is a ClojureScript codebase compiled by `shadow-cljs` into multiple targets defined in `shadow-cljs.edn`: browser apps (`:app`, `:mobile`, `:publishing`), web worker (`:db-worker`), and node scripts (`:db-worker-node`, `:logseq-cli`, `:electron`, `:test`, `:test-no-worker`). `CODEBASE_OVERVIEW.md` and `docs/dev-practices.md` are the canonical orientation docs. +Logseq is a ClojureScript codebase compiled by `shadow-cljs` into multiple targets defined in `shadow-cljs.edn`: browser apps (`:app`, `:mobile`, `:publishing`), web worker (`:db-worker`), and node scripts (`:db-worker-node`, `:electron`, `:test`, `:test-no-worker`). `CODEBASE_OVERVIEW.md` and `docs/dev-practices.md` are the canonical orientation docs. ## Codebase Layout (non-obvious) - `deps/` holds independent Clojure local-root libraries (`common`, `db`, `db-sync`, `graph-parser`, `outliner`, `publishing`, `publish`, `cli`, `shui`). Each has its own `deps.edn`, `.clj-kondo/`, and sometimes `package.json` / `bb.edn`. Edit the dep that owns the namespace and run that dep's tooling — not the root one. - `src/main/frontend/worker/**` and `src/main/frontend/worker_common/**` must NOT require frontend namespaces (except `frontend.worker.*` / `frontend.common.*`); the reverse is also forbidden (one tiny allowlist for `frontend.worker.file.reset`). `bb lint:worker-and-frontend-separate` enforces both directions — a stray `:require` that pulls React into the worker breaks it hard. Shared code goes through `deps/` or `frontend.common.*`. -- Subdirectories with their own `AGENTS.md` (read recursively before editing): `src/main/logseq/cli/`, `clj-e2e/`, `cli-e2e/`, `libs/guides/`. +- Subdirectories with their own `AGENTS.md` (read recursively before editing): `cli/` (OCaml CLI), `src/main/logseq/cli/`, `clj-e2e/`, `cli-e2e/`, `libs/guides/`. ## Build, Test, and Development Commands +- **Run build/test/lint inside the dev container** (canonical path; the host needs only Docker + Compose). `bin/dev ` forwards into the `Dockerfile.dev` image whose toolchain is pinned to CI (Node 24, Java 21, Clojure CLI, Babashka, pnpm). Examples: `bin/dev bb dev:lint-and-test`, `bin/dev bb dev:test -r `, `bin/dev bin/hypha-build`. The first run builds the image (~5 min) and installs deps; later runs are instant. See `Dockerfile.dev` and `docker-compose.dev.yml`. + - Why this matters for tests: the `:test` / `:test-no-worker` builds import `node:sqlite`, a Node 22.5+ built-in. On a host with older Node (e.g. 20.x), `pnpm cljs:run-test` / `node static/tests.js` fail at module load with `No such built-in module: node:sqlite` **before any test runs** — an environment issue, not a code failure. Run tests in the container (Node 24), not on an older-Node host. - `bb dev:lint-and-test` runs linters and unit tests; use it before submitting changes. - `bb dev:test -v ` runs a single unit test (example: `bb dev:test -v logseq.some-test/foo`). Each invocation recompiles `static/tests.js` first; for tight loops run `clojure -M:test watch test` once and then `node static/tests.js -v ` (or `-r `, `-i focus`, etc. — see `docs/dev-practices.md`). - App E2E tests live in `clj-e2e/`; run from that directory with `bb test` (or `bb -f clj-e2e/bb.edn test` from repo root). @@ -33,8 +35,9 @@ Logseq is a ClojureScript codebase compiled by `shadow-cljs` into multiple targe - Reuse `src/resources/dicts/en.edn` keys only on exact semantic owner + textual role match. Follow `docs/i18n-key-naming.md` for new or renamed keys. Add English source text in `en.edn`; add non-English entries only when providing real translations; keep complete sentences whole; use placeholders for plain dynamic text; run `bb lang:validate-translations`, `bb lang:lint-hardcoded`, and `bb lang:format-dicts` as needed. ## Testing Guidelines -- Unit tests live in `src/test/` and are runnable via `bb dev:lint-and-test`. +- Unit tests live in `src/test/` and are runnable via `bb dev:lint-and-test` (run it inside the dev container — see Build/Test commands; the test build needs Node 22.5+ for `node:sqlite`). - A namespace's tests live in the sibling namespace with a `-test` suffix (`frontend.db.model` → `frontend.db.model-test`). +- For CLJS tests, avoid recompiling when source files have not changed since the last successful `cljs:test`; run against the existing compiled test artifact instead. - See `docs/dev-practices.md` for repl-driven, autorun, database, performance, and async test helpers. ## *IMPORTANT*: Always respect directory-specific AGENTS.md based on file path @@ -43,14 +46,18 @@ Logseq is a ClojureScript codebase compiled by `shadow-cljs` into multiple targe ## Commit & Pull Request Guidelines - Commit subjects are short and imperative, often with a scoped prefix matching existing history: `fix:`, `feat:` / `feature:`, `enhance:` / `enhance(rtc):`, `chore:`, `dev:`, `test:`. - PRs should describe the behavior change, link relevant issues, and note any test coverage added or skipped. +- Never include the word "Codex" or any agent name in commit subjects, commit bodies, trailers, branch names, PR titles, or PR descriptions. +- PR titles must describe the code change only. +- Before creating or updating commits or PRs, verify that the generated metadata does not contain "Codex" or any agent name in any casing. ## Agent-Specific Notes - Repo-local skills live under `.agents/skills/`; load the matching `SKILL.md` before editing files or proposing changes. - **i18n (mandatory)**: Always load `.agents/skills/logseq-i18n/SKILL.md` before any change that adds, edits, or removes user-facing UI text, regardless of whether other skills also apply. - Review notes in `prompts/review.md` codify recurring Clojure(Script) mistakes (`empty?` vs `empty`, `conn` vs `db`, `memoize` leaks, log helpers, `:block/title` vs deprecated `:block/content`, etc.); check them when preparing changes. -- DB-sync feature guide for AI agents: `docs/agent-guide/db-sync/db-sync-guide.md`. -- DB-sync protocol reference: `docs/agent-guide/db-sync/protocol.md`. +- Runtime, sync, CLI, rendering, search, and Graph View engineering guidance is consolidated in `docs/agent-guide/implemented/architecture/2026-08-24-logseq-runtime-and-engineering-guide.md`; current source and tests remain authoritative. - For db-sync D1 schema changes, add or update a Cloudflare worker SQL migration under `deps/db-sync/worker/migrations/`; do not rely on ad hoc runtime-only schema migration code. - New properties go in `logseq.db.frontend.property/built-in-properties` AND require a paired entry in `frontend.worker.db.migrate/schema-version->updates` (e.g. `["65.10" {:properties [:block/journal-day]}]`). Skipping the migration silently breaks existing graphs. - Avoid creating new classes or properties unless required. - When deleting properties in a db migration, add those properties to `logseq.db-sync.tx-sanitize/migration-deleted-attrs` so server-side tx sanitization drops them from incoming syncs. +- Use spec-dev-tool to manage agent decision documents; run `spec-dev-tool --help` and follow its AGENT WORKFLOW. +- When asked to find simplifications, run `spec-dev-tool guide find-simplifications` from inside this Git worktree and follow the emitted workflow. diff --git a/CODEBASE_OVERVIEW.md b/CODEBASE_OVERVIEW.md index c0b65a5b10b8..639a28103cad 100644 --- a/CODEBASE_OVERVIEW.md +++ b/CODEBASE_OVERVIEW.md @@ -58,8 +58,6 @@ This is overview of this repository's most important directories and files. - `deps/` contains ClojureScript dependencies or libraries used by the frontend. - `deps/graph-parser/` is a library that parses a Logseq graph and saves it to a database. -- `packages/` contains JavaScript dependencies used by the frontend - - `packages/ui/` - The frontend's component system based on shadcn - `scripts` - Dev scripts - `clj-e2e/` - end to end clj frontend tests - `android/` - Android app @@ -101,6 +99,7 @@ Everything above describes upstream Logseq and is preserved verbatim for clean u - `init.cljs` — bootstraps the Hypha layer at app start. - `plugin_init.cljs` — runtime monkey-patch that rewrites plugin asset URLs through the Hypha CORP proxy (no upstream `LSPlugin.core` patch). - `asset_cache.cljs` — background LRU eviction of cached asset binaries via `navigator.storage.estimate` + IndexedDB cleanup. + - `capture.cljs` — quick capture from the PWA share target / bookmarklet: parses the `hypha-*` URL params and dispatches upstream's `:editor/quick-capture`. - `hypha-server/` — the TypeScript reverse-proxy that fronts the upstream `db-sync` node-adapter on port 3030: access-code auth + JWT/JWKS, plugin-marketplace caching, plugin-asset CORP injection, and pass-through of `/sync/`, `/graphs/`, `/assets/`, `/e2ee/` routes. Tests live in `hypha-server/test/`. - `docs/hypha/` — operator and architecture docs (self-hosting, operations, phase plans). - `bin/hypha-*` — build entry points (`bin/hypha-build`, `--release` for production). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9a3d96e35bb1..27e240a76c6c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -53,7 +53,7 @@ For ways to help with coding, read the next section. ### Code Contributions For contributors who want to help with coding, we have a list of [good first -issues](https://github.com/logseq/logseq/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) +issues](https://github.com/logseq/db-test/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) to help you get started. These are issues that are beginner-friendly and do not require advanced knowledge of the codebase. We encourage new contributors to start with these issues and gradually work their way up to more challenging @@ -190,5 +190,5 @@ Your contributions to open source, large or small, make great projects like this [feature-request]: https://discuss.logseq.com/c/feedback/feature-requests/ "Submit Feature Request" [forum]: https://discuss.logseq.com "Logseq Forum" [search-pr]: https://github.com/logseq/logseq/pulls "Search open PRs" -[new-issue]: https://github.com/logseq/logseq/issues/new?assignees=&labels=&template=bug_report.yaml "Submit a New issue" -[issue-tracker]: https://github.com/logseq/logseq/issues "Logseq Issue Tracker" +[new-issue]: https://github.com/logseq/db-test/issues/new?assignees=&labels=&template=bug_report.yaml "Submit a New issue" +[issue-tracker]: https://github.com/logseq/db-test/issues "Logseq Issue Tracker" diff --git a/Dockerfile.dev b/Dockerfile.dev index ed55991483c1..3b1e488afa89 100644 --- a/Dockerfile.dev +++ b/Dockerfile.dev @@ -14,6 +14,7 @@ # - Clojure CLI 1.12.4.1618 (CI CLOJURE_VERSION) # - Babashka 1.12.215 (CI BABASHKA_VERSION) # - pnpm 10.33.0 (root package.json packageManager) +# - OCaml 5.1.1 (CI OCAML_VERSION, builds the cli/ CLI) # # This is the DEV image. Production images live in Dockerfile.hypha (M3, # different concern). They are intentionally separate so dev tooling does @@ -33,6 +34,7 @@ ARG NODE_MAJOR=24 ARG CLOJURE_VERSION=1.12.4.1618 ARG BABASHKA_VERSION=1.12.215 ARG PNPM_VERSION=10.33.0 +ARG OCAML_VERSION=5.1.1 ARG USER_UID=1000 ARG USER_GID=1000 @@ -60,6 +62,8 @@ RUN apt-get update \ build-essential rlwrap procps \ python3 \ libsecret-1-dev \ + # opam + OCaml compiler build deps for the cli/ (OCaml/Melange) CLI. + opam m4 unzip rsync patch pkg-config \ # Playwright headless-chromium runtime deps (M4 headless-auth smoke). # Mirrors `npx playwright install-deps chromium` on Ubuntu 22.04 so # operators can run the spec without sudo inside the container. @@ -116,13 +120,26 @@ RUN if ! getent group ${USER_GID} >/dev/null 2>&1; then groupadd --gid ${USER_GI WORKDIR /workspace USER dev -ENV HOME=/home/dev +ENV HOME=/home/dev \ + OPAMROOT=/home/dev/.opam \ + OPAMYES=1 + +# --- OCaml switch for cli/ ------------------------------------------------- +# +# The compiler lives in the image; the CLI's opam packages are installed into +# the hypha-opam volume on first use (Docker seeds the empty volume from this +# directory), via `bin/dev bash -c 'cd cli && opam install . --deps-only --with-test'`. +# No sandboxing: bubblewrap needs privileges the dev container does not have. +RUN opam init --bare --disable-sandboxing --no-setup \ + && opam switch create default ${OCAML_VERSION} \ + && opam clean --all-switches --download-cache --logs # Smoke labels for sanity-checking the built image LABEL org.hypha.toolchain.node="${NODE_MAJOR}.x" \ org.hypha.toolchain.clojure="${CLOJURE_VERSION}" \ org.hypha.toolchain.babashka="${BABASHKA_VERSION}" \ - org.hypha.toolchain.pnpm="${PNPM_VERSION}" + org.hypha.toolchain.pnpm="${PNPM_VERSION}" \ + org.hypha.toolchain.ocaml="${OCAML_VERSION}" # Default: interactive shell. Compose / bin/dev overrides this per call. CMD ["bash"] diff --git a/Dockerfile.hypha b/Dockerfile.hypha index 90f989e8a28e..1bde930bf60e 100644 --- a/Dockerfile.hypha +++ b/Dockerfile.hypha @@ -87,7 +87,7 @@ RUN bin/hypha-build --release # Prune dev-only packages from hypha-server before copying to runtime stage. # (better-sqlite3 in deps/db-sync has no devDependencies to prune.) -RUN pnpm --dir hypha-server prune --prod +RUN pnpm --dir hypha-server prune --prod --ignore-workspace # ──────────────────────────────────────────────────────────────────────────── # Stage 2: runtime diff --git a/HYPHA.md b/HYPHA.md index ef2fe88e4118..b2dc3edd25c4 100644 --- a/HYPHA.md +++ b/HYPHA.md @@ -18,6 +18,7 @@ the same app on their own server. | **Cross-device personal cloud** | Same access code from a different browser → same graphs, sync via the upstream RTC layer | | **Plugin marketplace** | Phase 1.5 caching reverse-proxy for the Logseq marketplace + R2 plugin assets, with CORP-header injection so iframes pass Hypha's required COEP gate | | **Asset cache eviction** | Phase 1.6.1 background LRU eviction of cached asset binaries (`navigator.storage.estimate` + IDB cleanup) | +| **Installable PWA + quick capture** | Web manifest so the instance installs as a real app, plus an Android share target and a desktop bookmarklet that drop links into today's journal ([quick-capture.md](docs/hypha/quick-capture.md)) | | **Upload-failure visibility** | Cloud-upload errors surface as user notifications instead of silent spinners | | **0 backend services** | No Postgres, no Redis, no managed Cloudflare deployment — just node + sqlite in one container | diff --git a/HYPHA_PATCHES.md b/HYPHA_PATCHES.md index 68484ced3d9e..01dbc61999c3 100644 --- a/HYPHA_PATCHES.md +++ b/HYPHA_PATCHES.md @@ -21,13 +21,13 @@ during weekly upstream-sync, the detection grep is the first thing run; the - **Patch form**: ```clojure ;; ORIGINAL (~line 349) - (defmethod events/handle :user/login [[_]] + (defevent! :user/login [[_]] (if (mobile-util/native-platform?) (route-handler/redirect! {:to :user-login}) (login/open-login-modal!))) ;; HYPHA - (defmethod events/handle :user/login [[_]] + (defevent! :user/login [[_]] (cond hypha-config/hypha-mode? (hypha-login/open-login-modal!) @@ -42,6 +42,8 @@ during weekly upstream-sync, the detection grep is the first thing run; the `[frontend.hypha.config :as hypha-config]`, `[frontend.hypha.login :as hypha-login]`. - **Line count**: +4 (one cond clause + if→cond restructuring) +2 requires +- **Upstream sync 2026-11**: upstream replaced the `events/handle` + multimethod with `defevent!` registrations; the patch moved along unchanged. - **Rationale**: In Hypha mode the access-code login modal must replace Cognito's Amplify-driven modal. All call sites that publish `:user/login` (`components/settings.cljs`, `components/header.cljs`, etc.) stay @@ -53,7 +55,7 @@ during weekly upstream-sync, the detection grep is the first thing run; the - Wrapping `:user/login` via an event hijack: rejected (more invasive, higher surface for upstream divergence). - **Break signal — structural**: - - `defmethod events/handle :user/login` is renamed, deleted, or moved + - `defevent! :user/login` is renamed, deleted, or moved to another file or split across files. - **Break signal — semantic**: - Cond ordering changes; a new clause lands before `hypha-mode?` and @@ -61,7 +63,7 @@ during weekly upstream-sync, the detection grep is the first thing run; the - `:user/login` event is replaced by a new event schema upstream. - **Detection**: - Structural, automatic: - `rg -c 'defmethod events/handle :user/login' src/main/frontend/handler/events/ui.cljs` + `rg -c 'defevent! :user/login' src/main/frontend/handler/events/ui.cljs` ⇒ `1` - Semantic, manual at triage: the first cond clause must read `hypha-config/hypha-mode?`. @@ -237,8 +239,9 @@ during weekly upstream-sync, the detection grep is the first thing run; the - A third encryption-mode hook gets introduced; we should evaluate. - **Detection**: - Structural, automatic: - `rg -c 'rum/defc new-db-graph-inner' src/main/frontend/components/repo.cljs` - ⇒ `1` + `rg -c '(rum|hsx)/defc new-db-graph-inner' src/main/frontend/components/repo.cljs` + ⇒ `1` (upstream migrated the component from `rum/defc` to `hsx/defc`; + the anchor tolerates either framework form). - Semantic, manual at triage: the `cloud?` and `graph-e2ee?` initial values must read `hypha-config/hypha-mode?`. - **On break**: @@ -266,19 +269,29 @@ during weekly upstream-sync, the detection grep is the first thing run; the ;; HYPHA (defn- snapshot-stream-url "... reverse-proxy-aware ..." - [request graph-id] + [^js self request graph-id] (let [url (js/URL. (.-url request)) - headers (.-headers request) - forwarded-host (some-> headers (.get "x-forwarded-host")) - forwarded-proto (some-> headers (.get "x-forwarded-proto")) - origin (if (seq forwarded-host) - (str (if (seq forwarded-proto) forwarded-proto "http") - "://" - forwarded-host) + headers (when (trust-forwarded-headers? self) + (.-headers request)) + forwarded-host (first-forwarded-value headers "x-forwarded-host") + forwarded-proto (first-forwarded-value headers "x-forwarded-proto") + origin (if forwarded-host + (str (or forwarded-proto "http") "://" forwarded-host) (.-origin url))] (str origin "/sync/" graph-id "/snapshot/stream"))) ``` -- **Line count**: +13 (8 net lines of code, plus a 5-line docstring) + plus the helpers `trust-forwarded-headers?` (env flag + `DB_SYNC_TRUST_FORWARDED_HEADERS`) and `first-forwarded-value` (first + entry of a comma-separated header), and a 3-line pass-through of the + flag in `deps/db-sync/src/logseq/db_sync/node/graph.cljs` + (`env-object`). +- **Hardened**: 2026-11 — the headers used to be honoured from any + request and taken whole. Now they count only when the deployment sets + `DB_SYNC_TRUST_FORWARDED_HEADERS` (hypha-server's db-sync runner + always does; a bare node adapter or Cloudflare Worker does not), and + with a proxy chain (`host-a, host-b`) only the first, client-facing + entry is used. +- **Line count**: ~+35 (helpers, docstrings, flag pass-through) - **Rationale**: When db-sync runs behind hypha-server's reverse proxy, the request URL the adapter sees has the internal loopback host (`http://127.0.0.1:8787`). Using `request.url.origin` for embedded URLs @@ -290,8 +303,9 @@ during weekly upstream-sync, the detection grep is the first thing run; the them to reconstruct the public-facing URL. - **Companion change (NOT a patch)**: `hypha-server/src/proxy.ts` injects these headers on every proxied path - (rewriteRequestHeaders hook). Counts as Hypha-server-own code, not an - upstream patch. + (rewriteRequestHeaders hook), and `hypha-server/src/db-sync-runner.ts` + spawns the adapter with `DB_SYNC_TRUST_FORWARDED_HEADERS=true`. Counts + as Hypha-server-own code, not an upstream patch. - **Additive alternatives considered**: - Modify the response body in `hypha-server` proxy with a JSON-rewrite hook: rejected — fragile (depends on exact response shape) and @@ -314,7 +328,11 @@ during weekly upstream-sync, the detection grep is the first thing run; the `rg -c 'defn- snapshot-stream-url' deps/db-sync/src/logseq/db_sync/worker/handler/sync.cljs` ⇒ `1` - Semantic, manual at triage: the function body must read - `x-forwarded-host` from `.headers`. + `x-forwarded-host` from `.headers`, gated by + `trust-forwarded-headers?`. + - Regression guard: + `snapshot-download-url-uses-forwarded-headers-only-when-trusted-test` + in `deps/db-sync/test/logseq/db_sync/worker_handler_sync_test.cljs`. - **On break**: - Structural → find the new URL-building location, re-anchor. - Semantic → re-apply the X-Forwarded-Host respect logic. @@ -330,6 +348,28 @@ during weekly upstream-sync, the detection grep is the first thing run; the - **Files**: - `deps/db/src/logseq/db/frontend/schema.cljs` - `deps/db/src/logseq/db/frontend/malli_schema.cljs` + - `src/main/frontend/worker/sync/large_title.cljs` (since 2026-11, see + "Extended" below) +- **Extended**: 2026-11 — marking the attribute `:db/index true` does not + reindex. A graph that already held large-title-object datoms keeps them + out of `:avet`, so `find-large-title-object-eid` and + `rehydrate-large-titles-from-db!` found nothing there. Both walk every + datom of the attribute anyway, so they now read `:aevt` through + `large-title-object-datoms`: + ```clojure + ;; ORIGINAL (two call sites) + (d/datoms db :avet large-title-object-attr) + ;; HYPHA + (d/datoms db :aevt large-title-object-attr) + ``` + This was chosen over a versioned migration that re-transacts the + datoms: a Hypha-only entry in + `frontend.worker.db.migrate/schema-version->updates` would take the + minor version upstream uses next, and graphs already on it would skip + upstream's migration. Regression guard: + `large-title-lookups-find-datoms-that-predate-the-index-test` in + `frontend.worker.sync.large-title-test`. The schema entry stays, so an + upstream `:avet` read of the attribute cannot throw. - **Patch form** (two-piece, semantically one patch — both files must move in lockstep to keep the db-sync adapter's symmetry check happy): @@ -508,12 +548,20 @@ during weekly upstream-sync, the detection grep is the first thing run; the ;; HYPHA (defn- normalize-graph-e2ee? [graph-e2ee?] - (if (nil? graph-e2ee?) - (not (seq (:http-base @worker-state/*db-sync-config))) - (true? graph-e2ee?))) + (true? graph-e2ee?)) ``` -- **Line count**: +8 (1 line of logic plus a 7-line explanatory comment). - `crypt.cljs/graph-e2ee?` is left untouched at its upstream definition. + The frontend twin `normalize-graph-e2ee?` in + `src/main/frontend/handler/db_based/sync.cljs` has the same form. +- **Simplified**: 2026-11 — until then the nil default read + `(not (seq (:http-base @worker-state/*db-sync-config)))`, meant as + "self-hosted ⇒ false, Logseq.com ⇒ true". `:http-base` is always set + (it defaults to the Logseq.com API base), so that was always `false`. + Hypha never runs without a hypha-server, so the patch now says so + directly. The frontend twin still defaulted nil to `true` and was + aligned. +- **Line count**: -3 logic lines plus a 6-line explanatory comment, in + both files. `crypt.cljs/graph-e2ee?` is left untouched at its upstream + definition. - **Rationale**: Stock Logseq's `graph-e2ee?` returns `nil` for graphs with no explicit `:logseq.kv/graph-rtc-e2ee?` setting. Every consumer in `worker/sync/{upload,assets,apply_txs,handle_message}.cljs` treats @@ -535,14 +583,10 @@ during weekly upstream-sync, the detection grep is the first thing run; the - **Older graphs created before M9.3**: same nil default, same failure. - This patch makes the upload path's `normalize-graph-e2ee?` hypha-aware: - when the worker's `db-sync-config` has a custom `:http-base` (= - self-hosted Hypha, set by `persist_db/browser.cljs` from - `frontend.config/set-custom-sync-server-url!`), unset state defaults to - **false** (no e2ee). When `:http-base` is empty (= stock Logseq pointing - at Logseq.com), unset state keeps the safer default **true**. This is - identical in shape to M9.3's UI default reversal, just propagated through - the upload-path fallback. `graph-e2ee?` itself remains the upstream pure + This patch makes the upload path's `normalize-graph-e2ee?` default + unset state to **false** (no e2ee). This is identical in shape to + M9.3's UI default reversal, just propagated through the upload-path + fallback. `graph-e2ee?` itself remains the upstream pure passthrough; the truthiness consumers (` (sync-util/auth-token) worker-util/parse-jwt :sub)))) + (let [platform' (platform/current)] + (cond + (seq refresh-token) (p/resolved refresh-token) + (browser-runtime? platform') () - ;; frontend.worker.sync.auth/) + ;; frontend.worker.sync.auth/c` now. + - Only 401/403 from `/auth/session` count as a lost session. Offline + (`:status 0`) and 5xx reject in `