Repository navigation
fix(mobile-bar): toolbar stays above the keyboard at the page bottom - #311
cameronapak wants to merge 59 commits into
Conversation
Greenfield Lunora Vite+React app under spikes/lunora-outline to prove ADR 0009 invariants without Dotflowy custom sync. Co-authored-by: Cursor <cursoragent@cursor.com>
Replace messages demo with outline nodes (Dotflowy field parity), wholeOutline shape (owner-only where), and Better Auth + authorizeShard identity.userId === shardKey. Co-authored-by: Cursor <cursoragent@cursor.com>
Port orderSiblings/chainDisagreements and structural plan* helpers; vitest proves rapid insert/indent/outdent/remove sequences leave chainDisagreements empty (ADR 0009). Co-authored-by: Cursor <cursoragent@cursor.com>
Server defineMutator + client bindMutators share plan*; shape sync and auth gate enable a tiny list UI for two-tab live convergence demos. Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Extract one rowToNode/docToNode helper, add ADR 0004 lunora-bridge + idempotent demo seed, trim unused Vite assets/CSS, update spike README. Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
DO watermark FIFO serializes concurrent seeds; second call no-ops. Deterministic DEMO_SEED_IDS keep optimistic overlays converging. Also unify nodeToRow map and distinguish empty-UI seeding vs truly empty. Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Record cutover decision: authoritative mutators + shapes replace
custom {ops} sync. Amend ADR 0008 divergence #1; no PR until
full cutover and pre-existing tests are green.
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
…plans Converge spike plan* / seed / map-node on Dotflowy Node + tree.ts helpers. Spike imports via @dotflowy/outline-plans Vite alias; bun + pnpm tests pass. Co-authored-by: Cursor <cursoragent@cursor.com>
Add root lunora/ schema+mutators (shared outline-plans), route /_lunora to defineApp with product Better Auth identity bridge. No dual signup UX. Co-authored-by: Cursor <cursoragent@cursor.com>
HANDOFF status → phase-2-compose; spike README points at shared planners. Co-authored-by: Cursor <cursoragent@cursor.com>
Default-OFF `dotflowy:flag:lunora-sync` swaps tree-store feed and dogfood mutations onto `@lunora/db` wholeOutline + bindMutators, leaving `/api/sync` untouched for Playwright and normal dev. Co-authored-by: Cursor <cursoragent@cursor.com>
Record flag name, smoke steps, architecture sketch, and known gaps. Co-authored-by: Cursor <cursoragent@cursor.com>
Port insertChildAtStart, field toggles, moveNode, and atomic splitNode so flag-ON editing covers Enter/move/complete/task/kind/bookmark without the custom-DO wire. Co-authored-by: Cursor <cursoragent@cursor.com>
…mirrors Route undo/redo through one restoreNodes watermark and /mirror through planMirrorNode, closing two high-leverage Lunora dogfood gaps. Co-authored-by: Cursor <cursoragent@cursor.com>
Close ADR 0018 batch gaps with one watermark each (removeMany/moveMany/ indentMany/outdentMany), parent mirror indents into the content source, and route daily scaffold+day node writes through materializeDailyNodes while kv claims stay on /api/kv. Co-authored-by: Cursor <cursoragent@cursor.com>
Record new mutators and remaining flag-ON work (OPML, quick-add appendChild, e2e, KV phase 2b). Co-authored-by: Cursor <cursoragent@cursor.com>
Route quick-add born and OPML import through Lunora mutators when the sync flag is ON, and start side-collections (tagColors + savedQueries) on the same shard/clientSeq FIFO. dailyIndex stays on /api/kv. Co-authored-by: Cursor <cursoragent@cursor.com>
Record appendChild, importNodes chunking caveats, drag path OK, and tagColors/savedQueries on Lunora; dailyIndex still deferred. Co-authored-by: Cursor <cursoragent@cursor.com>
Atomic get-or-create twin of DO getOrCreateKv; claimMapping/setMapping ride Lunora when lunora-sync is ON. touchedAt bumps so watermark pokes fire. Co-authored-by: Cursor <cursoragent@cursor.com>
Auto-runs when flag ON and Lunora shard is empty; skips if non-empty. More menu + window.__dotflowyMigrateToLunora for manual retry. Co-authored-by: Cursor <cursoragent@cursor.com>
Mocks /_lunora/ws + /_lunora/rpc enough for flag-ON load/edit/reload. Classic seedOutline remains the default for the existing suite. Co-authored-by: Cursor <cursoragent@cursor.com>
Record dual-path pass/skip matrix, dogfood migrate FAIL, keep flag OFF. Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Hardens lunora-structural /delete against a watermark race, and records the broader E2E_LUNORA matrix (355 pass / 13 skip). Co-authored-by: Cursor <cursoragent@cursor.com>
Local-only dogfood path for Lunora MCP writes: comp an unlimited subscription row in local D1, mint a real Better Auth MCP bearer via PKCE, and document the live tools/call PASS in HANDOFF. Co-authored-by: Cursor <cursoragent@cursor.com>
delete-confirm could time out on big rows when shape hydration lagged page.goto in the full serial suite. Add openSeededOutline helpers and use them in delete-confirm; HANDOFF records 356/0/13 on E2E_PORT=3235. Co-authored-by: Cursor <cursoragent@cursor.com>
Flip isLunoraSyncEnabled and isLunoraOutlineEnabled to ON when unset; keep localStorage/?lunora-sync=off and LUNORA_OUTLINE=0|false|off as escape hatches. Classic e2e seedOutline forces flag off so the default suite stays on /api/sync mocks. Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Account deletion now erases the Lunora SHARD (system RPC wipeUserShard) alongside USER_OUTLINE. Shell sync-ready and seedIfEmpty run only after auto-migrate settles. Document paired kill-switches (ADR 0051/0055). Co-authored-by: Cursor <cursoragent@cursor.com>
Lunora outline sync defaults OFF; Settings beta toggle writes account-prefs and mirrors localStorage before reload. Worker MCP reads env force then the same preference on classic DO. Co-authored-by: Cursor <cursoragent@cursor.com>
Stamp TanStack direct-tx metadata and wait on shape-first checkpoints so the 3s fallback no longer reverts keystrokes. Also hardens kv natural keys, beta Settings copy, More menu actions-first with Copy as Markdown, and cf:dev jsxDEV. Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Production Lunora path owns sync; drop spikes/lunora-outline and retarget ADR/comments/lint ignores that pointed at it. Co-authored-by: Cursor <cursoragent@cursor.com>
One minor user-facing fragment; drop e2e/internal patch notes that shouldn't ship in What's new. Co-authored-by: Cursor <cursoragent@cursor.com>
Harden MCP shard decode, force restore/import userId, unify empty applyChangeOps counts, and pin e2e SPA nav + caret placement. Co-authored-by: Cursor <cursoragent@cursor.com>
Await account-prefs kvPut before reload; refuse classic undo when Lunora is on but sync isn't ready; map failed RPC bodies to status errors. Co-authored-by: Cursor <cursoragent@cursor.com>
A flag-gated (`?kbdebug=on`) overlay printing innerHeight, clientHeight, the visualViewport band, and the mobile bar's measured rect, so the ADR 0030 keyboard anchoring could be diagnosed on a real iPhone rather than reasoned about. Removed again in the follow-up commit; kept in history because iOS viewport behavior changes and this will be worth re-applying. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The mobile actions bar and quick-add panel could sit behind the software keyboard when editing near the bottom of a long page, and could drift up the screen mid-session. Both surfaces lifted by `innerHeight - (visualViewport.height + offsetTop)`. On iOS Safari `innerHeight` is not a stable quantity: it read 714, 635 and 279 in one simulator session, and 526 then 482 on a physical iPhone with nothing else changing. At the bottom of a long page it collapses to equal `visualViewport.height`, which reduces the expression to `-offsetTop` -- always negative, always clamped to zero, so the bar never lifted. `clientHeight` and the VirtualKeyboard API's per-focus baseline were both tried and both fail the same way: Safari moves the box `position: fixed; bottom: 0` resolves against, and no property reliably names it, so every formula is correct only while the chrome sits where it assumed. So measure it. `data/keyboard-inset.ts` appends a zero-size fixed bottom:0 probe and publishes `probe.bottom - visualViewport.height` as `--kb-inset` on <html>. Consumers read the custom property, so the keyboard animation costs zero React re-renders, and the safe-area pad subtracts the same inset rather than branching on it. `useKeyboardViewport` is deleted. ADR 0030 records all four rejected approaches with the measurements that killed each; AGENTS.md leads with "measure the anchor, don't compute it". Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
📝 WalkthroughWalkthroughLunora outline synchronization is added behind an opt-in beta setting, with sharded storage, server-authoritative mutations, classic-to-Lunora migration, MCP routing, editor integration, mobile keyboard positioning updates, and expanded unit and end-to-end coverage. ChangesLunora rollout
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related issues
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 20
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
worker/auth.ts (1)
224-233: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftShard wipe after the classic DO wipe reintroduces a partial-failure data-loss window.
stub.wipe()(classic outline) is irreversible;wipeLunoraUserShardnow runs after it and throws on RPC failure, aborting the wholedeleteUser(account survives). If the shard RPC fails for any reason (network blip, Lunora shard outage), the user is left with an intact account but a permanently wiped classic outline — deletion reports failure yet real data was already destroyed. The comment above this block ("DO wipe (irreversible, last)") no longer matches the code: the shard wipe is now the true last, and equally irreversible, step.Consider either reordering (attempt the shard wipe before the classic wipe) or accepting/documenting that both irreversible ops can partially fail — but the existing comment should be updated either way so the invariant it documents isn't misleading.
As per coding guidelines, "Update agent or human documentation in the same change when objective repository facts, paths, commands, or tooling become stale."
Also applies to: 248-255
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@worker/auth.ts` around lines 224 - 233, Reorder the deletion steps in beforeDelete so wipeLunoraUserShard completes before the irreversible classic outline operation stub.wipe; preserve the guard and Stripe cancellation ordering. Update the surrounding comments to identify the shard wipe as the first irreversible step and stub.wipe as the final step, accurately describing failure behavior. Ensure deleteUser still aborts when either wipe fails.Source: Coding guidelines
src/components/OutlineEditor.tsx (1)
1476-1503: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winAdd quick-add parity for Enter mid-split behavior.
src/components/OutlineEditor.tsx:1418now performs the keymap’s new mid-text split path, butsrc/components/quick-add.tsx:949still usesonEnter: noop, while docs describe Enter as commit/close. Either wire this row through the same split-capable Enter handler or replace the stale commit/close docs with the actual quick-add Enter behavior.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/components/OutlineEditor.tsx` around lines 1476 - 1503, Update the quick-add Enter handling in the relevant quick-add row configuration, replacing the current noop with the same split-capable Enter behavior used by OutlineEditor’s keymap path. Ensure mid-text Enter splits the node consistently while preserving the documented commit/close behavior where applicable.Source: Path instructions
🟡 Minor comments (10)
src/data/lunora-checkpoints.ts-16-24 (1)
16-24: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winGuard against
@tanstack/dbinternal metadata behavior.
__tanstack_db_directis not part of TanStack DB’s documented public API, so this optimistic-hold/prevent revert logic can fail silently when@tanstack/dbchanges its internal direct-tx handling. Capture the expected library behavior in a regression test and add a dependency-upgrade check/CI guard for this magic string.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/lunora-checkpoints.ts` around lines 16 - 24, Protect the direct-transaction behavior centered on DIRECT_TRANSACTION_METADATA_KEY by adding a regression test that verifies optimistic rows remain present and typed values are not reverted when mutationFn completes without pending shape sync. Also add a dependency-upgrade or CI guard that detects changes to TanStack DB’s handling of the "__tanstack_db_direct" metadata key, so updates cannot silently invalidate this fallback.src/data/outline-plans/seed.ts-16-21 (1)
16-21: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winInternal jargon in first-run user-facing copy.
These four strings land in a real opted-in beta user's outline:
maybeSeed(src/data/lunora-sync.tslines 146-162) firesseedIfEmptywhenever the shard is empty, andmaybeAutoMigrateToLunorareturns"seed"precisely for a brand-new account with no classic data. "Lunora outline spike" and "restores fromwholeOutline" expose implementation vocabulary as product copy.✏️ Suggested user-facing wording
export const DEMO_SEED_TEXTS = [ - "Welcome to the Lunora outline spike", + "Welcome to Dotflowy", "Open a second tab — edits sync live", "Try indent / outdent / delete", - "Hard reload restores from wholeOutline", + "Reload anytime — your outline is saved", ] as const;🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/outline-plans/seed.ts` around lines 16 - 21, Update the user-facing strings in DEMO_SEED_TEXTS to remove internal implementation terminology, replacing “Lunora outline spike” and “wholeOutline” with clear product language while preserving the intended onboarding guidance about syncing, editing, and restoring after a reload.docs/adr/0055-lunora-replaces-custom-outline-sync.md-38-39 (1)
38-39: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winStep 5 contradicts the "production defaults OFF" lock.
Line 28 states classic DO stays the default for browser and MCP until a user opts in, and ADR 0051 still documents wiping
USER_OUTLINEon account deletion — but step 5 lists deletingUserOutlineDOcustom changelog sync as part of this sequence. Mark it as not-yet-done / post-rollout so the record doesn't read as if classic sync is already gone.📝 Suggested wording
-5. Migrate kv side-collections; remount MCP onto mutators; snapshot-migrate user data; delete `UserOutlineDO` custom changelog sync. +5. Migrate kv side-collections; remount MCP onto mutators; snapshot-migrate user data. **Deferred until opt-in rollout completes:** delete `UserOutlineDO` custom changelog sync (classic DO is still the default per "Identity / e2e / kv" above, and is still wiped on account deletion — ADR 0051).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/adr/0055-lunora-replaces-custom-outline-sync.md` around lines 38 - 39, Update step 5 in the migration sequence to mark deletion of UserOutlineDO custom changelog sync as post-rollout or not yet completed, preserving classic DO sync as the production default until opt-in. Keep the existing migration tasks unchanged and ensure the wording does not imply classic sync has already been removed.src/data/lunora-outline-store.ts-489-501 (1)
489-501: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winUse a Lunora-safe optimistic key for saved query migration.
savedQuerieshas nogetKeyoverride, so the optimistic insert keys on_id: args.id.saved-query.tscreates rows with UUID/generated ids, butlunora-migrate.tsfalls back toString(v.id ?? row.key), so a classically migrated row withoutvalue.idcan insert an arbitrary kv key as_id, contradicting the documented server_id/clientId invariant. Generate or look up a Lunora-safe saved-query id during migration instead of reusing the kv key.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/lunora-outline-store.ts` around lines 489 - 501, Update the saved-query migration in lunora-migrate.ts to generate or resolve a Lunora-safe saved-query identifier when value.id is absent, instead of falling back to row.key. Ensure migrated rows use the same server _id/clientId invariant expected by savedQueries and saved-query.ts, including for optimistic inserts.src/data/outline-plans/planners.ts-832-849 (1)
832-849: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
nullconflates "invalid" with "already materialized", so idempotent retries throw.If every requested id already exists, all inserts are skipped and
planFromWorkingCopyreturnsnull, whichlunora/mutators.tsL688 turns intomaterializeDailyNodes: no-op or invalid. A retry after a dropped response — or a lost daily claim race — therefore surfaces an error on a fully-successful state. Distinguish the two (an empty plan for no-op,nullonly for invalid placement) and let the mutator return early, matching howplanSeedIfEmptyis handled at L294.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/outline-plans/planners.ts` around lines 832 - 849, The insert planner should return an explicit empty plan when every requested ID is already present, reserving null for invalid placement. Update the logic around the inserts loop and planFromWorkingCopy so idempotent retries produce a no-op plan, and update materializeDailyNodes to recognize that plan and return early like planSeedIfEmpty.src/data/outline-plans/change-ops.test.ts-14-28 (1)
14-28: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winTest asserts bucket shape, not the applied outcome — it green-lights the same-id ordering defect.
The fixture inserts and then updates the same id
n1, which is precisely the case that misapplies under deletes → patches → inserts. AssertingapplyPlan(...)(or the commit order) would catch it; as written the expectations pass either way.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/outline-plans/change-ops.test.ts` around lines 14 - 28, Update the test around planFromChangeOps to verify the applied outcome rather than only the deletes, inserts, and patches buckets. Apply the generated plan using the existing applyPlan or commit-order path, then assert that the same-id insert/update case produces the updated “hello!” record and does not retain the stale “hello” value.lunora/mcp.ts-130-133 (1)
130-133: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winSilent fallbacks fabricate daily-index mappings.
A row missing
keygets the row_idas its key, and a row missingnodeIdbecomes"". Both flow straight into MCPclaimDailyScaffoldas if they were real mappings. Skip malformed rows instead of coercing them.🐛 Proposed fix
- return rows.map((r) => ({ - key: String(r.key ?? r._id), - nodeId: String(r.nodeId ?? ""), - })); + return rows.flatMap((r) => + typeof r.key === "string" && typeof r.nodeId === "string" + ? [{ key: r.key, nodeId: r.nodeId }] + : [], + );🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@lunora/mcp.ts` around lines 130 - 133, Update the row-mapping logic to validate that each row has both a real key and nodeId before creating a mapping; skip malformed rows rather than falling back to r._id or an empty string. Preserve the existing string conversion for valid values and ensure only validated mappings reach claimDailyScaffold.src/data/lunora-client.ts-16-20 (1)
16-20: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winGuard against an empty-string
VITE_LUNORA_URL.
??doesn't catch an empty string, so a defined-but-empty env var silently producesnew LunoraClient({ url: "" })instead of falling back towindow.location.origin.🛡️ Proposed fix
- const url = - (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? - window.location.origin; + const envUrl = import.meta.env.VITE_LUNORA_URL as string | undefined; + const url = envUrl && envUrl.trim() !== "" ? envUrl : window.location.origin;🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/lunora-client.ts` around lines 16 - 20, Update the URL selection in the client initialization block guarded by `if (!client)` so an empty or whitespace-only `VITE_LUNORA_URL` falls back to `window.location.origin`, while preserving non-empty configured URLs. Ensure `new LunoraClient` receives the resolved valid URL.scripts/react-jsx-dev-runtime-shim.ts-1-23 (1)
1-23: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winKeep the
jsxDEValias production-only. Right now it is unconditionally registered in Vite, so the dev server also uses the shim and dropssource/selfdebug info from realjsxDEVcalls. Gate it to production-only paths or keep the existing comment accurate.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@scripts/react-jsx-dev-runtime-shim.ts` around lines 1 - 23, Update the Vite alias registration for the jsxDEV shim so it is applied only to production paths such as cf:dev/build:cf, while the normal dev server continues resolving React’s real jsx-dev-runtime. Keep the shim implementation unchanged and ensure its comment accurately describes the production-only alias behavior.e2e/fixtures.ts-602-613 (1)
602-613: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winPer-connection-prune the shape subscription maps.
page.reload()closes the original WS (sockets.delete) but leavesshapeSubs,shapeCheckpoints, andshapeKeysintact. A fresh client can hit the existing shape id, getbaseCheckpoint: 1, and receive a previous shape diff that includes its own freshly inserted/updated rows, causing the pending watermark to complete too early. Use a per-WS subscription/pruning path instead of global mutable shape maps.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@e2e/fixtures.ts` around lines 602 - 613, The shape subscription state in the WebSocket connection flow must be scoped and pruned per connection: when a socket closes or is removed, remove its associated entries from shapeSubs, shapeCheckpoints, and shapeKeys so a reloaded client cannot reuse stale checkpoints or diffs. Update the socket lifecycle and shape subscription handling around sockets, preserving independent state for active connections and preventing prior-client data from completing a new client’s pending watermark.
🧹 Nitpick comments (18)
src/data/lunora-migrate.ts (2)
213-232: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winGate the global migration helper to dev builds.
__dotflowyMigrateToLunorais attached towindowin production for every user. It's scoped to the caller's own store/userIdand refuses when the shard is non-empty, so it isn't a trust-boundary hole — but shipping a data-migration trigger on the global object is an avoidable footgun.🔒 Proposed guard
export function installMigrateConsoleHelper( getStore: () => { store: OutlineStore; userId: string } | null, ): void { if (typeof window === "undefined") return; + // Dev/dogfood only — the More-menu entry is the supported user-facing path. + if (!import.meta.env.DEV) return;If the More menu genuinely needs it in production, call
migrateClassicToLunoradirectly from that handler instead of round-tripping through a global.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/lunora-migrate.ts` around lines 213 - 232, Gate installMigrateConsoleHelper so it only attaches __dotflowyMigrateToLunora in development builds, using the project’s existing dev-environment check. Preserve the current migration callback behavior when enabled, and leave production callers without the global helper; if a production More-menu action needs migration, invoke migrateClassicToLunora directly instead.
104-157: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winPer-row awaited round trips, and a dropped kv fetch is reported as a successful migration.
Two things on this function:
- Every row is its own awaited transaction across three loops. A daily index accrues one row per day used, so this is hundreds of sequential RPCs — and
lunora-sync.tsholdsmarkNodesSyncReady()until migrate settles, so the user stares at a gated shell for the duration. Batch per collection (or at least run the three collections concurrently).fetchKv(...).catch(() => [])on Lines 108, 119, and 140 discards an entire collection on any failure, yetmigrateClassicToLunorastill returns{status:"migrated"}. A user whose/api/kv?collection=tag-colorsrequest blips loses all tag colors with no signal. At minimum count the skipped collections and report them inMigrateResult.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/lunora-migrate.ts` around lines 104 - 157, Update importKv to avoid one sequential awaited transaction per row by batching each collection’s mutations or running the three collection imports concurrently while preserving persistence completion. Replace the silent fallback catches for tag-colors, saved-queries, and daily-index with tracked collection failures, and propagate the skipped-collection count/details through migrateClassicToLunora’s MigrateResult so partial imports are not reported as fully migrated.src/data/lunora-outline-store.ts (2)
144-148: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win20+ structural
applybodies repeat the same three lines.Nearly every mutator is
buildTreeIndex(snapshotNodes(collection))→planX(...)→if (plan) applyPlanToCollection(collection, plan). Two small helpers would collapse the bulk of this file and give the index-caching fix a single place to land.♻️ Sketch
const indexed = <A>(serverRef: string, plan: (i: TreeIndex, a: A) => OutlinePlan | null) => defineMutator<A>({ serverRef, apply: (_ctx, args) => { const p = plan(buildTreeIndex(snapshotNodes(collection)), args); if (p) applyPlanToCollection(collection, p); }, }); const listed = <A>(serverRef: string, plan: (n: OutlineNode[], a: A) => OutlinePlan | null) => defineMutator<A>({ serverRef, apply: (_ctx, args) => { const p = plan(snapshotNodes(collection), args); if (p) applyPlanToCollection(collection, p); }, }); // insertSibling: indexed<InsertSiblingArgs>("mutators:insertSibling", planInsertSibling), // indentMany: listed<IndentManyArgs>("mutators:indentMany", (n, a) => // planIndentMany(n, a.nodeIds, a.updatedAt, a.resolveMirror ?? false)),Also applies to: 429-437
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/lunora-outline-store.ts` around lines 144 - 148, Refactor the repeated mutator apply bodies in this module by introducing shared indexed and listed mutator helpers near the existing mutator definitions. Have the indexed helper centralize buildTreeIndex(snapshotNodes(collection)), planning, and conditional applyPlanToCollection, while the listed helper centralizes snapshotNodes(collection), planning, and application; update mutators such as the apply body using planInsertSibling and the additional occurrences to use these helpers without changing their server references or planner arguments.
61-70: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winAvoid monkey-patching the Lunora checkpoint method.
resolveis part of an alpha API and Lunora calls it internally; reassigningfrom.resolveis fragile and can break if that contract changes. If Lunora exposes a subscribe/onResolve callback oncheckpoints, register a relay through that instead.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/lunora-outline-store.ts` around lines 61 - 70, Replace the monkey-patching in relayCheckpoints with Lunora’s supported checkpoints subscription or onResolve callback, registering a handler that forwards each resolved watermark to the target CheckpointRegistry. Preserve the existing from-to relay behavior without reassigning from.resolve.src/data/outline-plans/planners.test.ts (1)
597-610: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDead setup in the cycle test.
Lines 598-601 build and mutate a fixture that is immediately discarded by the reassignment on L604. Drop it so the test reads as the single scenario it actually asserts.
♻️ Proposed cleanup
it("refuses a cycle when mirror prev sibling resolves into self", () => { - let nodes = seedFlat(["x", "m"]); - nodes = nodes.map((n) => - n.id === "m" ? { ...n, mirrorOf: "x", text: "x" } : n, - ); - // Indenting nothing after m that would cycle — indent m under x is fine. - // Cycle: indent a node whose prev sibling mirrors THAT node. - nodes = seedFlat(["a", "m", "b"]); - nodes = nodes.map((n) => + // Cycle: indent a node whose prev sibling mirrors THAT node. + const nodes = seedFlat(["a", "m", "b"]).map((n) => n.id === "m" ? { ...n, mirrorOf: "b", text: "b" } : n, );🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/outline-plans/planners.test.ts` around lines 597 - 610, Remove the initial seedFlat(["x", "m"]) setup and mutation in the test “refuses a cycle when mirror prev sibling resolves into self”, keeping only the later ["a", "m", "b"] scenario and its assertion.lunora/mcp.ts (1)
43-85: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
MutatorDb/MutatorCtx/assertOwner/commitPlanare duplicated verbatim fromlunora/mutators.ts(L40-L123).Two copies of the shard ctx types and the commit ordering will drift — the mutators copy already carries the ordering rationale comment that this one lacks. Extract them into a shared
lunora/shard-ctx.ts(or similar) and import in both.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@lunora/mcp.ts` around lines 43 - 85, Extract the shared MutatorDb, MutatorCtx, assertOwner, and commitPlan definitions from lunora/mcp.ts into a common shard context module, preserving the existing commit ordering and rationale comment from lunora/mutators.ts. Update both mcp.ts and mutators.ts to import and reuse these shared symbols, removing their duplicate local definitions.lunora/mutators.ts (1)
508-513: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winNo upper bound on the
nodessnapshot arrays.
restoreNodesandimportNodesaccept arbitrarily long arrays and commit them in one transaction. A malformed client (or a very large outline) can push the DO past its transaction budget with no server-side guard. A validated max length (with the client already chunking imports, per the L534-L538 note) makes the failure mode explicit instead of a transaction abort.Also applies to: 539-543
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@lunora/mutators.ts` around lines 508 - 513, Validate an explicit maximum length for the snapshot arrays accepted by restoreNodes and importNodes, using the existing validator configuration and a shared limit where appropriate. Ensure oversized nodes inputs are rejected before either mutator commits its transaction, while preserving the client-side chunking behavior for valid imports.src/data/outline-plans/map-node.ts (1)
51-53: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winOutbound helpers erase field types.
Because
NodeDocLiketypes every field asunknown,nodeToDocFields/nodeToRow/nodeToInsertFieldsall returnunknown-valued fields — so the optimistic-insert call sites get no checking on the very boundary this module exists to guard. Deriving the return type fromOutlineNodekeepsNodeDocLikeloose for inbound rows while typing the outbound payload.♻️ Proposed typing
+type NodeRow = Omit<OutlineNode, "id"> & { _id: string; _creationTime: number }; + export function nodeToDocFields( node: OutlineNode, -): Omit<NodeDocLike, "_id"> & { _id: string; _creationTime: number } { +): NodeRow {export function nodeToInsertFields( node: OutlineNode, -): Omit<ReturnType<typeof nodeToDocFields>, "_id" | "_creationTime"> { +): Omit<NodeRow, "_id" | "_creationTime"> {Also applies to: 77-82
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/outline-plans/map-node.ts` around lines 51 - 53, Update the outbound helpers nodeToDocFields, nodeToRow, and nodeToInsertFields to derive their field types from OutlineNode rather than NodeDocLike, while preserving the explicit _id and _creationTime types. Keep NodeDocLike loose for inbound row handling, and ensure optimistic-insert call sites receive checked payload field types.lunora/ratelimit/schema.ts (1)
18-22: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winType
ctx.dbthrough Lunora’s generated facade.
"ratelimit_buckets"is already generated consistently, butdb: ctx.db as neverbypasses Lunora’s generated DB shape, so any future table-name or schema-level drift is not caught at typecheck. Use the generated DB facade/type here instead ofunknown.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@lunora/ratelimit/schema.ts` around lines 18 - 22, Update makeRateLimiter so ctx.db uses Lunora’s generated database facade/type rather than unknown, and remove the db: ctx.db as never cast when calling createDbStore. Preserve the existing "ratelimit_buckets" table configuration while ensuring generated schema changes are checked by the type system.worker/index.ts (1)
101-104: 🧹 Nitpick | 🔵 Trivial
ShardDOisn't wrapped by Sentry (documented as TEMP).Errors thrown inside
ShardDOwon't surface in Sentry the wayUserOutlineDOdoes, which is a real observability gap on a path now carrying live outline writes. The comment already flags this as a HANDOFF item — just noting it so it doesn't get lost.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@worker/index.ts` around lines 101 - 104, Wrap the exported ShardDO with the same Sentry Durable Object instrumentation used by UserOutlineDO, updating the ShardDOState typing or adapter as needed to satisfy Sentry’s DurableObjectState constraint while preserving the SHARD binding export.scripts/comp-dev-plan.ts (1)
41-53: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winGuard
userIdbefore interpolating it into the SQL command.
wrangler d1 execute --commandtakes no bound parameters, so the id is spliced raw into SQL. Even in a local-only script, an id containing a quote breaks the statement, and the pattern is easy to copy into a less-trusted context later. A cheap shape check keeps it honest.🛡️ Proposed guard
function compSubscription(userId: string): void { + // `wrangler d1 execute` has no bound params — refuse anything that isn't a + // plain id so the interpolation below can't break (or extend) the statement. + if (!/^[A-Za-z0-9_-]+$/.test(userId)) { + throw new Error(`unexpected user id shape: ${JSON.stringify(userId)}`); + } const proc = Bun.spawnSync(🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@scripts/comp-dev-plan.ts` around lines 41 - 53, Validate userId at the start of compSubscription before interpolating it into the SQL command, enforcing the expected identifier shape and rejecting invalid values. Keep the existing SQL execution path unchanged for valid IDs, and fail immediately with a clear error for invalid input.src/data/flags.ts (1)
53-66: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueConsider memoizing the resolved flag — it's read on hot paths.
Because the flag can only change via a reload (Settings toggle calls
hardReset, URL override is per-load), each call re-parsingwindow.location.searchis pure overhead.getLiveNodes,hasNode,liveOutlineNodes, and bothrunStructural*entry points all call this per invocation, several of them inside per-index-build code paths.♻️ Resolve once per load
+let lunoraSyncResolved: boolean | null = null; + export function isLunoraSyncEnabled(): boolean { if (typeof window === "undefined") return LUNORA_SYNC_DEFAULT; + if (lunoraSyncResolved !== null) return lunoraSyncResolved; try { const q = new URLSearchParams(window.location.search).get("lunora-sync"); - if (q === "on" || q === "1") return true; - if (q === "off" || q === "0") return false; + if (q === "on" || q === "1") return (lunoraSyncResolved = true); + if (q === "off" || q === "0") return (lunoraSyncResolved = false); const v = window.localStorage.getItem(LUNORA_SYNC_FLAG_KEY); - if (v === "on") return true; - if (v === "off") return false; + if (v === "on") return (lunoraSyncResolved = true); + if (v === "off") return (lunoraSyncResolved = false); } catch { // localStorage / URLSearchParams can throw; fall back to the default. } - return LUNORA_SYNC_DEFAULT; + return (lunoraSyncResolved = LUNORA_SYNC_DEFAULT); }Note
src/data/flags.test.tsmutates the stub between tests, so caching needs a test-visible reset (or the memo lives in a small internal helper the tests can clear).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/flags.ts` around lines 53 - 66, Memoize the resolved value in isLunoraSyncEnabled so URL and localStorage parsing occurs once per page load, while preserving the existing default and override precedence. Provide a test-visible reset mechanism for the cached value so flags.test.ts can clear it after mutating its stubs, and ensure hardReset continues to establish a fresh resolution when appropriate.src/data/flags.test.ts (1)
50-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd the numeric URL forms and the throwing-storage fallback.
isLunoraSyncEnabledalso accepts?lunora-sync=1|0and swallows storage exceptions; neither is covered, so a regression in either branch passes.💚 Suggested additions
test("URL ?lunora-sync=off wins over localStorage on", () => { store.set(LUNORA_SYNC_FLAG_KEY, "on"); location.search = "?lunora-sync=off"; expect(isLunoraSyncEnabled()).toBe(false); }); + + test("numeric URL forms are honored", () => { + location.search = "?lunora-sync=1"; + expect(isLunoraSyncEnabled()).toBe(true); + location.search = "?lunora-sync=0"; + expect(isLunoraSyncEnabled()).toBe(false); + }); + + test("falls back to the default when storage throws", () => { + (globalThis as { window?: unknown }).window = { + localStorage: { + getItem: () => { + throw new Error("private mode"); + }, + }, + location, + }; + expect(isLunoraSyncEnabled()).toBe(false); + }); });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/flags.test.ts` around lines 50 - 61, Add tests in the existing isLunoraSyncEnabled suite for the numeric URL values, asserting ?lunora-sync=1 enables and ?lunora-sync=0 disables regardless of localStorage. Also mock storage access in the store setup to throw and verify isLunoraSyncEnabled falls back to its documented default without propagating the exception.src/plugins/daily/get-or-create.ts (1)
74-85: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win
liveOutlineNodes()duplicates the branchgetLiveNodes()already owns, and each lookup allocates the whole outline.
getLiveNodes()(src/data/live-nodes.tsLines 19-29) already returns Lunora rows when the flag is on and the context exists, so theliveOutlineNodes()pre-check is redundant inhasNode,hasChildInLiveCollection, andhealExistingDay. Worse, every call maps the entire collection into a fresh array just to run.some()— andhasNodeis called per scaffold key inclaimScaffoldNode, again in the apply-time revalidation, and insiderunDailyMigration's claim/create loops, so a migration pays O(keys × nodes) plus one full array allocation per probe.♻️ Collapse to one source and stop materializing arrays
-function liveOutlineNodes(): OutlineNode[] | null { - if (!isLunoraSyncEnabled()) return null; - const lunora = getLunoraOutlineContext(); - if (!lunora) return null; - return lunora.store.collection.toArray.map(rowToNode); -} - function hasNode(id: string): boolean { - const lunoraNodes = liveOutlineNodes(); - if (lunoraNodes) return lunoraNodes.some((n) => n.id === id); - return getLiveNodes().some((n) => n.id === id); + return buildTreeIndex(getLiveNodes()).byId.has(id); }(or better: hoist one index per flow —
claimScaffoldNode/runDailyMigrationcan share a singlebuildTreeIndex(getLiveNodes())instead of re-deriving per probe.)Also applies to: 405-411
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/plugins/daily/get-or-create.ts` around lines 74 - 85, Remove liveOutlineNodes and make hasNode, hasChildInLiveCollection, and healExistingDay use getLiveNodes directly, eliminating the redundant Lunora branch and full-collection mapping. Replace repeated per-probe scans with an appropriate tree/index lookup; where possible, build one index from getLiveNodes and reuse it throughout claimScaffoldNode and runDailyMigration, including apply-time revalidation.src/data/keyboard-inset.ts (1)
34-44: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win
isEditing()is broader than "text-editable", and the loop runs on pointer devices with no software keyboard.el instanceof HTMLInputElementis true forcheckbox/radio/range/button, and any focused contentEditable keeps a per-framegetBoundingClientRect()running for the whole editing session — on desktop that is a permanent forced layout with--kb-insetpinned at0. Narrowing the input check and gating the loop on a coarse pointer (or onvv.heightactually differing from the layout viewport) keeps the measurement where it pays off.♻️ Suggested narrowing
+const TEXT_INPUT_TYPES = new Set([ + "text", + "search", + "url", + "tel", + "email", + "password", + "number", +]); + function isEditing(): boolean { const el = document.activeElement; - return ( - el instanceof HTMLElement && - (el.isContentEditable || - el instanceof HTMLInputElement || - el instanceof HTMLTextAreaElement) - ); + if (!(el instanceof HTMLElement)) return false; + if (el.isContentEditable || el instanceof HTMLTextAreaElement) return true; + return el instanceof HTMLInputElement && TEXT_INPUT_TYPES.has(el.type); }Also applies to: 62-79
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/keyboard-inset.ts` around lines 34 - 44, Update isEditing() to recognize only text-capable input types, excluding checkbox, radio, range, button, and other non-text controls. Also gate the per-frame keyboard-inset measurement loop on a coarse pointer or an actual visual-viewport height difference from the layout viewport, so contentEditable on desktop does not continuously call getBoundingClientRect() while --kb-inset remains zero.src/data/mutations.ts (1)
67-88: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider extracting the repeated Lunora preamble. The
isLunoraSyncEnabled()+getLunoraOutlineContext()+trackLunoraMutation(...)triad is copied into ~20 mutators; a new mutator that forgets theif (lunora)fallback silently writes to the idle classic collection. A tiny helper keeps the guard in one place:♻️ Sketch of the helper
// lunora-sync.ts (or a local helper in mutations.ts) export function withLunora<T>( run: (ctx: LunoraOutlineContext) => T, ): { hit: true; value: T } | { hit: false } { if (!isLunoraSyncEnabled()) return { hit: false }; const lunora = getLunoraOutlineContext(); return lunora ? { hit: true, value: run(lunora) } : { hit: false }; }- if (isLunoraSyncEnabled()) { - const lunora = getLunoraOutlineContext(); - if (lunora) { - const t = now(); - trackLunoraMutation( - lunora.store.mutators.insertSibling({ id, userId: lunora.userId, ... }), - ); - return id; - } - } + const routed = withLunora((lunora) => { + const t = now(); + trackLunoraMutation( + lunora.store.mutators.insertSibling({ id, userId: lunora.userId, ... }), + ); + return id; + }); + if (routed.hit) return routed.value;🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/data/mutations.ts` around lines 67 - 88, Extract the repeated Lunora guard and mutation tracking flow into a shared withLunora helper, using the existing isLunoraSyncEnabled, getLunoraOutlineContext, and trackLunoraMutation behavior. Update the mutator branches, including the insertSibling path, to invoke this helper and return the handled value only when it reports a hit; otherwise preserve the classic fallback path.worker/lunora-mcp-store.ts (1)
76-124: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winNo timeout on the Worker→shard
stub.fetchcall.
shardRpcawaitsstub.fetch(...)with noAbortSignal/timeout, so a hung Durable Object shard would hang this call indefinitely (bounded only by whatever platform-level limitslunorash/runtime'sresolveShardor the Workers runtime impose). Every MCP tool operation (getNodes,applyBatch,getKv,getOrCreateKv,wipeUserShard) funnels through this helper.⏱️ Proposed fix: bound the shard RPC with an explicit timeout
const stub = resolveShard(env.SHARD, userId); + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 10_000); const res = await stub.fetch( new Request("https://shard.internal/rpc", { method: "POST", headers: { "content-type": "application/json", "x-lunora-userid": userId, "x-lunora-system": "1", }, body: JSON.stringify({ functionPath, args }), + signal: controller.signal, }), - ); + ).finally(() => clearTimeout(timeout));🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@worker/lunora-mcp-store.ts` around lines 76 - 124, Update shardRpc’s stub.fetch call to use an explicit AbortSignal timeout, ensuring every Worker-to-shard RPC fails within a bounded duration when the Durable Object is unresponsive. Preserve the existing request, response decoding, and error handling behavior for completed requests.e2e/fixtures.ts (1)
1045-1059: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winFail loudly on unrecognized
mutators:*paths.An unmatched mutator path still replies 200 and emits a
wholeOutlinepoke of unchanged rows, so a renamed/typo'd mutator inlunora/mutators.tsyields a green-looking RPC that mutated nothing — the spec then fails somewhere far from the cause (or passes for the wrong reason). Keep the permissive branch for non-mutator paths only.♻️ Suggested change
- } - // Unknown mutators: accept so watermark chain doesn't wedge. + } else if (path.startsWith("mutators:")) { + // Unmodeled mutator: fail loudly instead of acking a no-op write, so a + // rename in `lunora/mutators.ts` surfaces here and not three + // assertions later. + return route.fulfill({ + status: 501, + contentType: "application/json", + body: JSON.stringify({ error: `unmocked mutator: ${path}` }), + }); + } + // Non-mutator paths (queries etc.): accept so the watermark chain + // doesn't wedge.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@e2e/fixtures.ts` around lines 1045 - 1059, Update the unknown-mutator handling in the fixture request path to reject unrecognized `mutators:*` routes instead of replying successfully and emitting a `wholeOutline` poke. Preserve the existing permissive behavior for unknown non-mutator paths, and ensure unmatched mutator requests fail before the success response and poke logic.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 7e5e4945-2d00-4448-8d68-cf35611bd0f2
⛔ Files ignored due to path filters (14)
bun.lockis excluded by!**/*.locklunora/_generated/api.tsis excluded by!**/_generated/**lunora/_generated/app.tsis excluded by!**/_generated/**lunora/_generated/collections.tsis excluded by!**/_generated/**lunora/_generated/crons.tsis excluded by!**/_generated/**lunora/_generated/dataModel.tsis excluded by!**/_generated/**lunora/_generated/drizzle.global.tsis excluded by!**/_generated/**lunora/_generated/drizzle.shard.tsis excluded by!**/_generated/**lunora/_generated/functions.tsis excluded by!**/_generated/**lunora/_generated/openapi.jsonis excluded by!**/_generated/**lunora/_generated/openapi.tsis excluded by!**/_generated/**lunora/_generated/server.tsis excluded by!**/_generated/**lunora/_generated/shard.tsis excluded by!**/_generated/**lunora/_generated/vectors.tsis excluded by!**/_generated/**
📒 Files selected for processing (97)
.changeset/lunora-opt-in-beta.md.changeset/mobile-bar-keyboard-anchor.md.dev.vars.example.oxfmtrc.json.oxlintrc.jsonAGENTS.mddocs/adr/0008-sync-via-a-per-user-durable-object.mddocs/adr/0030-mobile-actions-bar.mddocs/adr/0051-self-serve-account-deletion.mddocs/adr/0055-lunora-replaces-custom-outline-sync.mde2e/atomic-structural-writes.spec.tse2e/changelog.spec.tse2e/daily-notes.spec.tse2e/delete-confirm.spec.tse2e/drag-filtered.spec.tse2e/fixtures.tse2e/lunora-optimistic-hold.spec.tse2e/lunora-save-failure.spec.tse2e/lunora-structural.spec.tse2e/lunora-sync-smoke.spec.tse2e/lunora-undo.spec.tse2e/opml-import.spec.tse2e/save-failure.spec.tse2e/sibling-chain-repair.spec.tse2e/update-available.spec.tslunora/.lunora-schema.jsonlunora/mcp.tslunora/mutators.tslunora/ratelimit/schema.tslunora/schema.tslunora/shapes.tspackage.jsonscripts/comp-dev-plan.tsscripts/mint-mcp-token.tsscripts/react-jsx-dev-runtime-shim.tssrc/components/MobileActionsBar.tsxsrc/components/OutlineEditor.tsxsrc/components/OutlineRow.tsxsrc/components/delete-confirm-dialog.tsxsrc/components/header-more-menu.tsxsrc/components/history-restore.tsxsrc/components/lunora-sync-host.tsxsrc/components/markdown-paste.tssrc/components/node-switcher.tsxsrc/components/opml-import-dialog.tsxsrc/components/quick-add.tsxsrc/components/use-bullet-keymap.tssrc/data/account-prefs.tssrc/data/collection.tssrc/data/flags.test.tssrc/data/flags.tssrc/data/focus-key.tssrc/data/history.tssrc/data/keyboard-inset.tssrc/data/live-nodes.tssrc/data/lunora-bridge.test.tssrc/data/lunora-bridge.tssrc/data/lunora-checkpoints.test.tssrc/data/lunora-checkpoints.tssrc/data/lunora-client.tssrc/data/lunora-kv-store.tssrc/data/lunora-migrate.tssrc/data/lunora-outline-store.tssrc/data/lunora-sync.tssrc/data/mutations.tssrc/data/node-count.tssrc/data/outline-plans/change-ops.test.tssrc/data/outline-plans/change-ops.tssrc/data/outline-plans/index.tssrc/data/outline-plans/map-node.tssrc/data/outline-plans/planners.test.tssrc/data/outline-plans/planners.tssrc/data/outline-plans/seed.test.tssrc/data/outline-plans/seed.tssrc/data/outline-plans/types.tssrc/data/saved-queries.tssrc/data/seed.tssrc/data/selection-state.tssrc/data/structural.tssrc/data/tag-colors.tssrc/data/tree-store.tssrc/hooks/use-keyboard-viewport.tssrc/plugins/daily/claim-mapping.test.tssrc/plugins/daily/claim-mapping.tssrc/plugins/daily/daily-index.tssrc/plugins/daily/get-or-create.tssrc/routes/__root.tsxsrc/routes/settings.tsxsrc/styles.cssvite.config.tsworker/auth.tsworker/index.tsworker/lunora-app.tsworker/lunora-mcp-bridge.test.tsworker/lunora-mcp-store.test.tsworker/lunora-mcp-store.tswrangler.jsonc
💤 Files with no reviewable changes (1)
- src/hooks/use-keyboard-viewport.ts
| // Drop prior Lunora mocks from earlier tests on this page — stacked | ||
| // `routeWebSocket` handlers can keep an old in-memory store alive across | ||
| // reload (delete "persists" then resurrects from the stale mock). | ||
| await page.unroute("**/_lunora/**"); | ||
| await page.unroute("**/api/auth/get-session"); | ||
| await page.unroute("**/api/nodes"); | ||
| await page.unroute("**/api/kv"); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Confirm the unroute matchers used vs. the matchers the routes were registered with,
# and check whether any spec seeds the same page twice (WS handlers can't be unrouted).
rg -nP -C2 '\bpage\.(unroute|unrouteAll)\b' e2e
rg -nP -C1 'page\.(route|routeWebSocket)\(\s*\(url\)' e2e/fixtures.ts
rg -nP -c 'seedOutlineLunora\(|seedOutline\(' e2e
# Verify the installed Playwright version exposes page.unrouteAll
fd -t f 'package.json' -d 2 --exec sh -c 'jq -r ".devDependencies[\"`@playwright/test`\"] // empty" {}'Repository: cameronapak/dotflowy
Length of output: 2389
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "## e2e/fixtures seedOutlineLunora outline"
ast-grep outline e2e/fixtures.ts --view expanded | sed -n '1,240p'
echo "## relevant e2e/fixtures.ts route sections"
cat -n e2e/fixtures.ts | sed -n '400,620p'
echo "## route and routeWebSocket registrations with URL predicates"
rg -n -C2 'page\.(route|routeWebSocket)\(' e2e/fixtures.ts
echo "## unroute usage across e2e"
rg -n -C3 'page\.(unroute|unrouteAll)\(' e2e
echo "## duplicate seed calls per file"
python3 - <<'PY'
from pathlib import Path
for p in sorted(Path("e2e").glob("*.ts")):
text=p.read_text()
seeds=text.count("seedOutline("), text.count("seedOutlineLunora(")
if sum(seeds):
print(f"{p}: seedOutline={seeds[0]} seedOutlineLunora={seeds[1]}")
PYRepository: cameronapak/dotflowy
Length of output: 16044
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "## full Lunora route registrations"
cat -n e2e/fixtures.ts | sed -n '580,1095p'
echo "## read-only behavioral probe of matcher identity semantics"
node - <<'JS'
function route(urlMatcher) { return { urlMatcher }; }
const routes = [
route((url) => url.pathname === "/api/nodes"),
route((url) => url.pathname === "/_lunora/rpc"),
route("**/api/nodes"),
route("**/_lunora/rpc"),
];
function unrouteExact(pattern) {
return routes.filter((entry) => entry !== pattern).length;
}
for (const p of ["**/api/nodes", "**/_lunora/rpc", (url) => url.pathname === "/api/nodes"]) {
routes.push(route(p));
}
console.log(JSON.stringify({ remainingRoutesAfterUnrouteGlob: unrouteExact("**/api/nodes") }));
console.log(JSON.stringify({ remainingRoutesAfterUnrouteExactFunction: unrouteExact((url) => url.pathname === "/api/nodes") }));
console.log(JSON.stringify({ unrouteAllBehavior: `${routes.length} total routes would be removed` }));
JSRepository: cameronapak/dotflowy
Length of output: 21146
Clear all previous route-backed mocks before re-seeding
These entries register predicate matchers ((url) => url.pathname === ...), while the teardown uses literal route patterns, so those registered handlers remain attached to the page and can resurrect a stale Lunora store on the next seed. page.routeWebSocket and addInitScript cannot be unrouted, so re-seeding the same page is still unsafe. Use unrouteAll({ behavior: "ignoreErrors" }) and document that one seedOutlineLunora must be used per page.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@e2e/fixtures.ts` around lines 546 - 552, Update seedOutlineLunora teardown to
call page.unrouteAll({ behavior: "ignoreErrors" }) instead of the individual
literal-pattern unroute calls, ensuring predicate-based route mocks are removed
before reseeding. Document the limitation that page.routeWebSocket and
addInitScript cannot be removed and require one seedOutlineLunora invocation per
page.
| function assertOwner(ctx: MutatorCtx, userId: string): void { | ||
| if (ctx.auth.userId !== userId) { | ||
| throw new Error("unauthorized: shard userId mismatch"); | ||
| } | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# How does the Worker invoke these internal endpoints, and what auth ctx does it pass?
rg -n -C8 'x-lunora-system' worker lunora src
rg -n -C6 'listNodes|listDailyIndex|applyChangeOps|wipeUserShard' workerRepository: cameronapak/dotflowy
Length of output: 7377
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf 'Files:\n'
git ls-files | rg '^lunora/|worker/|src/' | head -200
printf '\nlunora/mcp.ts excerpt:\n'
sed -n '1,260p' lunora/mcp.ts
printf '\nworker/lunora-mcp-store.ts excerpt:\n'
sed -n '1,120p;130,245p' worker/lunora-mcp-store.ts
printf '\nSearch for auth/ctx building in relevant files:\n'
rg -n -C5 'auth|ctx|userId|x-lunora|internalMutation|MutatorCtx|system' lunora worker src -g '*.ts' -g '*.tsx'Repository: cameronapak/dotflowy
Length of output: 50377
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf 'lunora/mcp.ts lines 1-220:\n'
sed -n '1,220p' lunora/mcp.ts
printf '\nworker/lunora-mcp-store.ts lines 1-110 and 230-245:\n'
sed -n '1,110p' worker/lunora-mcp-store.ts
sed -n '230,245p' worker/lunora-mcp-store.ts
printf '\nFind mutateCtx / auth user mapping:\n'
rg -n -C6 'mutateCtx|create.*Ctx|auth\.userId|clientSeq|x-lunora-system|x-lunora-userid|internalMutation' . -g '*.ts' -g '*.tsx' \
| rg -n -C5 'mutateCtx|auth\.userId|clientSeq|x-lunora-system|x-lunora-userid|internalMutation' \
| head -400Repository: cameronapak/dotflowy
Length of output: 22752
Gate these MCP RPC entries on the system header, not ctx.auth.userId.
worker/lunora-mcp-store.ts only sends x-lunora-userid + x-lunora-system; if ctx.auth is absent here, assertOwner() rejects every endpoint, including wipeUserShard. Either populate auth.userId for x-lunora-system requests in shard auth handling, or replace assertOwner with a shared header-based check for these internal calls.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@lunora/mcp.ts` around lines 64 - 68, Update assertOwner and the MCP RPC
authorization flow so x-lunora-system requests are validated using the
x-lunora-userid system header rather than requiring ctx.auth.userId. Reuse the
existing shard authentication/header-checking mechanism if available, and ensure
all affected endpoints, including wipeUserShard, accept valid internal requests
while still rejecting mismatched user IDs.
| const WIPE_TABLES: ShardTable[] = [ | ||
| "nodes", | ||
| "tagColors", | ||
| "savedQueries", | ||
| "dailyIndex", | ||
| "ratelimit_buckets", | ||
| ]; |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Is the ratelimit bucket table shard-scoped, and what is its physical name?
rg -n -C6 'ratelimit_buckets|externallyManaged|defineSchemaExtension' lunora
fd -t f . lunora/_generated --exec rg -n 'ratelimit|buckets' {} \;Repository: cameronapak/dotflowy
Length of output: 16146
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the shard wrapper behavior for string queries and the wipe function around WIPE_TABLES.
sed -n '30,240p' lunora/mcp.ts
# Search for query routing / shardBy behavior and bindTableFacade implementation.
rg -n -C4 'shardBy|bindTableFacade|query\\(|query:|userId|externallyManaged|get rid of|wipe|WIPE_TABLES|delete.*rate|ratelimit' .
# Read generated shard facade bindings without executing repository code.
sed -n '780,870p' lunora/_generated/shard.ts
sed -n '1,90p' lunora/_generated/drizzle.shard.tsRepository: cameronapak/dotflowy
Length of output: 5015
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Search for shard/table binding behavior without malformed regex.
rg -n -C4 'shardBy|bindTableFacade|query\(|query:|userId|externallyManaged|get rid of|wipe|WIPE_TABLES|ratelimit' .
# Read generated shard facade bindings without executing repository code.
sed -n '780,870p' lunora/_generated/shard.ts
sed -n '1,90p' lunora/_generated/drizzle.shard.tsRepository: cameronapak/dotflowy
Length of output: 50377
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Find exact definitions of bindTableFacade and shardBy without broad output.
rg -n -C5 'function bindTableFacade|const bindTableFacade|exports\.bindTableFacade|export.*bindTableFacade|shardBy\(' .
rg -n -C5 'shardBy<|shardBy\(' node_modules/@lunora 2>/dev/null || true
# Read focused generated snippets.
sed -n '700,870p' lunora/_generated/shard.ts
sed -n '1,90p' lunora/_generated/drizzle.shard.ts
# Deterministic source-shape check for whether ratelimit_buckets has user-scoped fields/key behavior.
python3 - <<'PY'
from pathlib import Path
import json
files = {
"schema": Path("lunora/ratelimit/schema.ts").read_text(),
"dataModel": Path("lunora/_generated/dataModel.ts").read_text(),
"shard": Path("lunora/_generated/shard.ts").read_text(),
}
checks = {
"schema_has_table_buckets_key_value_ts_prev": 'key: v.string()' in files["schema"] and 'value: v.number()' in files["schema"] and '.internallyManaged()' not in files["schema"] and '.externallyManaged()' in files["schema"],
"data_model_ratelimit_has_no_user_field": 'interface Doc_ratelimit_buckets' in files["dataModel"] and 'userId: string;' in files["dataModel"].split('interface Doc_ratelimit_buckets', 1)[1].split('}', 1)[0],
"shard_ratelimit_buckets_facade_line": '"ratelimit_buckets"' in files["shard"] and 'bindTableFacade(db, "ratelimit_buckets")' in files["shard"],
}
print(json.dumps(checks, indent=2))
PYRepository: cameronapak/dotflowy
Length of output: 16507
🌐 Web query:
@lunora/db bindTableFacade query collect shardBy internallyManaged externallyManaged global table
💡 Result:
The @lunora/db package acts as a binding between Lunora queries and the TanStack DB data layer, providing typed, live-synced collections and a durable offline outbox [1][2]. Based on the available documentation and codebase references, there is no direct public API or internal configuration method specifically named bindTableFacade, shardBy, internallyManaged, externallyManaged, or global table within the @lunora/db package [3][4][2]. The architecture of @lunora/db primarily relies on defining collections using lunoraCollectionOptions to sync shapes into TanStack DB [5]. Key features include: 1. Collections: These provide a normalized, keyed store with incremental live queries via useLiveQuery, supporting lazy and eager loading strategies [3][2]. 2. Mutations: The package uses bindMutators for optimistic transactions, utilizing a watermarked, server-pushed protocol to ensure consistency [5]. 3. Data Scope: Loading strategies are managed via scopeBy (e.g., db.scope.x(args)) to allow for lazy, partial loading at the collection or scope level [3]. If you encountered these terms (bindTableFacade, shardBy, etc.) in specific project code or internal discussions, they may represent custom abstractions, deprecated experimental features, or internal implementation details not exposed in the standard @lunora/db public API [4][5]. It is recommended to check the specific version of the package in your project or consult the project's internal RFCs if they are part of a private or non-standard implementation [3][6].
Citations:
- 1: https://github.com/anolilab/lunora/blob/alpha/README.md
- 2: https://lunora.sh/docs/packages/db/
- 3: Client read architecture: normalized object pool + partial-bootstrap load strategies (Linear-style) anolilab/lunora#76
- 4: feat: land stable-1.0 roadmap and execute phases 0-4 anolilab/lunora#145
- 5: https://lunora.sh/docs/concepts/local-first
- 6: Optimistic mutations: opt-in serialized ordered queue (Linear-style) vs current concurrent cursor-gating anolilab/lunora#75
🌐 Web query:
site:lunora.sh schema.ts shardBy globallyManaged manuallyManage delete
💡 Result:
The available information indicates that the Lunora framework utilizes a schema.ts file to define database tables, which supports the.shardBy method to specify sharding keys for data distribution, such as shardBy('roomId') [1]. However, there is no documented information in the provided sources regarding globallyManaged, manuallyManage, or specific delete configurations within this context [1].
Citations:
🌐 Web query:
site:lunora.sh externallyManaged "shardBy" Lunora
💡 Result:
In the Lunora framework, the shardBy method is used within schema definitions to determine how data is sharded across SQLite-backed Durable Objects [1]. An example of this configuration in a schema file is shown below [1]: export const messages = defineTable({ roomId: v.string, body: v.string, }).shardBy('roomId'); There is no information in the available documentation regarding an externallyManaged property in conjunction with the shardBy method in Lunora.
Citations:
🌐 Web query:
GitHub anolilab lunora externallyManaged shardBy bindTableFacade
💡 Result:
Lunora is a type-safe, real-time backend framework developed by Anolilab that allows developers to build applications on their own Cloudflare accounts using services like Workers, Durable Objects, D1, R2, and Queues [1][2]. The framework is designed to provide a Convex-like developer experience (DX) while remaining "Vite-first" [1]. Regarding the specific identifiers and methods mentioned: externallyManaged In the context of Lunora, this appears to be a configuration property or state flag related to infrastructure or tenant management within its Cloudflare-based architecture (e.g., within the Lunora Cloud control plane or resource provisioning) [3]. shardBy The shardBy(key) method is a core API feature used for scaling applications beyond the limits of a single Durable Object (DO) [4]. By calling.shardBy(key) on a function, developers can opt into tenant-level isolation, causing the Lunora runtime to route requests to a specific Durable Object instance identified by that key [4]. bindTableFacade While not explicitly detailed in the top-level README, this identifier likely refers to an internal method or pattern used within the Lunora runtime or D1 adapter packages to map or bind specific database table interfaces (facades) to the application context, ensuring type-safe interaction with the underlying D1 SQL database [1]. The framework is currently in an alpha development stage, as indicated by its repository and security documentation [5]. Its architecture heavily relies on TypeScript for end-to-end type safety, leveraging code generation to keep server and client implementations in sync [1][2]. Recent development has focused on building out a cloud control plane (Lunora Cloud) and a robust observability suite covering traces, metrics, logs, and incidents [6][3].
Citations:
- 1: https://github.com/anolilab/lunora
- 2: https://lunora.sh/
- 3: feat(cloud): lunora cloud control plane on workers for platforms anolilab/lunora#85
- 4: https://github.com/anolilab/lunora/blob/alpha/README.md
- 5: https://github.com/anolilab/lunora/blob/alpha/SECURITY.md
- 6: feat(cloud): observability suite — traces, metrics, logs, issues, alerts, sessions, dashboards anolilab/lunora#179
🌐 Web query:
"ratelimit_buckets" "shardBy" "createDbStore"
💡 Result:
The terms you provided do not refer to a single, unified technical concept, but rather appear to be disparate terms from different software systems and documentation contexts: 1. ratelimit_buckets: This typically refers to the data structures used to track and enforce rate limits [1][2][3]. For instance, in the Coturn project, ratelimit_buckets is a fixed-size table of structures used to track request counts per IP address [2][3]. Similarly, in Rspamd, ratelimit_buckets are used to store and manage rate-limiting state [1]. 2. shardBy: This is a mechanism used to distribute load across multiple components or storage nodes [4][5][6]. In rate-limiting contexts (such as the Convex rate-limiter), "sharding" breaks a single large rate limit into smaller, independent "shards" or buckets to allow for higher throughput without sacrificing accuracy [4][6]. In cloud logging, ShardBy is an enum for different diversion or sharding mechanisms [5]. 3. createDbStore: This is a common factory pattern or function name used in various libraries to initialize a database-backed store [7][8]. For example, in the SolidJS community's solid-primitives library, createDbStore is a primitive that creates a store synchronized with a database [7][9][10]. In other systems, such as SwimOS, createDbStore is used to instantiate a database-backed storage component [8]. In summary, there is no single API or framework that combines all three specific terms; they are distinct technical concepts from different domains.
Citations:
- 1: rspamd/rspamd@10212c1
- 2: https://github.com/coturn/coturn/blob/66833df4/docs/401-ratelimit.md
- 3: https://github.com/coturn/coturn/blob/66833df4/src/server/ns_turn_ratelimit.c
- 4: https://mintlify.wiki/get-convex/rate-limiter/advanced/sharding
- 5: https://flambogamers.netlify.app/host-https-docs.cloud.google.com/logging/docs/reference/audit/appengine/rest/Shared.Types/ShardBy
- 6: https://github.com/get-convex/ratelimiter
- 7: https://github.com/solidjs-community/solid-primitives/tree/main/packages/db-store
- 8: https://docs.swimos.org/java/latest/swim.store.db/swim/store/db/DbStoreKernel.html
- 9: https://primitives.solidjs.community/package/db-store
- 10: https://registry.npmjs.org/%40solid-primitives%2Fdb-store
Exclude ratelimit_buckets from the user-shard wipe.
ratelimit_buckets is an externally managed rate-limit store with only key/value/ts/prev and no userId or .shardBy("userId"), unlike the other wiped tables. mctx.db.query(table) for a user shard can hit the shared bucket table, so account deletion would clear other users’ rate-limit state; rate counters are also not ADR 0051 user content to erase.
🛡️ Proposed fix: drop the shared bucket table from the per-user wipe
const WIPE_TABLES: ShardTable[] = [
"nodes",
"tagColors",
"savedQueries",
"dailyIndex",
- "ratelimit_buckets",
];📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const WIPE_TABLES: ShardTable[] = [ | |
| "nodes", | |
| "tagColors", | |
| "savedQueries", | |
| "dailyIndex", | |
| "ratelimit_buckets", | |
| ]; | |
| const WIPE_TABLES: ShardTable[] = [ | |
| "nodes", | |
| "tagColors", | |
| "savedQueries", | |
| "dailyIndex", | |
| ]; |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@lunora/mcp.ts` around lines 162 - 168, Remove "ratelimit_buckets" from the
WIPE_TABLES array so user-shard deletion only wipes user-scoped tables. Preserve
the remaining table entries and the existing wipe flow.
| let deleted = 0; | ||
| for (const table of WIPE_TABLES) { | ||
| const rows = await mctx.db.query(table).collect(); | ||
| for (const row of rows) { | ||
| await mctx.db.delete(row._id as Id<ShardTable>); | ||
| deleted += 1; | ||
| } | ||
| } |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift
Unbounded collect-then-delete in a single mutation.
Every row of every table is loaded and deleted one at a time inside one transaction. For a large outline this risks blowing the Durable Object transaction/CPU budget, and a failure part-way leaves a partially deleted account with no resume point. Consider a bounded page size per call plus a { deleted, done } result the Worker can loop on.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@lunora/mcp.ts` around lines 180 - 187, Replace the unbounded
collect-and-delete flow around WIPE_TABLES with bounded page processing per
mutation, returning a { deleted, done } result that indicates progress and
whether all tables are cleared. Update the Worker caller to repeatedly invoke
the mutation until done, preserving progress across calls so large accounts do
not exceed transaction or CPU limits.
| export const setText = defineMutator({ | ||
| args: { id: idArg, userId: userIdArg, text: v.string(), updatedAt: tsArg }, | ||
| server: async (ctx, args) => { | ||
| const mctx = ctx as unknown as MutatorCtx; | ||
| assertOwner(mctx, args.userId); | ||
| const index = buildTreeIndex(await loadNodes(mctx)); | ||
| const plan = planSetText(index, args.id, args.text, args.updatedAt); | ||
| if (!plan) throw new Error("setText: missing node"); | ||
| await commitPlan(mctx, plan); | ||
| }, | ||
| }); |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift
Field-only mutators load and index the entire shard on every edit.
planSetText only needs index.byId.has(nodeId) (planners.ts L296), yet this path does a full nodes collect, maps every row through docToNode, and builds a complete tree index. The same pattern repeats in setCompleted (L393-405), setCollapsed (L415-427), setIsTask (L437-444), setKind (L454-461) and setBookmarkedAt (L471-483) — i.e. on every keystroke batch and checkbox/collapse toggle, O(outline) work per mutation. A ctx.db.get(id) existence check (or a has-only planner overload) keeps these O(1).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@lunora/mutators.ts` around lines 374 - 384, The field-only mutators setText,
setCompleted, setCollapsed, setIsTask, setKind, and setBookmarkedAt should stop
loading all nodes and building a full tree index for existence validation.
Replace the loadNodes/buildTreeIndex/field-planner flow with an O(1)
ctx.db.get(args.id) existence check, or add and use a planner overload that only
performs index.byId.has(nodeId), while preserving the existing missing-node
error and commit behavior.
| // Lunora dogfood: no large-batch wire path yet — apply slices locally via | ||
| // mutator-backed mutations (same as runStructuralTracked when flag ON). | ||
| if (isLunoraSyncEnabled()) { | ||
| for (const slice of slices) { | ||
| slice(); | ||
| onProgress?.(); | ||
| await new Promise((resolve) => setTimeout(resolve, 0)); | ||
| } | ||
| return; | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Flag-ON sliced path has no rollback, so a throwing slice leaves a half-applied outline.
The classic path below wraps slices in a transaction and calls tx.rollback() on failure; the Lunora branch applies each slice directly and lets the throw escape with earlier slices already committed. runDailyMigration (src/plugins/daily/get-or-create.ts Line 570) reaches this path and swallows the rejection in ensureDailyMigrated, so a mid-migration failure surfaces as a silently half-organized tree with the undo point already captured.
At least document the non-atomic contract here and make the reachable callers explicit about their recovery (drop the undo point / re-run), rather than inheriting the classic path's rollback expectations.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/data/structural.ts` around lines 168 - 177, The Lunora branch in the
sliced mutation flow applies slices non-atomically, allowing failures to leave
partial changes while callers may assume rollback. Document this contract at the
Lunora path and update reachable callers, including runDailyMigration and
ensureDailyMigrated, to explicitly handle failed migrations by dropping the
captured undo point and supporting a re-run recovery instead of silently
swallowing the rejection.
| type TagColorRowDocLike = { _id: string; tag?: unknown; color?: unknown }; | ||
|
|
There was a problem hiding this comment.
🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win
Duplicate type TagColorRowDocLike declaration.
The same type TagColorRowDocLike = { _id: string; tag?: unknown; color?: unknown }; alias appears four times in a row at this location. Redeclaring a type alias with the same name in the same scope is a TypeScript duplicate-identifier error and will fail typechecking. Please de-duplicate to a single declaration.
🐛 Proposed fix
-type TagColorRowDocLike = { _id: string; tag?: unknown; color?: unknown };
-type TagColorRowDocLike = { _id: string; tag?: unknown; color?: unknown };
-type TagColorRowDocLike = { _id: string; tag?: unknown; color?: unknown };
-type TagColorRowDocLike = { _id: string; tag?: unknown; color?: unknown };
+type TagColorRowDocLike = { _id: string; tag?: unknown; color?: unknown };📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| type TagColorRowDocLike = { _id: string; tag?: unknown; color?: unknown }; | |
| type TagColorRowDocLike = { _id: string; tag?: unknown; color?: unknown }; |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/data/tag-colors.ts` around lines 243 - 244, Remove the repeated
TagColorRowDocLike declarations and retain exactly one type alias in that scope,
preserving its existing _id, tag, and color fields so typechecking succeeds.
| if (seedEntryLine && !hasChildInLiveCollection(dayId)) { | ||
| runStructural(() => appendChild(dayId, null, "")); | ||
| // Lunora: insertChildAtStart is already a watermarked mutator; classic | ||
| // path keeps runStructural + appendChild (last-child when empty = same). | ||
| if (isLunoraSyncEnabled()) { | ||
| insertChildAtStart(getTreeIndex(), dayId, false, ""); | ||
| } else { | ||
| runStructural(() => appendChild(dayId, null, "")); | ||
| } | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
fd -t f 'tree-store.ts' -E '*.test.ts' --exec ast-grep outline {} --items all
echo "=== does the store read getLiveNodes or nodesCollection? ==="
rg -nP -C4 '\b(getLiveNodes|nodesCollection)\b' src/data/tree-store.tsRepository: cameronapak/dotflowy
Length of output: 3976
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== relevant daily get-or-create sections ==="
wc -l src/plugins/daily/get-or-create.ts
sed -n '90,180p' src/plugins/daily/get-or-create.ts | cat -n
sed -n '400,560p' src/plugins/daily/get-or-create.ts | cat -n
sed -n '1,80p' src/plugins/daily/get-or-create.ts | cat -n
echo "=== imports and symbols around tree-store usage ==="
rg -n 'buildTreeIndex|getLiveNodes|getTreeIndex|insertChildAtStart|runStructural|appendChild|hasChildInLiveCollection' src/plugins/daily/get-or-create.ts src/plugins/daily src/data/tree-store.ts
echo "=== tree-store index update paths ==="
sed -n '360,420p' src/data/tree-store.ts || true
sed -n '100,220p' src/data/tree-store.ts || true
sed -n '350,390p' src/data/tree-store.ts || true
echo "=== lunora sync implementation references ==="
rg -n 'resetTreeFromNodes|isLunoraSyncEnabled|nodesCollection|getLiveNodes|buildTreeIndex' src/plugins src/data -g '*.ts'Repository: cameronapak/dotflowy
Length of output: 50376
Build the Lunora seed index from live outline nodes.
In src/plugins/daily/get-or-create.ts, Lines 160-162 use getTreeIndex() for Lunora, but with isLunoraSyncEnabled() the shared tree-store loop never subscribes to nodesCollection; unless Lunora sync has already called resetTreeFromNodes, that index remains EMPTY_INDEX and the seeded entry line is skipped. Use insertChildAtStart(buildTreeIndex(getLiveNodes()), ...) to match the existing live-node reads in this module.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/plugins/daily/get-or-create.ts` around lines 149 - 157, The Lunora seed
insertion currently uses the potentially stale getTreeIndex() result. In the
isLunoraSyncEnabled() branch of the seed-entry flow, build the index from live
outline nodes with buildTreeIndex(getLiveNodes()) and pass it to
insertChildAtStart, preserving the existing arguments and classic appendChild
path.
| action={ | ||
| <Switch | ||
| checked={ready ? enabled : false} | ||
| disabled={!ready} | ||
| onCheckedChange={(checked) => void setLunoraBetaEnabled(checked)} | ||
| aria-label="Upgraded outline sync beta" | ||
| /> | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
The beta opt-in write has no failure contract end to end. writeLunoraBeta propagates a kvPut rejection and the only caller discards it, so an offline toggle produces an unhandled rejection, no toast, and a switch that snaps back with no explanation.
src/routes/settings.tsx#L759-L766: catch the rejection, toast a failure, and add an in-flight guard so two quick taps can't issue two writes plus twohardResetcalls.src/data/account-prefs.ts#L65-L80: either resolve to a success signal instead of rejecting, or document that callers must handle rejection beforemirrorLunoraFlag/hardResetrun.
📍 Affects 2 files
src/routes/settings.tsx#L759-L766(this comment)src/data/account-prefs.ts#L65-L80
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/routes/settings.tsx` around lines 759 - 766, The beta toggle lacks
rejection handling and protection against concurrent writes. In
src/routes/settings.tsx lines 759-766, update the Switch handler around
setLunoraBetaEnabled to catch failures, show the established failure toast, and
add an in-flight guard that prevents duplicate writes and hardReset calls. In
src/data/account-prefs.ts lines 65-80, update writeLunoraBeta so its
success/rejection contract is explicit—either return a success signal or
document and preserve caller-handled rejection before mirrorLunoraFlag and
hardReset execute.
| const classicStub = env.USER_OUTLINE.get( | ||
| env.USER_OUTLINE.idFromName(resolveUserId(token.userId, env)), | ||
| ); | ||
| const useLunora = yield* Effect.promise(() => | ||
| isLunoraOutlineEnabledForUser(env, () => | ||
| classicStub.getKv("account-prefs"), | ||
| ), | ||
| ); | ||
| const mcpStore = useLunora | ||
| ? createLunoraOutlineStore(env, token.userId) | ||
| : classicStub; | ||
| return yield* handleMcp(request, mcpStore, origin, mcpPlan !== "free"); |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Inspect the Lunora env-force / account-prefs default semantics.
fd -t f 'lunora-mcp-store.ts' -x cat -n {}Repository: cameronapak/dotflowy
Length of output: 9142
🏁 Script executed:
#!/bin/bash
# Inspect the Worker MCP routing path and whether the classic DO preference lookup is protected.
sed -n '60,120p;950,1015p' worker/index.tsRepository: cameronapak/dotflowy
Length of output: 6152
Eliminate or protect the classic DO preference lookup on the MCP hot path.
With LUNORA_OUTLINE unset, isLunoraOutlineEnabledForUser unconditionally awaits classicStub.getKv("account-prefs"); any DO failure aborts /mcp before the Lunora store is selected. Cache the fallback for a bounded TTL, or default to classic until the preference can be read reliably.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@worker/index.ts` around lines 989 - 1000, The MCP path around
isLunoraOutlineEnabledForUser must not fail solely because the classic DO
preference lookup fails. Protect or eliminate the unconditional
classicStub.getKv("account-prefs") dependency by using a bounded-TTL cached
preference, or defaulting to the classicStub until the preference is read
reliably, while preserving Lunora selection when the preference lookup succeeds.
PR #311 branched off #310 by accident, so its CodeRabbit pass reviewed the Lunora diff as well. Verified each finding against the code; these are the ones that held up. - lunora/mcp.ts: drop ratelimit_buckets from the per-user wipe. It's the .externallyManaged() extension table (no userId, no shardBy), so it isn't user content under ADR 0051 and a per-user wipe has no business there. - change-ops.ts: coalesce ops per key. The plan's buckets apply deletes -> patches -> inserts, which doesn't preserve stream order, so `insert n1` + `update n1` dropped the update and `insert n1` + `delete n1` left the node alive. Tests now assert the APPLIED result, which is the only place a mis-bucketed op shows up. - history-restore.tsx: revert the undo/redo stack when a small Lunora restore fails. This is the common path; only the large one had a revert. - opml-import-dialog.tsx: keep the undo point when chunks already landed — drop() was deleting the escape hatch its own error copy pointed at. - markdown-paste.ts: report a failed paste instead of silently burning the undo point and moving the caret; take the resolved context as a param rather than re-reading it into a second failure mode. - settings.tsx / account-prefs.ts: give the beta toggle a failure contract (catch + toast + in-flight guard); document that the write rejects. - lunora-checkpoints.ts: cap the watermark poll so a mutation whose ack never lands releases its overlay instead of pinning a timer chain for the tab. - lunora-mcp-store.ts: fail the /mcp preference read closed to classic — a DO hiccup was aborting the request before a store was even chosen. - e2e/fixtures.ts: unrouteAll in the Lunora seed. Routes register with predicate matchers, so the per-glob unroute silently removed nothing. Not changed, with reasons: the tag-colors "duplicate type alias" doesn't exist (one declaration, typecheck clean); daily get-or-create's index is fed by lunora-sync's resetTreeFromNodes, not EMPTY_INDEX; and mcp.ts assertOwner does pass for system RPC (x-lunora-userid -> ctx.auth.userId). The remaining heavy lifts — whole-outline restoreNodes payload on paste, runStructural atomicity under the flag, unbounded shard wipe, O(outline) field mutators — are noted in comments and left for the Lunora alpha to work through. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
PR #311 branched off #310 by accident, so its CodeRabbit pass reviewed the Lunora diff as well. Verified each finding against the code; these are the ones that held up. - lunora/mcp.ts: drop ratelimit_buckets from the per-user wipe. It's the .externallyManaged() extension table (no userId, no shardBy), so it isn't user content under ADR 0051 and a per-user wipe has no business there. - change-ops.ts: coalesce ops per key. The plan's buckets apply deletes -> patches -> inserts, which doesn't preserve stream order, so `insert n1` + `update n1` dropped the update and `insert n1` + `delete n1` left the node alive. Tests now assert the APPLIED result, which is the only place a mis-bucketed op shows up. - history-restore.tsx: revert the undo/redo stack when a small Lunora restore fails. This is the common path; only the large one had a revert. - opml-import-dialog.tsx: keep the undo point when chunks already landed — drop() was deleting the escape hatch its own error copy pointed at. - markdown-paste.ts: report a failed paste instead of silently burning the undo point and moving the caret; take the resolved context as a param rather than re-reading it into a second failure mode. - settings.tsx / account-prefs.ts: give the beta toggle a failure contract (catch + toast + in-flight guard); document that the write rejects. - lunora-checkpoints.ts: cap the watermark poll so a mutation whose ack never lands releases its overlay instead of pinning a timer chain for the tab. - lunora-mcp-store.ts: fail the /mcp preference read closed to classic — a DO hiccup was aborting the request before a store was even chosen. - e2e/fixtures.ts: unrouteAll in the Lunora seed. Routes register with predicate matchers, so the per-glob unroute silently removed nothing. Not changed, with reasons: the tag-colors "duplicate type alias" doesn't exist (one declaration, typecheck clean); daily get-or-create's index is fed by lunora-sync's resetTreeFromNodes, not EMPTY_INDEX; and mcp.ts assertOwner does pass for system RPC (x-lunora-userid -> ctx.auth.userId). The remaining heavy lifts — whole-outline restoreNodes payload on paste, runStructural atomicity under the flag, unbounded shard wipe, O(outline) field mutators — are noted in comments and left for the Lunora alpha to work through. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
Closing at Cam’s request after reviewing this work for the mobile wrapped-text scrolling bug. The useful keyboard-geometry findings are carried into the current investigation: use the visible keyboard band, account for the toolbar, and do not assume fixed-position chrome and viewport measurements settle together. The wrapping failure reproduces in Chromium and WebKit because ordinary outline input has no ongoing caret reveal; the existing reveal is a one-time Day stream handoff. This PR addresses a related but distinct toolbar anchor issue, conflicts with current main, and contains unrelated historical sync changes. Its fixed-bottom probe is not being ported wholesale. Closing does not claim the separate toolbar positioning issue has been fixed or that this branch has been merged. Findings and verification continue in https://ampcode.com/threads/T-01a19bfc-4e45-7131-9716-48dd27acfa06 . |
Summary
The mobile actions bar and quick-add panel could sit behind the software keyboard when editing near the bottom of a long page, and could drift up the screen mid-session. They now position against a measured anchor instead of
window.innerHeight, which iOS Safari silently redefines as its own chrome resizes.Changes
position: fixed; bottom: 0probe, measured while a field is focused and published as the--kb-insetcustom property.useKeyboardViewportis deleted.Start here: change 2 — a probe replaces the formula because no viewport property reliably names the box
bottom: 0resolves against.Test plan
typecheck,typecheck:worker,typecheck:test,lint,fmt,bun run test(934 pass)e2e/mobile-actions-bar.spec.tspassesvisualViewport.heightstays self-consistent while Safari's chrome movese2e/quick-add.spec.tshas 13 failures; verified identical on the merge-base (22ba774), so pre-existing rather than from this changeNote
Low Risk
Keyboard positioning is isolated UI/CSS with a deleted hook; the Lunora items in this diff are mostly documentation and env examples, though the changeset implies broader sync behavior shipped elsewhere on the branch.
Overview
Mobile keyboard anchoring (ADR 0030) replaces viewport-based lift with
src/data/keyboard-inset.ts, which measures a zero-sizefixed; bottom: 0probe and writes--kb-inseton<html>while a field is focused (rAF loop, no per-frame React re-renders).MobileActionsBarand quick-add read that variable fortranslateYand subtract it from safe-area padding;useKeyboardViewportis removed. Root imports the module side-effect; AGENTS.md documents “measure the anchor, don’t compute it.”Release/docs (same branch): A minor changeset describes opt-in experimental outline sync in Settings (classic default, cross-device prefs), plus related UX fixes named there;
.dev.vars.exampledocuments optionalLUNORA_OUTLINEfor local dogfood. Agent/workspace notes require Lunora to stay opt-in and off user-facing “Lunora” naming;lunora/_generated/**is added to formatter/linter ignore patterns.Reviewed by Cursor Bugbot for commit 19aeace. Configure here.
Summary by CodeRabbit