From 494602bd682d17dde4d93bb1dc4e78dbff6d2f6c Mon Sep 17 00:00:00 2001 From: Colin Devroe Date: Thu, 3 Dec 2026 14:24:30 -0500 Subject: [PATCH] 1.7.9: Speed and reliability improvements across desktop, MCP, and CLI --- .github/workflows/maintenance-tests.yml | 3 +- AGENTS.md | 6 + CODEX.md | 6 + app/appSettings.js | 16 +- app/board/archiveBrowser.js | 59 ++- app/board/boardLabels.js | 69 ++- app/board/boardTabs.js | 2 +- app/board/plannerView.js | 30 +- app/board/renderBoard.js | 36 +- app/cards/createCardElement.js | 12 - app/init.js | 93 ++-- app/modals/closeAllModals.js | 10 +- app/modals/toggleEditCardModal.js | 93 +++- app/ui/theme.js | 8 + app/ui/tooltips.js | 56 +-- app/utilities/accessibility.js | 15 + app/utilities/dueNotifications.js | 121 +++-- bin/signboard-mcp.js | 42 +- config/build-info.json | 12 +- docs/codex/FILE_STRUCTURE.md | 4 + docs/codex/PROJECT_CONTEXT.md | 4 + index.html | 2 +- lib/allowedPaths.js | 68 ++- lib/appSettings.js | 126 +++--- lib/archive.js | 184 +++++--- lib/atomicFile.js | 58 ++- lib/boardDiscovery.js | 165 ++++--- lib/boardDuplication.js | 63 ++- lib/boardLabels.js | 134 +++--- lib/boardSnapshot.js | 4 +- lib/cardFrontmatter.js | 57 ++- lib/cardOrdering.js | 115 ++--- lib/cardTimestamps.js | 3 +- lib/cliApp.js | 68 ++- lib/cliBoard.js | 530 +++++++++++++--------- lib/cliInstall.js | 33 +- lib/cliState.js | 28 +- lib/directoryRename.js | 27 +- lib/externalPublishedCalendar.js | 53 ++- lib/fileReadQueue.js | 21 +- lib/fileTransaction.js | 61 ++- lib/importers/obsidian.js | 15 +- lib/importers/shared.js | 17 +- lib/importers/tasksmd.js | 4 +- lib/linuxPackageInstaller.js | 74 ++- lib/listOrderRecovery.js | 16 +- lib/mcpLaunch.js | 6 +- lib/mcpServer.js | 428 ++++++++++++++---- lib/obsidianIntegration.js | 19 +- main.js | 574 +++++++++++++++++------- package-lock.json | 4 +- package.json | 5 +- preload.js | 43 +- scripts/test-speed-reliability.js | 419 +++++++++++++++++ 54 files changed, 2984 insertions(+), 1137 deletions(-) create mode 100644 scripts/test-speed-reliability.js diff --git a/.github/workflows/maintenance-tests.yml b/.github/workflows/maintenance-tests.yml index 908d506..b263d1d 100644 --- a/.github/workflows/maintenance-tests.yml +++ b/.github/workflows/maintenance-tests.yml @@ -41,6 +41,7 @@ jobs: npm run test:editor-paths npm run test:board-refresh npm run test:board-card-metadata + npm run test:speed-reliability - name: Prepare isolated Electron desktop run: | sudo apt-get -o Acquire::Retries=1 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update @@ -102,7 +103,7 @@ jobs: shell: bash run: | failed=0 - for suite in maintenance mcp automation-parity desktop-cli card-ordering board-snapshot board-duplication archive obsidian-integration import-trello import-obsidian import-tasksmd app-settings update-release-notes update-errors packaging-config; do + for suite in maintenance speed-reliability mcp automation-parity desktop-cli card-ordering board-snapshot board-duplication archive obsidian-integration import-trello import-obsidian import-tasksmd app-settings update-release-notes update-errors packaging-config; do npm run "test:$suite" || failed=1 done exit "$failed" diff --git a/AGENTS.md b/AGENTS.md index 83c3280..07bf6b3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -122,3 +122,9 @@ App settings save responses reconcile against the submitted snapshot: preserve n ## Card move metadata — 1.7.8 `lib/archive.js` records cross-list move activity and normalizes destination Signboard properties in one atomic card write. Desktop drag/drop and move-to-top must not follow it with a second metadata write. Same-list drag reorders leave card contents unchanged. Preserve body/custom fields and the atomic-failure regression in `test:archive`; filtered-drag Electron tests assert both `status` and `signboard_list` before opening the editor. + +## Speed and reliability — 1.7.9 + +- Preload formats short due dates locally with a cache instead of per-card IPC, `waitForNativeMenuTrackingToSettle()` applies the 250ms AppKit settle delay only on macOS, tooltips resolve lazily without a global `document.body` `MutationObserver`, `renderBoard()` reuses `readBoardSnapshot`'s `boardSettings` and skips hidden Settings rebuilds, Archive Browser filters/sorts once per render, and startup skips already-completed app-settings migration while batching due-notification reads. +- Storage and main-process helpers exclude hidden dot-entries (`.git`, `.obsidian`, `._*.md`) from snapshots and ordering, protect `board-settings.md`/`app-settings.json`/card frontmatter against UTF-8 BOMs and parse-error wipes, harden `lib/fileTransaction.js` stale `.reap` recovery and wire locks into settings/frontmatter/CLI/MCP mutations, retry transient Windows `EPERM`/`EACCES`/`EBUSY` renames/unlinks, stop the board watcher before renaming `activeBoardRoot` on Windows, run Arch `pkexec pacman -U` asynchronously, avoid per-card-save Obsidian Base sync and unchanged-card rewrites, and cache/coalesce External Published Calendar feeds with UTF-8 byte-safe ICS folding. +- MCP fixes split-chunk `Content-Length` framing and `stdin` EOF response draining, handles `stdout`/`stderr` `EPIPE`, catches `EACCES`/`EPERM` junction errors in board discovery, pre-resolves canonical `allowedRoots` per call and scopes `assertAllowedTree`, refreshes desktop trusted/open state on mtime change, and preserves Windows paths in card bodies. CLI adds filename/card-ID-first `resolveCard`, lazy-loads heavy subcommands/importers, fixes boolean flag parsing and `--from-card` empty `titlePrefix`, and emits a direct `exec` wrapper on Linux. Keep `npm run test:speed-reliability` aligned. diff --git a/CODEX.md b/CODEX.md index 7f8b9ce..729ade0 100644 --- a/CODEX.md +++ b/CODEX.md @@ -161,3 +161,9 @@ App settings save responses reconcile against the submitted snapshot: preserve n ## Card move metadata — 1.7.8 `lib/archive.js` records cross-list move activity and normalizes destination Signboard properties in one atomic card write. Desktop drag/drop and move-to-top must not follow it with a second metadata write. Same-list drag reorders leave card contents unchanged. Preserve body/custom fields and the atomic-failure regression in `test:archive`; filtered-drag Electron tests assert both `status` and `signboard_list` before opening the editor. + +## Speed and reliability — 1.7.9 + +- Preload formats short due dates locally with a cache instead of per-card IPC, `waitForNativeMenuTrackingToSettle()` applies the 250ms AppKit settle delay only on macOS, tooltips resolve lazily without a global `document.body` `MutationObserver`, `renderBoard()` reuses `readBoardSnapshot`'s `boardSettings` and skips hidden Settings rebuilds, Archive Browser filters/sorts once per render, and startup skips already-completed app-settings migration while batching due-notification reads. +- Storage and main-process helpers exclude hidden dot-entries (`.git`, `.obsidian`, `._*.md`) from snapshots and ordering, protect `board-settings.md`/`app-settings.json`/card frontmatter against UTF-8 BOMs and parse-error wipes, harden `lib/fileTransaction.js` stale `.reap` recovery and wire locks into settings/frontmatter/CLI/MCP mutations, retry transient Windows `EPERM`/`EACCES`/`EBUSY` renames/unlinks, stop the board watcher before renaming `activeBoardRoot` on Windows, run Arch `pkexec pacman -U` asynchronously, avoid per-card-save Obsidian Base sync and unchanged-card rewrites, and cache/coalesce External Published Calendar feeds with UTF-8 byte-safe ICS folding. +- MCP fixes split-chunk `Content-Length` framing and `stdin` EOF response draining, handles `stdout`/`stderr` `EPIPE`, catches `EACCES`/`EPERM` junction errors in board discovery, pre-resolves canonical `allowedRoots` per call and scopes `assertAllowedTree`, refreshes desktop trusted/open state on mtime change, and preserves Windows paths in card bodies. CLI adds filename/card-ID-first `resolveCard`, lazy-loads heavy subcommands/importers, fixes boolean flag parsing and `--from-card` empty `titlePrefix`, and emits a direct `exec` wrapper on Linux. Keep `npm run test:speed-reliability` aligned. diff --git a/app/appSettings.js b/app/appSettings.js index bb4805c..b771327 100644 --- a/app/appSettings.js +++ b/app/appSettings.js @@ -356,12 +356,16 @@ async function loadAppSettings() { } async function migrateAppSettingsFromOpenBoards() { + const loadedSettings = await loadAppSettings(); + if (loadedSettings && loadedSettings.migration && loadedSettings.migration.boardSettingsMigrated) { + return; + } + if ( !window.electronAPI || typeof window.electronAPI.migrateAppSettingsFromBoard !== 'function' || typeof getStoredOpenBoards !== 'function' ) { - await loadAppSettings(); return; } @@ -375,25 +379,23 @@ async function migrateAppSettingsFromOpenBoards() { let migratedSettings = null; for (const boardRoot of openBoards) { const result = await window.electronAPI.migrateAppSettingsFromBoard(boardRoot); - if (!migratedSettings && result && result.settings) { + if (result && result.settings) { migratedSettings = result.settings; + if (result.settings.migration && result.settings.migration.boardSettingsMigrated) { + break; + } } } if (migratedSettings) { applyAppSettings(migratedSettings); renderAppSettingsControls(); - if (getAppAiSettings().enabled) { - refreshAppAiOllamaModels(); - } return; } } catch (error) { console.warn('Unable to migrate app settings from board settings.', error); } } - - await loadAppSettings(); } function renderAppSettingsControls() { diff --git a/app/board/archiveBrowser.js b/app/board/archiveBrowser.js index b4cc845..df4b741 100644 --- a/app/board/archiveBrowser.js +++ b/app/board/archiveBrowser.js @@ -472,10 +472,10 @@ async function clearArchiveBrowserSearchFromKeyboard(searchInput) { state.searchQuery = ''; resetArchiveBrowserPagination(state.activeTab); state.selectedEntryPath = ''; - renderArchiveBrowserModal(); - const selectedPath = syncArchiveBrowserSelection(getFilteredArchiveEntries()); - renderArchiveBrowserModal(); + const filteredEntries = getFilteredArchiveEntries(); + const selectedPath = syncArchiveBrowserSelection(filteredEntries); + renderArchiveBrowserModal(filteredEntries); if (selectedPath) { await loadArchiveBrowserDetail(selectedPath); } @@ -561,7 +561,7 @@ function handleArchiveBrowserResultKeydown(event) { } } -function renderArchiveBrowserResults() { +function renderArchiveBrowserResults(precomputedFilteredEntries) { const state = getArchiveBrowserState(); const resultsEl = document.getElementById('archiveBrowserResults'); const resultCountEl = document.getElementById('archiveBrowserResultCount'); @@ -570,7 +570,9 @@ function renderArchiveBrowserResults() { } const totalEntries = getArchiveEntriesForActiveTab(); - const filteredEntries = getFilteredArchiveEntries(); + const filteredEntries = Array.isArray(precomputedFilteredEntries) + ? precomputedFilteredEntries + : getFilteredArchiveEntries(); syncArchiveBrowserSelection(filteredEntries); const visibleCount = Math.max(ARCHIVE_BROWSER_BATCH_SIZE, state.visibleCountByTab[state.activeTab] || ARCHIVE_BROWSER_BATCH_SIZE); const entriesToRender = filteredEntries.slice(0, visibleCount); @@ -686,14 +688,16 @@ function renderArchiveBrowserResults() { resultCountEl.textContent = getArchiveBrowserResultCountLabel(filteredEntries, totalEntries); } -function renderArchiveBrowserDetail() { +function renderArchiveBrowserDetail(precomputedFilteredEntries) { const state = getArchiveBrowserState(); const detailEl = document.getElementById('archiveBrowserDetail'); if (!detailEl) { return; } - const filteredEntries = getFilteredArchiveEntries(); + const filteredEntries = Array.isArray(precomputedFilteredEntries) + ? precomputedFilteredEntries + : getFilteredArchiveEntries(); const selectedEntry = getSelectedArchiveEntry(filteredEntries); detailEl.innerHTML = ''; @@ -844,7 +848,7 @@ function renderArchiveBrowserDetail() { } } -function renderArchiveRestoreDialog() { +function renderArchiveRestoreDialog(precomputedFilteredEntries) { const state = getArchiveBrowserState(); const dialogEl = document.getElementById('archiveRestoreDialog'); const titleEl = document.getElementById('archiveRestoreTitle'); @@ -857,7 +861,9 @@ function renderArchiveRestoreDialog() { return; } - const filteredEntries = getFilteredArchiveEntries(); + const filteredEntries = Array.isArray(precomputedFilteredEntries) + ? precomputedFilteredEntries + : getFilteredArchiveEntries(); const selectedEntry = getSelectedArchiveEntry(filteredEntries); const restoreEntry = selectedEntry && selectedEntry.entryPath === state.restore.entryPath ? selectedEntry @@ -935,7 +941,7 @@ function renderArchiveRestoreDialog() { confirmButton.textContent = state.restore.isSaving ? 'Restoring...' : 'Restore card'; } -function renderArchiveBrowserModal() { +function renderArchiveBrowserModal(precomputedFilteredEntries) { const state = getArchiveBrowserState(); const modal = getArchiveBrowserModal(); const searchInput = document.getElementById('archiveBrowserSearchInput'); @@ -945,6 +951,10 @@ function renderArchiveBrowserModal() { return; } + const filteredEntries = Array.isArray(precomputedFilteredEntries) + ? precomputedFilteredEntries + : getFilteredArchiveEntries(); + cardsTab.classList.toggle('is-active', state.activeTab === ARCHIVE_BROWSER_TAB_IDS.CARDS); listsTab.classList.toggle('is-active', state.activeTab === ARCHIVE_BROWSER_TAB_IDS.LISTS); cardsTab.setAttribute('aria-selected', state.activeTab === ARCHIVE_BROWSER_TAB_IDS.CARDS ? 'true' : 'false'); @@ -952,9 +962,9 @@ function renderArchiveBrowserModal() { searchInput.value = state.searchQuery; searchInput.placeholder = getArchiveBrowserSearchPlaceholder(); renderArchiveBrowserSortOptions(); - renderArchiveBrowserResults(); - renderArchiveBrowserDetail(); - renderArchiveRestoreDialog(); + renderArchiveBrowserResults(filteredEntries); + renderArchiveBrowserDetail(filteredEntries); + renderArchiveRestoreDialog(filteredEntries); } async function loadArchiveBrowserDetail(entryPath) { @@ -1037,11 +1047,10 @@ async function refreshArchiveBrowserData() { }; state.selectedEntryPath = previousSelectedEntryPath; state.isLoading = false; - renderArchiveBrowserModal(); const filteredEntries = getFilteredArchiveEntries(); const selectedPath = syncArchiveBrowserSelection(filteredEntries); - renderArchiveBrowserModal(); + renderArchiveBrowserModal(filteredEntries); if (selectedPath) { await loadArchiveBrowserDetail(selectedPath); } @@ -1134,12 +1143,19 @@ function openArchiveRestoreDialog(entry) { return Promise.resolve(); } - return window.board.listLists(window.boardRoot).then((listNames) => { + const requestId = state.requestId; + const boardRoot = window.boardRoot; + + return window.board.listLists(boardRoot).then((listNames) => { + if (requestId !== state.requestId || !isArchiveBrowserModalOpen() || window.boardRoot !== boardRoot) { + return; + } + const names = Array.isArray(listNames) ? listNames : []; const availableLists = names.map((directoryName) => ({ directoryName, displayName: getArchiveDisplayNameForList(directoryName), - path: `${window.boardRoot}${directoryName}`, + path: `${boardRoot}${directoryName}`, })).sort((left, right) => left.displayName.localeCompare(right.displayName, undefined, { numeric: true, sensitivity: 'base', @@ -1332,11 +1348,10 @@ function setArchiveBrowserActiveTab(tabId) { : ARCHIVE_BROWSER_TAB_IDS.CARDS; resetArchiveBrowserPagination(state.activeTab); state.selectedEntryPath = ''; - renderArchiveBrowserModal(); const filteredEntries = getFilteredArchiveEntries(); const selectedPath = syncArchiveBrowserSelection(filteredEntries); - renderArchiveBrowserModal(); + renderArchiveBrowserModal(filteredEntries); if (selectedPath) { loadArchiveBrowserDetail(selectedPath).catch((error) => { console.error('Unable to load archive detail.', error); @@ -1414,11 +1429,10 @@ function initializeArchiveBrowserControls() { state.searchQuery = String(event.currentTarget.value || ''); resetArchiveBrowserPagination(state.activeTab); state.selectedEntryPath = ''; - renderArchiveBrowserModal(); const filteredEntries = getFilteredArchiveEntries(); const selectedPath = syncArchiveBrowserSelection(filteredEntries); - renderArchiveBrowserModal(); + renderArchiveBrowserModal(filteredEntries); if (selectedPath) { await loadArchiveBrowserDetail(selectedPath); } @@ -1443,11 +1457,10 @@ function initializeArchiveBrowserControls() { state.sortKeyByTab[state.activeTab] = nextSortKey; resetArchiveBrowserPagination(state.activeTab); state.selectedEntryPath = ''; - renderArchiveBrowserModal(); const filteredEntries = getFilteredArchiveEntries(); const selectedPath = syncArchiveBrowserSelection(filteredEntries); - renderArchiveBrowserModal(); + renderArchiveBrowserModal(filteredEntries); if (selectedPath) { await loadArchiveBrowserDetail(selectedPath); } diff --git a/app/board/boardLabels.js b/app/board/boardLabels.js index 32a2748..8fea3de 100644 --- a/app/board/boardLabels.js +++ b/app/board/boardLabels.js @@ -4300,7 +4300,7 @@ async function runBoardImport(importer) { } const boardInfo = getBoardRootInfo(); - const defaultPath = boardInfo ? boardInfo.parentRoot.replace(/\/+$/, '') : undefined; + const defaultPath = boardInfo ? formatBoardPickerParentPath(boardInfo.parentRoot) : undefined; await flushBoardSettingsSave(); state.importInProgress = importer; @@ -4530,8 +4530,31 @@ function resetBoardLabelFilter() { state.activeDateFilter = BOARD_DATE_FILTER_NONE; } -async function ensureBoardLabelsLoaded() { - if (!window.boardRoot) { +function formatBoardPickerParentPath(parentRoot) { + const normalized = String(parentRoot || '').trim(); + if (!normalized) { + return undefined; + } + if (/^[A-Za-z]:\/+$/.test(normalized)) { + return `${normalized.slice(0, 2)}/`; + } + if (/^\/+$/.test(normalized)) { + return '/'; + } + return normalized.replace(/\/+$/, ''); +} + +let boardLabelsLoadRequestId = 0; + +async function ensureBoardLabelsLoaded(options = {}) { + boardLabelsLoadRequestId += 1; + const requestId = boardLabelsLoadRequestId; + const requestedBoardRoot = typeof normalizeBoardPath === 'function' + ? normalizeBoardPath(options && options.boardRoot ? options.boardRoot : window.boardRoot) + : String((options && options.boardRoot) || window.boardRoot || ''); + const settingsModalOpen = typeof isBoardSettingsModalOpen === 'function' && isBoardSettingsModalOpen(); + + if (!requestedBoardRoot) { const state = getBoardLabelState(); state.importSummaryBoardRoot = ''; resetBoardLabelFilter(); @@ -4541,16 +4564,28 @@ async function ensureBoardLabelsLoaded() { applyColorSchemeById('light', { renderControls: false }); renderBoardLabelFilterButton(); renderBoardLabelFilterPopover(); - renderBoardThemeSettingsControls(); - renderBoardGeneralSettingsControls(); - renderBoardWorkflowSettingsControls(); - renderBoardExternalPublishedCalendarSettingsControls(); - renderAppSettingsControls(); - renderBoardImportControls(); + if (settingsModalOpen) { + renderBoardThemeSettingsControls(); + renderBoardGeneralSettingsControls(); + renderBoardWorkflowSettingsControls(); + renderBoardExternalPublishedCalendarSettingsControls(); + renderAppSettingsControls(); + renderBoardImportControls(); + } + return; + } + + const settings = options && options.preloadedSettings && typeof options.preloadedSettings === 'object' + ? options.preloadedSettings + : await window.board.readBoardSettings(requestedBoardRoot); + + const currentBoardRoot = typeof normalizeBoardPath === 'function' + ? normalizeBoardPath(window.boardRoot) + : String(window.boardRoot || ''); + if (requestId !== boardLabelsLoadRequestId || currentBoardRoot !== requestedBoardRoot) { return; } - const settings = await window.board.readBoardSettings(window.boardRoot); setBoardLabels(settings.labels || []); setBoardWorkflowSettings(settings.workflow || {}); setBoardExternalPublishedCalendarSettings(settings.externalPublishedCalendar || {}); @@ -4562,12 +4597,14 @@ async function ensureBoardLabelsLoaded() { } renderBoardLabelFilterButton(); renderBoardLabelFilterPopover(); - renderBoardThemeSettingsControls(); - renderBoardGeneralSettingsControls(); - renderBoardWorkflowSettingsControls(); - renderBoardExternalPublishedCalendarSettingsControls(); - renderAppSettingsControls(); - renderBoardImportControls(); + if (settingsModalOpen) { + renderBoardThemeSettingsControls(); + renderBoardGeneralSettingsControls(); + renderBoardWorkflowSettingsControls(); + renderBoardExternalPublishedCalendarSettingsControls(); + renderAppSettingsControls(); + renderBoardImportControls(); + } } function closeAllLabelPopovers() { diff --git a/app/board/boardTabs.js b/app/board/boardTabs.js index eaf3a90..845140b 100644 --- a/app/board/boardTabs.js +++ b/app/board/boardTabs.js @@ -10,7 +10,7 @@ function normalizeBoardPath(dir) { return ''; } - const normalizedDir = dir.replace(/\\/g, '/').trim(); + const normalizedDir = dir.replace(/\\/g, '/').trim().replace(/^([a-z]):\//, (_, drive) => `${drive.toUpperCase()}:/`); if (!normalizedDir) { return ''; } diff --git a/app/board/plannerView.js b/app/board/plannerView.js index 2d87d3d..cc00a46 100644 --- a/app/board/plannerView.js +++ b/app/board/plannerView.js @@ -975,10 +975,10 @@ async function restorePlannerCardContext() { if (typeof flushBoardLabelSettingsSave === 'function') await flushBoardLabelSettingsSave(); // Main-process archive/move/watch operations also own an active board root. // Restore their authorization context before exposing the original board. + state.cardContext = null; if (!await authorizeBoardAccess(context.boardRoot)) { throw new Error('Unable to restore the selected board after editing a Planner card.'); } - state.cardContext = null; window.boardRoot = context.boardRoot; window.__boardLabelState = context.labelState; window.__boardSearchState = context.searchState; @@ -1319,7 +1319,7 @@ function renderPlannerCalendarView(container, cardEntries) { return []; } - return sortableContainers.map((sortableContainer) => new Sortable(sortableContainer, createBoardCardSortableOptions({ + return sortableContainers.map((sortableContainer) => () => new Sortable(sortableContainer, createBoardCardSortableOptions({ group: 'planner-calendar-cards', animation: 150, draggable: '.planner-calendar-card', @@ -1409,7 +1409,7 @@ function renderPlannerWeekView(container, cardEntries) { return []; } - return sortableContainers.map((sortableContainer) => new Sortable(sortableContainer, createBoardCardSortableOptions({ + return sortableContainers.map((sortableContainer) => () => new Sortable(sortableContainer, createBoardCardSortableOptions({ group: 'planner-week-cards', animation: 150, draggable: '.planner-this-week-card', @@ -1540,16 +1540,16 @@ async function renderPlannerView() { const stagingEl = document.createElement('div'); stagingEl.className = 'planner-staging'; const activeView = getPlannerActiveView(); - let sortables = []; + let sortableFactories = []; if (activeView === PLANNER_VIEW_IDS.THIS_WEEK) { - sortables = renderPlannerWeekView(stagingEl, cards); + sortableFactories = renderPlannerWeekView(stagingEl, cards); } else if (activeView === PLANNER_VIEW_IDS.DAY) { - sortables = renderPlannerDayView(stagingEl, cards); + sortableFactories = renderPlannerDayView(stagingEl, cards); } else if (activeView === PLANNER_VIEW_IDS.AGENDA) { - sortables = renderPlannerAgendaView(stagingEl, cards); + sortableFactories = renderPlannerAgendaView(stagingEl, cards); } else { - sortables = renderPlannerCalendarView(stagingEl, cards); + sortableFactories = renderPlannerCalendarView(stagingEl, cards); } if (errors.length > 0) { @@ -1566,6 +1566,9 @@ async function renderPlannerView() { destroyPlannerSortables(); plannerBody.replaceChildren(...Array.from(stagingEl.childNodes)); + const sortables = sortableFactories + .map((factory) => (typeof factory === 'function' ? factory() : factory)) + .filter(Boolean); storePlannerSortables(sortables); renderPlannerViewControls(); @@ -2051,6 +2054,10 @@ async function openPlannerView(options = {}) { if (!state.isOpen || requestedScope) { applyPlannerScope(requestedScope === 'current' ? 'current' : 'all'); } + if (state.closeTimerId) { + clearTimeout(state.closeTimerId); + state.closeTimerId = null; + } state.isOpen = true; overlay.dataset.transitionDirection = String(options.transitionDirection || 'left'); overlay.classList.remove('hidden', 'is-closing'); @@ -2077,11 +2084,16 @@ function closePlannerView(options = {}) { closePlannerFilterPopover(); destroyPlannerSortables(); + if (state.closeTimerId) { + clearTimeout(state.closeTimerId); + state.closeTimerId = null; + } if (overlay) { overlay.classList.add('is-closing'); overlay.dataset.transitionDirection = String(options.transitionDirection || 'left'); overlay.setAttribute('aria-hidden', 'true'); - window.setTimeout(() => { + state.closeTimerId = window.setTimeout(() => { + state.closeTimerId = null; if (!getPlannerState().isOpen) { overlay.classList.add('hidden'); } diff --git a/app/board/renderBoard.js b/app/board/renderBoard.js index 3a1fd1e..bc93445 100644 --- a/app/board/renderBoard.js +++ b/app/board/renderBoard.js @@ -357,14 +357,25 @@ async function renderBoard() { const activeBoardView = typeof getActiveBoardView === 'function' ? getActiveBoardView() : 'kanban'; - const [snapshot] = await Promise.all([ - readBoardSnapshotForRender(boardRoot, { - includeBoardSettings: false, - includeTimestamps: activeBoardView === 'table', - includeTaskItems: false, - }), - ensureBoardLabelsLoaded(), - ]); + const snapshot = await readBoardSnapshotForRender(boardRoot, { + includeBoardSettings: true, + includeTimestamps: activeBoardView === 'table', + includeTaskItems: false, + }); + + if (!isCurrentBoardRenderRequest(requestId)) { + return; + } + + await ensureBoardLabelsLoaded({ + boardRoot, + preloadedSettings: snapshot.boardSettings, + }); + + if (!isCurrentBoardRenderRequest(requestId)) { + return; + } + const boardName = snapshot.boardName || window.board.getBoardName(boardRoot); const listsWithCards = snapshot.lists.map((listEntry) => ({ listName: listEntry.listName, @@ -372,10 +383,6 @@ async function renderBoard() { cards: Array.isArray(listEntry.cards) ? listEntry.cards : [], })); - if (!isCurrentBoardRenderRequest(requestId)) { - return; - } - updateBoardReadWarning(boardEl, snapshot); if (activeBoardView === 'table' && typeof renderTableBoard === 'function') { @@ -460,6 +467,7 @@ async function renderBoard() { .map((list) => list.getAttribute('data-path')) .filter(Boolean); + window.listOrderInProgress = true; try { if (!window.board || typeof window.board.reorderLists !== 'function') { throw new Error('List reorder is unavailable.'); @@ -472,6 +480,7 @@ async function renderBoard() { announceSignboardStatus('List order could not be saved.'); } } finally { + window.listOrderInProgress = false; await renderBoard(); } } @@ -484,6 +493,9 @@ async function renderBoard() { feather.replace(); } } catch (error) { + if (!isCurrentBoardRenderRequest(requestId)) { + return; + } if (isMissingBoardPathError(error)) { console.warn(`Board path is missing: ${boardRoot}`, error); renderMissingBoardAlert(boardRoot); diff --git a/app/cards/createCardElement.js b/app/cards/createCardElement.js index fef3a05..8eeacae 100644 --- a/app/cards/createCardElement.js +++ b/app/cards/createCardElement.js @@ -955,17 +955,5 @@ async function createCardElement(cardPath, options = {}) { await openCardEditor(); }); - // Not used yet! Drop zone for attachments - cardEl.addEventListener('dragover', e => e.preventDefault()); - cardEl.addEventListener('drop', async e => { - e.preventDefault(); - // const filePath = e.dataTransfer.files[0].path; - // const dst = await window.board.copyExternal(filePath, path.dirname(cardPath)); - // const newMd = `${md}\n![${path.basename(filePath)}](${path.basename(dst)})`; - // await window.board.writeCard(cardPath, newMd); - // const updatedCard = await createCardElement(cardPath); - // cardEl.parentNode.replaceChild(updatedCard, cardEl); - }); - return cardEl; } diff --git a/app/init.js b/app/init.js index 36d82b7..ffee9cb 100644 --- a/app/init.js +++ b/app/init.js @@ -79,7 +79,13 @@ async function collectDueTodayCards(boardRoot, todayIsoDate) { return collectDueTodayItemsForBoard(window.board, boardRoot, todayIsoDate); } +let dueCardNotificationCheckInFlight = false; + async function runDueCardNotificationCheck() { + if (dueCardNotificationCheckInFlight) { + return; + } + if ( !window.electronAPI || typeof window.electronAPI.notifyDueCards !== 'function' || @@ -115,40 +121,47 @@ async function runDueCardNotificationCheck() { return; } - let allDueItems = []; + dueCardNotificationCheckInFlight = true; + try { + let allDueItems = []; + + for (const boardRoot of boardRoots) { + let boardName = ''; + try { + boardName = typeof getBoardLabelFromPath === 'function' + ? getBoardLabelFromPath(boardRoot) + : String(boardRoot || '').replace(/\/+$/, '').split('/').pop(); + } catch { + boardName = ''; + } - for (const boardRoot of boardRoots) { - let boardName = ''; - try { - boardName = typeof getBoardLabelFromPath === 'function' - ? getBoardLabelFromPath(boardRoot) - : String(boardRoot || '').replace(/\/+$/, '').split('/').pop(); - } catch { - boardName = ''; + const dueItems = await collectDueTodayCards(boardRoot, todayIsoDate); + allDueItems = allDueItems.concat(dueItems.map((item) => ({ + ...item, + boardName, + }))); } - const dueItems = await collectDueTodayCards(boardRoot, todayIsoDate); - allDueItems = allDueItems.concat(dueItems.map((item) => ({ - ...item, - boardName, - }))); - } + const notificationBody = buildDueNotificationBody(allDueItems); + if (notificationBody) { + await window.electronAPI.notifyDueCards({ + title: 'Signboard', + body: notificationBody, + }); + } - const notificationBody = buildDueNotificationBody(allDueItems); - if (notificationBody) { - await window.electronAPI.notifyDueCards({ - title: 'Signboard', - body: notificationBody, - }); + writeDueNotificationLastRunDate(todayIsoDate); + } finally { + dueCardNotificationCheckInFlight = false; } - - writeDueNotificationLastRunDate(todayIsoDate); } function startDueCardNotificationSchedule() { - runDueCardNotificationCheck().catch((error) => { - console.error('Initial due-card notification check failed.', error); - }); + window.setTimeout(() => { + runDueCardNotificationCheck().catch((error) => { + console.error('Initial due-card notification check failed.', error); + }); + }, 1000); if (dueCardNotificationIntervalId) { clearInterval(dueCardNotificationIntervalId); @@ -285,10 +298,21 @@ function isBoardDragInProgress() { return typeof Sortable !== 'undefined' && Sortable && Sortable.active != null; } +function isInlineListTitleEditing() { + const active = typeof document !== 'undefined' ? document.activeElement : null; + return Boolean( + active && + active.isContentEditable && + typeof active.closest === 'function' && + active.closest('#board .list') + ); +} + function isExternalBoardRefreshBlocked() { return isBoardDragInProgress() || Boolean(window.listOrderInProgress) || Boolean(window.cardOrderInProgress) + || isInlineListTitleEditing() || (typeof isCardDatePopoverOpen === 'function' && isCardDatePopoverOpen()) || (typeof isCardLabelPopoverOpen === 'function' && isCardLabelPopoverOpen()) || (typeof isListActionsPopoverOpen === 'function' && isListActionsPopoverOpen()) @@ -988,7 +1012,7 @@ async function externalBoardSyncTick() { // The drop handler updates paths in place and acknowledges its own // watch events after the transaction. Do not queue a redundant refresh // from those events while the asynchronous drop is still finishing. - if (window.cardOrderInProgress) { + if (window.cardOrderInProgress || window.listOrderInProgress) { return; } @@ -997,7 +1021,7 @@ async function externalBoardSyncTick() { } const latestToken = Number(await window.board.getBoardWatchToken()); - if (window.cardOrderInProgress) { + if (window.cardOrderInProgress || window.listOrderInProgress) { return; } if (!Number.isFinite(latestToken) || latestToken <= externalBoardWatchToken) { @@ -1017,11 +1041,24 @@ function startExternalBoardSync() { } externalBoardSyncIntervalId = window.setInterval(() => { + if (typeof document !== 'undefined' && document.visibilityState === 'hidden') { + return; + } externalBoardSyncTick().catch((error) => { console.error('External board sync tick failed.', error); }); }, EXTERNAL_BOARD_SYNC_INTERVAL_MS); + if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') { + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'visible') { + externalBoardSyncTick().catch((error) => { + console.error('External board sync tick on visibility restore failed.', error); + }); + } + }); + } + externalBoardSyncTick().catch((error) => { console.error('Initial external board sync failed.', error); }); diff --git a/app/modals/closeAllModals.js b/app/modals/closeAllModals.js index 7e5bedb..956660f 100644 --- a/app/modals/closeAllModals.js +++ b/app/modals/closeAllModals.js @@ -23,9 +23,9 @@ function resetCardEditorModalState() { cardEditorCardMetadata.value = ''; } - const cardEditorCardDueDateDisplay = document.getElementById('cardEditorCardDueDateDisplay'); - if (cardEditorCardDueDateDisplay) { - cardEditorCardDueDateDisplay.textContent = ''; + const cardEditorCardDatesDisplay = document.getElementById('cardEditorCardDatesDisplay'); + if (cardEditorCardDatesDisplay) { + cardEditorCardDatesDisplay.textContent = ''; } const cardEditorCardLabels = document.getElementById('cardEditorCardLabels'); @@ -298,6 +298,10 @@ async function closeAllModals(e, options = {}){ if (boardSettingsClosed) boardColorSchemePicker.close(); + if (typeof closeCardDatePopover === 'function') { + closeCardDatePopover(); + } + if (editModalClosed) { if (typeof destroyTaskLineDueDateControls === 'function') { destroyTaskLineDueDateControls(); diff --git a/app/modals/toggleEditCardModal.js b/app/modals/toggleEditCardModal.js index 0296522..135cb6f 100644 --- a/app/modals/toggleEditCardModal.js +++ b/app/modals/toggleEditCardModal.js @@ -624,8 +624,25 @@ function filePathToRendererUrl(filePath) { } const forwardPath = normalized.replace(/\\/g, '/'); - const prefixedPath = forwardPath.startsWith('/') ? forwardPath : `/${forwardPath}`; - return `file://${encodeURI(prefixedPath)}`; + const encodeSegments = (raw) => raw.split('/').map((segment, index) => ( + index === 0 && /^[A-Za-z]:$/.test(segment) + ? segment + : encodeURIComponent(segment) + )).join('/'); + + if (forwardPath.startsWith('//')) { + const withoutSlashes = forwardPath.replace(/^\/+/, ''); + const firstSlash = withoutSlashes.indexOf('/'); + if (firstSlash === -1) { + return `file://${encodeURIComponent(withoutSlashes)}`; + } + const host = withoutSlashes.slice(0, firstSlash); + const rest = withoutSlashes.slice(firstSlash + 1); + return `file://${host}/${encodeSegments(rest)}`; + } + + const withoutLeadingSlash = forwardPath.startsWith('/') ? forwardPath.slice(1) : forwardPath; + return `file:///${encodeSegments(withoutLeadingSlash)}`; } function appendLinkedObjectIcon(parent, linkedObject) { @@ -1091,6 +1108,13 @@ async function refreshActiveCardEditorFromDiskIfClean() { const cardEditorTitle = document.getElementById('cardEditorTitle'); const editorTextarea = document.querySelector('#cardEditorOverType .overtype-input'); + // Never hold isApplyingExternalEditorRefresh across async metadata IPCs, or user typing would be dropped. + await renderActiveEditorMetadata(card.frontmatter, card.timestamps); + + if (!isActiveEditorUnchangedFromDisk() || getActiveEditorCardPath() !== cardPath) { + return false; + } + isApplyingExternalEditorRefresh = true; try { setEditorFrontmatter(card.frontmatter); @@ -1098,8 +1122,6 @@ async function refreshActiveCardEditorFromDiskIfClean() { cardEditorTitle.textContent = card.frontmatter.title || ''; } - await renderActiveEditorMetadata(card.frontmatter, card.timestamps); - if (activeCardEditorInstance && typeof activeCardEditorInstance.setValue === 'function') { activeCardEditorInstance.setValue(card.body); } else if (editorTextarea) { @@ -2487,7 +2509,11 @@ function setupTaskLineDueDateControls(editor) { }; } +let cardEditorOpenRequestId = 0; + async function toggleEditCardModal(cardPath, options = {}) { + cardEditorOpenRequestId += 1; + const openRequestId = cardEditorOpenRequestId; const shouldOpenDueDatePicker = Boolean(options && options.openDueDatePicker); const shouldFocusNotes = Boolean(options && options.focusNotes); const modalEditCard = document.getElementById('modalEditCard'); @@ -2495,9 +2521,15 @@ async function toggleEditCardModal(cardPath, options = {}) { destroyCardEditorBodyUrlControls(); const card = await window.board.readCard(cardPath); + if (openRequestId !== cardEditorOpenRequestId) { + return; + } const cardEditorCardPath = document.getElementById('cardEditorCardPath'); const cardID = await window.board.getCardID(cardPath); + if (openRequestId !== cardEditorOpenRequestId) { + return; + } const cardEditorCardID = document.getElementById('cardEditorCardID'); cardEditorCardID.textContent = cardID; cardEditorCardID.setAttribute('aria-label', `Open card file ${cardID}`); @@ -2517,10 +2549,10 @@ async function toggleEditCardModal(cardPath, options = {}) { cardEditorTitle.textContent = card.frontmatter.title || ''; cardEditorCardDatesDisplay.textContent = ''; setDueDateVisualClass(cardEditorSetDatesLink, ''); - setEditorLabelDisplay(card.frontmatter.labels); - renderCardEditorRelatedNotes(card.frontmatter); - renderCardEditorTimestamps(card.timestamps); - await renderActiveEditorMetadata(card.frontmatter); + await renderActiveEditorMetadata(card.frontmatter, card.timestamps); + if (openRequestId !== cardEditorOpenRequestId) { + return; + } const [editor] = new OverType('#cardEditorOverType', { value: card.body, @@ -2542,7 +2574,6 @@ async function toggleEditCardModal(cardPath, options = {}) { OverType.setTheme(customOverTypeThemes.light); } - editor.setValue(card.body); removeViewModeToolbarButton(editor); editor.container.classList.remove('preview-mode'); editor.container.classList.remove('plain-mode'); @@ -2554,11 +2585,19 @@ async function toggleEditCardModal(cardPath, options = {}) { if ( e.code == 'Enter' ) { e.preventDefault(); return; } }; + const triggerTitleSave = async () => { + const cardEditorContents = document.getElementsByClassName('overtype-input'); + if (cardEditorContents[0]) { + await handleNotesSave(cardEditorContents[0].value, false); + } + }; + cardEditorTitle.onkeyup = async (e) => { if ( e.code == 'Enter' ) { e.preventDefault(); return; } - - const cardEditorContents = document.getElementsByClassName('overtype-input'); - await handleNotesSave(cardEditorContents[0].value,false); + await triggerTitleSave(); + }; + cardEditorTitle.oninput = async () => { + await triggerTitleSave(); }; const openDatesPickerControl = async (e) => { @@ -5354,12 +5393,20 @@ async function handleClickDuplicateCard( e ) { e.stopPropagation(); const cardEditorCardPath = document.getElementById('cardEditorCardPath'); - const card = await window.board.readCard(cardEditorCardPath.value); + if (typeof flushEditorSaveIfNeeded === 'function') { + await flushEditorSaveIfNeeded(); + } - let currentCardName = await window.board.getCardFileName(cardEditorCardPath.value); - let newCardName = '999' + currentCardName.slice(3,currentCardName.length).slice(0, -8) + await rand5() + '.md'; + const sourcePath = cardEditorCardPath.value; + const card = await window.board.readCard(sourcePath); - let newCardPath = cardEditorCardPath.value.replace( currentCardName, newCardName ); + let currentCardName = await window.board.getCardFileName(sourcePath); + let newCardName = '999' + currentCardName.slice(3, currentCardName.length).slice(0, -8) + await rand5() + '.md'; + + const lastNameIndex = sourcePath.lastIndexOf(currentCardName); + let newCardPath = lastNameIndex >= 0 + ? `${sourcePath.slice(0, lastNameIndex)}${newCardName}${sourcePath.slice(lastNameIndex + currentCardName.length)}` + : sourcePath.replace(currentCardName, newCardName); const duplicatedFrontmatterSource = { ...card.frontmatter, @@ -5386,8 +5433,18 @@ async function handleClickDuplicateCard( e ) { body: card.body, }); - await closeAllModals(createCloseAllModalsRequest(), { rerender: true }); - await toggleEditCardModal(newCardPath); + await closeAllModals(createCloseAllModalsRequest(), { + rerender: true, + preservePlannerCardContext: true, + }); + try { + await toggleEditCardModal(newCardPath); + } catch (error) { + if (typeof restorePlannerCardContext === 'function') { + await restorePlannerCardContext().catch(() => {}); + } + throw error; + } if (typeof announceSignboardStatus === 'function') { announceSignboardStatus(`Duplicated card "${copiedFrontmatter.title || 'Untitled'}".`); } diff --git a/app/ui/theme.js b/app/ui/theme.js index 0107fee..98fbb31 100644 --- a/app/ui/theme.js +++ b/app/ui/theme.js @@ -245,9 +245,17 @@ window.addEventListener('DOMContentLoaded', () => { if (window.electronAPI && typeof window.electronAPI.onOmarchyThemeChanged === 'function') { window.electronAPI.onOmarchyThemeChanged((status) => { + const wasFollowing = typeof isFollowingOmarchyTheme === 'function' && isFollowingOmarchyTheme(); if (typeof setAppOmarchyThemeStatus === 'function') { setAppOmarchyThemeStatus(status); } + const isNowFollowing = typeof isFollowingOmarchyTheme === 'function' && isFollowingOmarchyTheme(); + if (!wasFollowing && !isNowFollowing) { + if (typeof renderAppSettingsControls === 'function') { + renderAppSettingsControls(); + } + return; + } applyConfiguredAppTheme({ renderBoard: true }) .then(() => { if (typeof renderAppSettingsControls === 'function') { diff --git a/app/ui/tooltips.js b/app/ui/tooltips.js index 1291e84..c74302e 100644 --- a/app/ui/tooltips.js +++ b/app/ui/tooltips.js @@ -173,6 +173,7 @@ function findTooltipTarget(startNode) { return null; } + syncTooltipTarget(candidate); const tooltipText = collapseTooltipText(candidate.getAttribute(TOOLTIP_TEXT_ATTR)); return tooltipText ? candidate : null; } @@ -294,51 +295,39 @@ function handleTooltipFocusOut(event) { hideTooltip(); } -function handleTooltipViewportChange() { - if (!areTooltipsEnabled()) { - hideTooltip(); - return; - } +let tooltipViewportRafId = 0; +function handleTooltipViewportChange() { const state = getTooltipState(); - if (!state.activeTarget || !state.activeTarget.isConnected) { - hideTooltip(); + if (!state.activeTarget) { return; } - updateTooltipPosition(state.activeTarget); -} - -function observeTooltipTargets() { - const state = getTooltipState(); - if (state.observer || !document.body) { + if (tooltipViewportRafId) { return; } - const observer = new MutationObserver((mutations) => { - for (const mutation of mutations) { - if (mutation.type === 'attributes') { - syncTooltipTarget(mutation.target); - continue; - } + const update = () => { + tooltipViewportRafId = 0; + if (!areTooltipsEnabled()) { + hideTooltip(); + return; + } - for (const node of mutation.addedNodes) { - if (!(node instanceof Element)) { - continue; - } - syncTooltipTargets(node); - } + const latestState = getTooltipState(); + if (!latestState.activeTarget || !latestState.activeTarget.isConnected) { + hideTooltip(); + return; } - }); - observer.observe(document.body, { - childList: true, - subtree: true, - attributes: true, - attributeFilter: ['title', 'aria-label', 'alt', 'data-tooltip', 'data-sb-tooltip', 'data-sb-tooltip-disabled'], - }); + updateTooltipPosition(latestState.activeTarget); + }; - state.observer = observer; + if (typeof window.requestAnimationFrame === 'function') { + tooltipViewportRafId = window.requestAnimationFrame(update); + } else { + update(); + } } function initializeTooltips() { @@ -364,7 +353,6 @@ function initializeTooltips() { window.addEventListener('resize', handleTooltipViewportChange); window.addEventListener('scroll', handleTooltipViewportChange, true); - observeTooltipTargets(); state.initialized = true; } diff --git a/app/utilities/accessibility.js b/app/utilities/accessibility.js index 9b47d0f..7d73e06 100644 --- a/app/utilities/accessibility.js +++ b/app/utilities/accessibility.js @@ -267,7 +267,22 @@ function prefersReducedMotion() { return Boolean(state.reducedMotionQuery && state.reducedMotionQuery.matches); } +function isMacOsPlatformForMenuSettle() { + if (typeof isPrimaryShortcutMacPlatform === 'function') { + return isPrimaryShortcutMacPlatform(); + } + if (typeof navigator === 'undefined') { + return false; + } + const platform = String(navigator.platform || navigator.userAgent || ''); + return /Mac|iPhone|iPad|iPod/i.test(platform); +} + function waitForNativeMenuTrackingToSettle() { + if (!isMacOsPlatformForMenuSettle()) { + return Promise.resolve(); + } + return new Promise((resolve) => { window.setTimeout(() => { if (typeof window.requestAnimationFrame === 'function') { diff --git a/app/utilities/dueNotifications.js b/app/utilities/dueNotifications.js index a7e8d0c..0bc2d9a 100644 --- a/app/utilities/dueNotifications.js +++ b/app/utilities/dueNotifications.js @@ -57,9 +57,53 @@ function buildDueNotificationBody(dueItemsValue) { return normalizeDueNotificationText(summary, DUE_NOTIFICATION_MAX_BODY_LENGTH); } +function appendDueItemsForCardRecord(dueItems, card, todayIsoDate) { + const cardTitle = normalizeDueNotificationText( + String(card?.frontmatter?.title || '').trim() || 'Untitled', + DUE_NOTIFICATION_MAX_CARD_TITLE_LENGTH, + ); + const cardDueDate = normalizeTaskDueDateValue(card?.frontmatter?.due); + + if (cardDueDate === todayIsoDate) { + dueItems.push({ + kind: 'card', + cardTitle, + taskText: '', + }); + } + + const taskItems = Array.isArray(card?.taskItems) + ? card.taskItems + : parseTaskListItems(card?.body || ''); + for (const taskItem of taskItems) { + if (taskItem.isCompleted) { + continue; + } + + const taskDueDate = normalizeTaskDueDateValue(taskItem.due); + if (taskDueDate !== todayIsoDate) { + continue; + } + + const taskText = normalizeDueNotificationText( + taskItem.contentWithoutDue || taskItem.content || '', + DUE_NOTIFICATION_MAX_TASK_SNIPPET_LENGTH, + ); + if (!taskText) { + continue; + } + + dueItems.push({ + kind: 'task', + cardTitle, + taskText, + }); + } +} + async function collectDueTodayItemsForBoard(boardApi, boardRoot, todayIsoDate) { const dueItems = []; - if (!boardApi || typeof boardApi.listLists !== 'function' || typeof boardApi.listCards !== 'function' || typeof boardApi.readCard !== 'function') { + if (!boardApi) { return dueItems; } @@ -71,6 +115,41 @@ async function collectDueTodayItemsForBoard(boardApi, boardRoot, todayIsoDate) { return dueItems; } + if (typeof boardApi.readBoardSnapshot === 'function') { + try { + const snapshot = await boardApi.readBoardSnapshot(normalizedBoardRoot, { + includeBoardSettings: true, + includeTimestamps: false, + includeTaskItems: true, + }); + if (snapshot && Array.isArray(snapshot.lists)) { + const workflowSettings = snapshot.boardSettings && snapshot.boardSettings.workflow + ? snapshot.boardSettings.workflow + : {}; + for (const listEntry of snapshot.lists) { + const listName = String(listEntry && listEntry.listName || '').trim(); + if ( + !listName || + (typeof isBoardListCompletedByWorkflow === 'function' && + isBoardListCompletedByWorkflow(listName, workflowSettings)) + ) { + continue; + } + for (const card of Array.isArray(listEntry.cards) ? listEntry.cards : []) { + appendDueItemsForCardRecord(dueItems, card, todayIsoDate); + } + } + return dueItems; + } + } catch { + // Fall back to legacy per-list reads below. + } + } + + if (typeof boardApi.listLists !== 'function' || typeof boardApi.listCards !== 'function' || typeof boardApi.readCard !== 'function') { + return dueItems; + } + let lists = []; let workflowSettings = {}; try { @@ -105,45 +184,7 @@ async function collectDueTodayItemsForBoard(boardApi, boardRoot, todayIsoDate) { const cardPath = `${listPath}/${cardFileName}`; try { const card = await boardApi.readCard(cardPath); - const cardTitle = normalizeDueNotificationText( - String(card?.frontmatter?.title || '').trim() || 'Untitled', - DUE_NOTIFICATION_MAX_CARD_TITLE_LENGTH, - ); - const cardDueDate = normalizeTaskDueDateValue(card?.frontmatter?.due); - - if (cardDueDate === todayIsoDate) { - dueItems.push({ - kind: 'card', - cardTitle, - taskText: '', - }); - } - - const taskItems = parseTaskListItems(card?.body || ''); - for (const taskItem of taskItems) { - if (taskItem.isCompleted) { - continue; - } - - const taskDueDate = normalizeTaskDueDateValue(taskItem.due); - if (taskDueDate !== todayIsoDate) { - continue; - } - - const taskText = normalizeDueNotificationText( - taskItem.contentWithoutDue || taskItem.content || '', - DUE_NOTIFICATION_MAX_TASK_SNIPPET_LENGTH, - ); - if (!taskText) { - continue; - } - - dueItems.push({ - kind: 'task', - cardTitle, - taskText, - }); - } + appendDueItemsForCardRecord(dueItems, card, todayIsoDate); } catch { // Ignore unreadable cards and continue scanning. } diff --git a/bin/signboard-mcp.js b/bin/signboard-mcp.js index 815cfd3..174041a 100644 --- a/bin/signboard-mcp.js +++ b/bin/signboard-mcp.js @@ -1,22 +1,62 @@ #!/usr/bin/env node +const fs = require('fs').promises; +const path = require('path'); const packageJson = require('../package.json'); const { + OPEN_BOARDS_STATE_FILE, + TRUSTED_BOARD_ROOTS_FILE, + getDefaultDesktopUserDataDir, readDesktopOpenBoardsState, readDesktopTrustedBoardRoots, } = require('../lib/boardDiscovery'); const { startSignboardMcpServer } = require('../lib/mcpServer'); +async function statSignature(filePath) { + try { + const stats = await fs.stat(filePath); + return `${stats.mtimeMs}:${stats.size}`; + } catch { + return 'missing'; + } +} + async function runMcpServer() { - const [trustedBoardRoots, desktopOpenBoardsState] = await Promise.all([ + const userDataDir = getDefaultDesktopUserDataDir(); + const trustedPath = userDataDir ? path.join(userDataDir, TRUSTED_BOARD_ROOTS_FILE) : ''; + const openBoardsPath = userDataDir ? path.join(userDataDir, OPEN_BOARDS_STATE_FILE) : ''; + + let lastTrustedSig = trustedPath ? await statSignature(trustedPath) : ''; + let lastOpenSig = openBoardsPath ? await statSignature(openBoardsPath) : ''; + let [trustedBoardRoots, desktopOpenBoardsState] = await Promise.all([ readDesktopTrustedBoardRoots(), readDesktopOpenBoardsState(), ]); + const refreshDesktopState = async () => { + if (!userDataDir) { + return { trustedBoardRoots, desktopOpenBoardsState }; + } + const [nextTrustedSig, nextOpenSig] = await Promise.all([ + statSignature(trustedPath), + statSignature(openBoardsPath), + ]); + if (nextTrustedSig !== lastTrustedSig) { + trustedBoardRoots = await readDesktopTrustedBoardRoots(); + lastTrustedSig = nextTrustedSig; + } + if (nextOpenSig !== lastOpenSig) { + desktopOpenBoardsState = await readDesktopOpenBoardsState(); + lastOpenSig = nextOpenSig; + } + return { trustedBoardRoots, desktopOpenBoardsState }; + }; + await startSignboardMcpServer({ appVersion: packageJson.version, trustedBoardRoots, desktopOpenBoardsState, + refreshDesktopState, }); } diff --git a/config/build-info.json b/config/build-info.json index d1e92e9..7756e71 100644 --- a/config/build-info.json +++ b/config/build-info.json @@ -1,11 +1,11 @@ { "schemaVersion": 1, - "version": "1.7.8", - "buildId": "20261120.1", + "version": "1.7.9", + "buildId": "20261203.1", "channel": "release", - "builtAt": "2026-11-20T09:20:39.136Z", - "sourceFingerprint": "3de83b023a4a0a600a5fb60bac620a8c6461c49006225ddcfc47ba8cf5dac30b", - "sourceFileCount": 177, - "commit": "b70b112c850688ebef15a9e2865032818b324cf6", + "builtAt": "2026-12-03T19:24:08.339Z", + "sourceFingerprint": "6d8eb88befe4f186e73822414e75d0c80c9a3e578bc36551cbb74980a381a91b", + "sourceFileCount": 178, + "commit": "d4d8cfdbd526ddd75231ffd57075b747a4059834", "dirty": true } diff --git a/docs/codex/FILE_STRUCTURE.md b/docs/codex/FILE_STRUCTURE.md index 8afdc5d..3cd64ba 100644 --- a/docs/codex/FILE_STRUCTURE.md +++ b/docs/codex/FILE_STRUCTURE.md @@ -244,3 +244,7 @@ Linux CI installs only the required Xvfb/Openbox dependencies, with bounded netw Editor archive actions share one pending promise through final modal cleanup. Other modal transitions wait for it; archive cleanup bypasses its own wait. Preserve failure cleanup, duplicate-request handling, and the delayed-archive Electron regression. App settings save responses reconcile against the submitted snapshot: preserve newer renderer edits while accepting server-generated values for unchanged fields. Keep the deferred-save regression in `test:app-settings` and Smart Actions Electron coverage aligned. + +## 1.7.9 speed and reliability coverage + +- `scripts/test-speed-reliability.js` (`npm run test:speed-reliability`) — focused regressions for dot-entry exclusion, BOM/parse-error protection, `fileTransaction` stale `.reap` recovery, Linux zero-birthtime fallback, `insertCardFileAtTop` unchanged-entry skipping, `.DS_Store` archive cleanup & `--as` validation, duplication whitespace/lock filtering, CLI card-ID fast lookup & boolean flags, MCP split-chunk framing/EOF drain/Windows path body preservation, Obsidian Kanban settings stripping, UTF-8 ICS line folding, async Arch Pacman installation, and Linux direct-`exec` CLI shims. diff --git a/docs/codex/PROJECT_CONTEXT.md b/docs/codex/PROJECT_CONTEXT.md index 400683e..976b619 100644 --- a/docs/codex/PROJECT_CONTEXT.md +++ b/docs/codex/PROJECT_CONTEXT.md @@ -670,3 +670,7 @@ App settings save responses reconcile against the submitted snapshot: preserve n ## Card move metadata — 1.7.8 `lib/archive.js` records cross-list move activity and normalizes destination Signboard properties in one atomic card write. Desktop drag/drop and move-to-top must not follow it with a second metadata write. Same-list drag reorders leave card contents unchanged. Preserve body/custom fields and the atomic-failure regression in `test:archive`; filtered-drag Electron tests assert both `status` and `signboard_list` before opening the editor. + +## Speed and reliability — 1.7.9 + +Desktop rendering eliminates per-card `formatDueDate` IPC round-trips, gates the 250ms AppKit select/menu settle delay to macOS, resolves tooltips lazily without a global `MutationObserver`, folds `boardSettings` into `readBoardSnapshot` without rebuilding hidden Settings panels, avoids duplicate Archive Browser renders/sorts, pauses external-sync polling while hidden, and hardens editor refresh/open/duplicate and Planner context restoration races. Main-process and shared storage layers exclude hidden dot-entries from snapshots and ordering, protect settings/cards against UTF-8 BOMs and parse-error overwrites, harden `lib/fileTransaction.js`, retry Windows transient renames/unlinks, stop board watchers before Windows board moves, run Arch Pacman updates asynchronously, diff Obsidian metadata refreshes, and cache External Published Calendar feeds with UTF-8-safe ICS folding. MCP fixes split-chunk header framing, EOF draining, `EPIPE`, Windows junction discovery errors, pre-resolved `allowedRoots`, scoped `assertAllowedTree`, live desktop root refreshes, and Windows path body preservation; CLI adds card-ID-first lookup, lazy module loading, boolean-flag parsing fixes, single-write `--move-to`, and a direct `exec` Linux shim. Covered by `npm run test:speed-reliability`. diff --git a/index.html b/index.html index 0c77769..0cc5329 100644 --- a/index.html +++ b/index.html @@ -424,7 +424,7 @@

Sponsor Signboard when it supports your work

Commercial-use sponsorship

$49 one-time

-

No subscription. Pay once and keep using the for commercial work.

+

No subscription. Pay once and keep using the app for commercial work.

diff --git a/lib/allowedPaths.js b/lib/allowedPaths.js index 2fe9eb9..638bb6e 100644 --- a/lib/allowedPaths.js +++ b/lib/allowedPaths.js @@ -1,11 +1,18 @@ const fs = require('fs').promises; const path = require('path'); +const { mapFileReads } = require('./fileReadQueue'); function isInside(root, candidate) { const relative = path.relative(root, candidate); return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)); } +async function resolveCanonicalRoots(allowedRoots) { + const roots = Array.isArray(allowedRoots) ? allowedRoots : []; + const resolved = await Promise.all(roots.map((root) => fs.realpath(root).catch(() => null))); + return resolved.filter(Boolean); +} + // Resolve the nearest existing ancestor for new files/directories as well as // existing targets. A dangling symlink must never be mistaken for a new path. async function canonicalPath(candidate) { @@ -25,8 +32,10 @@ async function canonicalPath(candidate) { } } -async function assertAllowedPath(allowedRoots, candidate, label = 'Path') { - const roots = (await Promise.all(allowedRoots.map((root) => fs.realpath(root).catch(() => null)))).filter(Boolean); +async function assertAllowedPath(allowedRoots, candidate, label = 'Path', preResolvedRoots = null) { + const roots = Array.isArray(preResolvedRoots) + ? preResolvedRoots + : await resolveCanonicalRoots(allowedRoots); const resolved = await canonicalPath(candidate); if (!roots.some((root) => isInside(root, resolved))) { throw new Error(`${label} is outside SIGNBOARD_MCP_ALLOWED_ROOTS.`); @@ -36,18 +45,49 @@ async function assertAllowedPath(allowedRoots, candidate, label = 'Path') { // Bulk import/archive operations may follow known nested files. Validate links // before entering shared helpers, including links in otherwise hidden folders. -async function assertAllowedTree(allowedRoots, root, seen = new Set()) { - const resolved = await assertAllowedPath(allowedRoots, root); - if (seen.has(resolved)) return; - seen.add(resolved); - const stat = await fs.stat(root); - if (!stat.isDirectory()) return; - for (const entry of await fs.readdir(root, { withFileTypes: true })) { - const child = path.join(root, entry.name); - if (entry.isSymbolicLink() || entry.isDirectory()) { - await assertAllowedTree(allowedRoots, child, seen); - } +async function assertAllowedTree(allowedRoots, root, seen = new Set(), preResolvedRoots = null) { + const roots = Array.isArray(preResolvedRoots) + ? preResolvedRoots + : await resolveCanonicalRoots(allowedRoots); + let level = [root]; + + while (level.length > 0) { + const nextLevel = []; + await mapFileReads(level, async (currentPath) => { + const resolved = await assertAllowedPath(allowedRoots, currentPath, 'Path', roots); + if (seen.has(resolved)) { + return; + } + seen.add(resolved); + + let stat; + try { + stat = await fs.stat(currentPath); + } catch (error) { + if (error && error.code === 'ENOENT') { + return; + } + throw error; + } + if (!stat.isDirectory()) { + return; + } + + const entries = await fs.readdir(currentPath, { withFileTypes: true }); + for (const entry of entries) { + if (entry.isSymbolicLink() || entry.isDirectory()) { + nextLevel.push(path.join(currentPath, entry.name)); + } + } + }); + level = nextLevel; } } -module.exports = { assertAllowedPath, assertAllowedTree, canonicalPath, isInside }; +module.exports = { + assertAllowedPath, + assertAllowedTree, + canonicalPath, + isInside, + resolveCanonicalRoots, +}; diff --git a/lib/appSettings.js b/lib/appSettings.js index 245a8aa..6292dfb 100644 --- a/lib/appSettings.js +++ b/lib/appSettings.js @@ -2,6 +2,7 @@ const fs = require('fs').promises; const path = require('path'); const appSettingsSchema = require('../shared/appSettingsSchema'); const { atomicWriteFile } = require('./atomicFile'); +const { withFileTransaction } = require('./fileTransaction'); const { APP_SETTINGS_FILE_NAME, @@ -34,15 +35,32 @@ function getAppSettingsPath(userDataPath) { return path.join(userDataPath, APP_SETTINGS_FILE_NAME); } -async function readAppSettings(userDataPath) { +async function readAppSettingsStrict(userDataPath) { const settingsPath = getAppSettingsPath(userDataPath); try { const raw = await fs.readFile(settingsPath, 'utf8'); - const parsed = JSON.parse(raw); + const cleanRaw = raw.startsWith('\uFEFF') ? raw.slice(1) : raw; + const parsed = JSON.parse(cleanRaw); return { settingsPath, ...normalizeAppSettings(parsed), }; + } catch (error) { + if (error && error.code === 'ENOENT') { + return { + settingsPath, + ...normalizeAppSettings({}), + }; + } + + throw error; + } +} + +async function readAppSettings(userDataPath) { + const settingsPath = getAppSettingsPath(userDataPath); + try { + return await readAppSettingsStrict(userDataPath); } catch (error) { if (error && error.code !== 'ENOENT') { console.error('Failed to read app settings.', error); @@ -67,70 +85,74 @@ async function writeAppSettings(userDataPath, settings) { } async function updateAppSettings(userDataPath, partialSettings = {}) { - const current = await readAppSettings(userDataPath); - const next = { - ...current, - ...(isObject(partialSettings) ? partialSettings : {}), - }; + return withFileTransaction(getAppSettingsPath(userDataPath), async () => { + const current = await readAppSettingsStrict(userDataPath); + const next = { + ...current, + ...(isObject(partialSettings) ? partialSettings : {}), + }; - if (Object.prototype.hasOwnProperty.call(partialSettings, 'notifications')) { - next.notifications = normalizeNotificationSettings(partialSettings.notifications); - } + if (Object.prototype.hasOwnProperty.call(partialSettings, 'notifications')) { + next.notifications = normalizeNotificationSettings(partialSettings.notifications); + } - if (Object.prototype.hasOwnProperty.call(partialSettings, 'tooltipsEnabled')) { - next.tooltipsEnabled = normalizeTooltipsEnabled(partialSettings.tooltipsEnabled); - } + if (Object.prototype.hasOwnProperty.call(partialSettings, 'tooltipsEnabled')) { + next.tooltipsEnabled = normalizeTooltipsEnabled(partialSettings.tooltipsEnabled); + } - if (Object.prototype.hasOwnProperty.call(partialSettings, 'quickAdd')) { - next.quickAdd = normalizeQuickAddSettings(partialSettings.quickAdd); - } + if (Object.prototype.hasOwnProperty.call(partialSettings, 'quickAdd')) { + next.quickAdd = normalizeQuickAddSettings(partialSettings.quickAdd); + } - if (Object.prototype.hasOwnProperty.call(partialSettings, 'appearance')) { - next.appearance = normalizeAppearanceSettings(partialSettings.appearance); - } + if (Object.prototype.hasOwnProperty.call(partialSettings, 'appearance')) { + next.appearance = normalizeAppearanceSettings(partialSettings.appearance); + } - if (Object.prototype.hasOwnProperty.call(partialSettings, 'externalPublishedCalendar')) { - next.externalPublishedCalendar = normalizeExternalPublishedCalendarSettings(partialSettings.externalPublishedCalendar); - } + if (Object.prototype.hasOwnProperty.call(partialSettings, 'externalPublishedCalendar')) { + next.externalPublishedCalendar = normalizeExternalPublishedCalendarSettings(partialSettings.externalPublishedCalendar); + } - if (Object.prototype.hasOwnProperty.call(partialSettings, 'ai')) { - next.ai = normalizeAiSettings(partialSettings.ai); - } + if (Object.prototype.hasOwnProperty.call(partialSettings, 'ai')) { + next.ai = normalizeAiSettings(partialSettings.ai); + } - if (Object.prototype.hasOwnProperty.call(partialSettings, 'migration')) { - next.migration = { - ...normalizeAppSettings(current).migration, - ...normalizeAppSettings({ migration: partialSettings.migration }).migration, - }; - } + if (Object.prototype.hasOwnProperty.call(partialSettings, 'migration')) { + next.migration = { + ...normalizeAppSettings(current).migration, + ...normalizeAppSettings({ migration: partialSettings.migration }).migration, + }; + } - return writeAppSettings(userDataPath, next); + return writeAppSettings(userDataPath, next); + }); } async function migrateAppSettingsFromBoardSettings(userDataPath, boardRoot, legacySettings = {}) { - const current = await readAppSettings(userDataPath); - if (current.migration && current.migration.boardSettingsMigrated) { + return withFileTransaction(getAppSettingsPath(userDataPath), async () => { + const current = await readAppSettingsStrict(userDataPath); + if (current.migration && current.migration.boardSettingsMigrated) { + return { + migrated: false, + settings: current, + }; + } + + const nextSettings = await writeAppSettings(userDataPath, { + ...current, + notifications: normalizeNotificationSettings(legacySettings.notifications), + tooltipsEnabled: normalizeTooltipsEnabled(legacySettings.tooltipsEnabled), + migration: { + boardSettingsMigrated: true, + sourceBoardRoot: typeof boardRoot === 'string' ? boardRoot : '', + migratedAt: new Date().toISOString(), + }, + }); + return { - migrated: false, - settings: current, + migrated: true, + settings: nextSettings, }; - } - - const nextSettings = await writeAppSettings(userDataPath, { - ...current, - notifications: normalizeNotificationSettings(legacySettings.notifications), - tooltipsEnabled: normalizeTooltipsEnabled(legacySettings.tooltipsEnabled), - migration: { - boardSettingsMigrated: true, - sourceBoardRoot: typeof boardRoot === 'string' ? boardRoot : '', - migratedAt: new Date().toISOString(), - }, }); - - return { - migrated: true, - settings: nextSettings, - }; } module.exports = { diff --git a/lib/archive.js b/lib/archive.js index 2a66ff1..b54d61e 100644 --- a/lib/archive.js +++ b/lib/archive.js @@ -3,7 +3,9 @@ const path = require('path'); const boardLabels = require('./boardLabels'); const cardFrontmatter = require('./cardFrontmatter'); const { insertCardFileAtTop } = require('./cardOrdering'); -const { atomicWriteFile } = require('./atomicFile'); +const { atomicWriteFile, renameWithWindowsRetry } = require('./atomicFile'); +const { mapFileReads } = require('./fileReadQueue'); +const { withFileTransaction } = require('./fileTransaction'); const { normalizeSignboardCardFrontmatter } = require('./obsidianIntegration'); const { clearCardArchiveState, @@ -99,7 +101,7 @@ async function pathExists(targetPath) { function isPathInside(rootPath, targetPath) { const relative = path.relative(rootPath, targetPath); - return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative)); + return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)); } function randomSuffix(length = 5) { @@ -172,11 +174,8 @@ function buildArchivedCardFileName(cardFile, nextPrefix) { function getCardIdFromFileName(fileName) { const normalized = String(fileName || ''); - if (!normalized.endsWith('.md') || normalized.length < 8) { - return ''; - } - - return normalized.slice(normalized.length - 8, normalized.length - 3); + const match = normalized.match(/-([A-Za-z0-9]{5})\.md$/); + return match ? match[1] : ''; } function getFallbackTimestampFromStats(stats) { @@ -345,26 +344,28 @@ async function writeArchivedListMetadata(listPath, metadata = {}) { async function listMarkdownCardFiles(directoryPath) { const entries = await fs.readdir(directoryPath, { withFileTypes: true }); return entries - .filter((entry) => entry.isFile() && entry.name.endsWith('.md')) + .filter((entry) => entry.isFile() && !entry.name.startsWith('.') && entry.name.endsWith('.md')) .map((entry) => entry.name) .sort(compareArchiveNames); } async function mutateCard(cardPath, transform) { - const currentCard = await cardFrontmatter.readCard(cardPath); - const nextFrontmatter = typeof transform === 'function' - ? transform(currentCard.frontmatter, currentCard) - : currentCard.frontmatter; - - await cardFrontmatter.writeCard(cardPath, { - frontmatter: nextFrontmatter, - body: currentCard.body, - }); + return withFileTransaction(cardPath, async () => { + const currentCard = await cardFrontmatter.readCard(cardPath); + const nextFrontmatter = typeof transform === 'function' + ? transform(currentCard.frontmatter, currentCard) + : currentCard.frontmatter; + + await cardFrontmatter.writeCard(cardPath, { + frontmatter: nextFrontmatter, + body: currentCard.body, + }); - return { - frontmatter: nextFrontmatter, - body: currentCard.body, - }; + return { + frontmatter: nextFrontmatter, + body: currentCard.body, + }; + }); } async function buildBoardLabelNameMap(boardRoot) { @@ -411,7 +412,7 @@ function normalizeArchivedCardState(frontmatter = {}, fallback = {}) { async function buildArchivedCardEntry(boardRoot, cardPath, labelNameMap, options = {}) { const [card, stats] = await Promise.all([ cardFrontmatter.readCard(cardPath), - fs.stat(cardPath), + options.stats ? Promise.resolve(options.stats) : fs.stat(cardPath), ]); const fileName = path.basename(cardPath); const archivedListPath = trimStringValue(options.archivedListPath); @@ -431,7 +432,7 @@ async function buildArchivedCardEntry(boardRoot, cardPath, labelNameMap, options .map((labelId) => labelNameMap.get(labelId) || labelId) .filter(Boolean); - return { + const entry = { kind: 'card', entryPath: cardPath, archivedCardPath: cardPath, @@ -450,6 +451,12 @@ async function buildArchivedCardEntry(boardRoot, cardPath, labelNameMap, options due: trimStringValue(card.frontmatter.due), previewText: buildPreviewText(card.body), }; + + if (options.includeCard) { + return { entry, card }; + } + + return entry; } function toPublicArchivedListEntry(listPath, metadata, cardCount) { @@ -503,13 +510,21 @@ async function listArchiveEntries(boardRoot) { const lists = []; const sortedEntries = entries.slice().sort((left, right) => compareArchiveNames(left.name, right.name)); + const cardJobs = []; for (const entry of sortedEntries) { + if (entry.name.startsWith('.')) { + continue; + } + const entryPath = path.join(archiveRoot, entry.name); if (entry.isFile() && entry.name.endsWith('.md')) { - cards.push(await buildArchivedCardEntry(normalizedBoardRoot, entryPath, labelNameMap, { - archiveContainerType: 'standalone-card', - })); + cardJobs.push({ + cardPath: entryPath, + options: { + archiveContainerType: 'standalone-card', + }, + }); continue; } @@ -522,16 +537,24 @@ async function listArchiveEntries(boardRoot) { lists.push(toPublicArchivedListEntry(entryPath, metadata, cardFiles.length)); for (const cardFile of cardFiles) { - cards.push(await buildArchivedCardEntry(normalizedBoardRoot, path.join(entryPath, cardFile), labelNameMap, { - archivedListPath: entryPath, - archiveContainerType: 'archived-list', - originalListDirectoryName: metadata.originalListDirectoryName, - originalListDisplayName: metadata.originalListDisplayName, - archivedAt: metadata.archivedAt, - })); + cardJobs.push({ + cardPath: path.join(entryPath, cardFile), + options: { + archivedListPath: entryPath, + archiveContainerType: 'archived-list', + originalListDirectoryName: metadata.originalListDirectoryName, + originalListDisplayName: metadata.originalListDisplayName, + archivedAt: metadata.archivedAt, + }, + }); } } + const builtCards = await mapFileReads(cardJobs, (job) => ( + buildArchivedCardEntry(normalizedBoardRoot, job.cardPath, labelNameMap, job.options) + )); + cards.push(...builtCards); + cards.sort(compareArchivedEntriesByNewest); lists.sort(compareArchivedEntriesByNewest); @@ -557,7 +580,6 @@ async function readArchiveEntry(boardRoot, entryPath) { const stats = await fs.stat(normalizedEntryPath); if (stats.isFile()) { - await ensureFile(normalizedEntryPath, 'Archived card'); const labelNameMap = await buildBoardLabelNameMap(normalizedBoardRoot); const archivedListPath = path.dirname(normalizedEntryPath) === archiveRoot ? '' @@ -567,14 +589,15 @@ async function readArchiveEntry(boardRoot, entryPath) { listMetadata = await readArchivedListMetadata(archivedListPath); } - const entry = await buildArchivedCardEntry(normalizedBoardRoot, normalizedEntryPath, labelNameMap, { + const { entry, card } = await buildArchivedCardEntry(normalizedBoardRoot, normalizedEntryPath, labelNameMap, { archivedListPath, archiveContainerType: archivedListPath ? 'archived-list' : 'standalone-card', originalListDirectoryName: listMetadata && listMetadata.originalListDirectoryName, originalListDisplayName: listMetadata && listMetadata.originalListDisplayName, archivedAt: listMetadata && listMetadata.archivedAt, + stats, + includeCard: true, }); - const card = await cardFrontmatter.readCard(normalizedEntryPath); return { ok: true, @@ -590,24 +613,24 @@ async function readArchiveEntry(boardRoot, entryPath) { }; } - await ensureDirectory(normalizedEntryPath, 'Archived list'); + if (!stats.isDirectory()) { + throw new Error(`Archived list is not a directory: ${normalizedEntryPath}`); + } const metadata = await readArchivedListMetadata(normalizedEntryPath, { stats }); const cardFiles = await listMarkdownCardFiles(normalizedEntryPath); const labelNameMap = await buildBoardLabelNameMap(normalizedBoardRoot); - const cards = await Promise.all( - cardFiles.map((cardFile) => buildArchivedCardEntry( - normalizedBoardRoot, - path.join(normalizedEntryPath, cardFile), - labelNameMap, - { - archivedListPath: normalizedEntryPath, - archiveContainerType: 'archived-list', - originalListDirectoryName: metadata.originalListDirectoryName, - originalListDisplayName: metadata.originalListDisplayName, - archivedAt: metadata.archivedAt, - }, - )), - ); + const cards = await mapFileReads(cardFiles, (cardFile) => buildArchivedCardEntry( + normalizedBoardRoot, + path.join(normalizedEntryPath, cardFile), + labelNameMap, + { + archivedListPath: normalizedEntryPath, + archiveContainerType: 'archived-list', + originalListDirectoryName: metadata.originalListDirectoryName, + originalListDisplayName: metadata.originalListDisplayName, + archivedAt: metadata.archivedAt, + }, + )); return { ok: true, @@ -628,24 +651,40 @@ function getListContextFromPath(listPath) { }; } +const IGNORABLE_ARCHIVE_CONTAINER_FILES = new Set(['.ds_store', 'thumbs.db', 'desktop.ini']); + async function maybeRemoveEmptyArchivedListContainer(archivedListPath) { const normalizedListPath = trimStringValue(archivedListPath); if (!normalizedListPath || !(await pathExists(normalizedListPath))) { return false; } - const remainingCardFiles = await listMarkdownCardFiles(normalizedListPath); - if (remainingCardFiles.length > 0) { + const entries = await fs.readdir(normalizedListPath, { withFileTypes: true }); + const nonMetadataEntries = entries.filter((entry) => entry.name !== ARCHIVED_LIST_METADATA_FILE); + const hasRealContent = nonMetadataEntries.some( + (entry) => !entry.isFile() || !IGNORABLE_ARCHIVE_CONTAINER_FILES.has(entry.name.toLowerCase()), + ); + if (hasRealContent) { return false; } const metadataPath = getArchivedListMetadataPath(normalizedListPath); + for (const entry of nonMetadataEntries) { + await fs.rm(path.join(normalizedListPath, entry.name), { force: true }).catch(() => {}); + } if (await pathExists(metadataPath)) { await fs.rm(metadataPath, { force: true }); } - await fs.rmdir(normalizedListPath); - return true; + try { + await fs.rmdir(normalizedListPath); + return true; + } catch (error) { + if (error && (error.code === 'ENOTEMPTY' || error.code === 'ENOENT')) { + return false; + } + throw error; + } } async function archiveCard(boardRoot, cardPath) { @@ -684,13 +723,25 @@ async function archiveCard(boardRoot, cardPath) { let archivedCardFile = path.basename(normalizedCardPath); let archivedCardPath = path.join(archiveRoot, archivedCardFile); - while (await pathExists(archivedCardPath)) { - const nextPrefix = await nextArchiveCardPrefix(archiveRoot); - archivedCardFile = buildArchivedCardFileName(archivedCardFile, nextPrefix); - archivedCardPath = path.join(archiveRoot, archivedCardFile); + if (await pathExists(archivedCardPath)) { + let candidatePrefix = Number(await nextArchiveCardPrefix(archiveRoot)); + for (let attempt = 0; attempt < 1000 && (await pathExists(archivedCardPath)); attempt += 1) { + archivedCardFile = buildArchivedCardFileName( + archivedCardFile, + String(candidatePrefix + attempt).padStart(3, '0'), + ); + archivedCardPath = path.join(archiveRoot, archivedCardFile); + } + + if (await pathExists(archivedCardPath)) { + const ext = path.extname(archivedCardFile) || '.md'; + const stem = archivedCardFile.slice(0, archivedCardFile.length - ext.length); + archivedCardFile = `${stem}-${randomSuffix(5)}${ext}`; + archivedCardPath = path.join(archiveRoot, archivedCardFile); + } } - await fs.rename(normalizedCardPath, archivedCardPath); + await renameWithWindowsRetry(normalizedCardPath, archivedCardPath); await mutateCard(archivedCardPath, (frontmatter) => setCardArchiveState(frontmatter, { archivedAt, originalListDirectoryName: sourceList.directoryName, @@ -866,6 +917,17 @@ async function restoreArchivedList(boardRoot, archivedListPath, restoredDirector const nextDirectoryName = trimStringValue(restoredDirectoryName) || trimStringValue(existingMetadata.originalListDirectoryName) || path.basename(normalizedArchivedListPath); + + if ( + !nextDirectoryName || + nextDirectoryName === '.' || + nextDirectoryName === '..' || + nextDirectoryName.includes('/') || + nextDirectoryName.includes('\\') + ) { + throw new Error('Restored list directory name must be a single valid folder name.'); + } + const restoredListPath = path.join(normalizedBoardRoot, nextDirectoryName); if (!isPathInside(normalizedBoardRoot, restoredListPath) || isPathInside(archiveRoot, restoredListPath)) { @@ -876,7 +938,7 @@ async function restoreArchivedList(boardRoot, archivedListPath, restoredDirector throw new Error(`Destination list already exists: ${nextDirectoryName}`); } - await fs.rename(normalizedArchivedListPath, restoredListPath); + await renameWithWindowsRetry(normalizedArchivedListPath, restoredListPath); const restoredList = getListContextFromPath(restoredListPath); const restoredAt = formatActivityTimestamp(); diff --git a/lib/atomicFile.js b/lib/atomicFile.js index acc9c28..e004ba3 100644 --- a/lib/atomicFile.js +++ b/lib/atomicFile.js @@ -2,7 +2,32 @@ const fs = require('fs').promises; const path = require('path'); const { randomUUID } = require('crypto'); +const WINDOWS_RETRYABLE_FS_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']); +const WINDOWS_RETRY_DELAYS_MS = [25, 75, 150, 300]; +const BEST_EFFORT_CHMOD_CODES = new Set(['EPERM', 'ENOSYS', 'ENOTSUP', 'EINVAL']); + +async function renameWithWindowsRetry(fromPath, toPath, platform = process.platform) { + for (let attempt = 0; ; attempt += 1) { + try { + return await fs.rename(fromPath, toPath); + } catch (error) { + const retryable = platform === 'win32' + && error + && WINDOWS_RETRYABLE_FS_CODES.has(error.code) + && attempt < WINDOWS_RETRY_DELAYS_MS.length; + if (!retryable) { + throw error; + } + await new Promise((resolve) => setTimeout(resolve, WINDOWS_RETRY_DELAYS_MS[attempt])); + } + } +} + async function syncDirectory(directoryPath) { + if (process.platform === 'win32') { + return; + } + let directoryHandle = null; try { @@ -24,6 +49,9 @@ async function atomicWriteFile(filePath, data, options = {}) { const encoding = typeof options === 'string' ? options : (options && options.encoding) || undefined; + const shouldSyncDir = typeof options === 'object' && options !== null && options.syncDir === false + ? false + : true; const tempPath = path.join( directoryPath, `.${baseName}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`, @@ -34,24 +62,36 @@ async function atomicWriteFile(filePath, data, options = {}) { await fs.mkdir(directoryPath, { recursive: true }); let mode = 0o666 & ~process.umask(); - try { - const existing = await fs.stat(resolvedPath); - mode = existing.mode & 0o777; - } catch (error) { - if (error.code !== 'ENOENT') throw error; + if (process.platform !== 'win32') { + try { + const existing = await fs.stat(resolvedPath); + mode = existing.mode & 0o777; + } catch (error) { + if (error.code !== 'ENOENT') throw error; + } } try { fileHandle = await fs.open(tempPath, 'wx', 0o600); await fileHandle.writeFile(data, encoding ? { encoding } : undefined); - await fileHandle.chmod(mode); + if (process.platform !== 'win32') { + try { + await fileHandle.chmod(mode); + } catch (error) { + if (!error || !BEST_EFFORT_CHMOD_CODES.has(error.code)) { + throw error; + } + } + } await fileHandle.sync(); await fileHandle.close(); fileHandle = null; - await fs.rename(tempPath, resolvedPath); + await renameWithWindowsRetry(tempPath, resolvedPath); shouldCleanupTemp = false; - await syncDirectory(directoryPath); + if (shouldSyncDir) { + await syncDirectory(directoryPath); + } } finally { if (fileHandle) { await fileHandle.close().catch(() => {}); @@ -65,4 +105,6 @@ async function atomicWriteFile(filePath, data, options = {}) { module.exports = { atomicWriteFile, + renameWithWindowsRetry, + syncDirectory, }; diff --git a/lib/boardDiscovery.js b/lib/boardDiscovery.js index f72bebc..a76dfa0 100644 --- a/lib/boardDiscovery.js +++ b/lib/boardDiscovery.js @@ -1,7 +1,8 @@ const fs = require('fs').promises; const os = require('os'); const path = require('path'); -const { assertAllowedPath } = require('./allowedPaths'); +const { assertAllowedPath, resolveCanonicalRoots } = require('./allowedPaths'); +const { mapFileReads } = require('./fileReadQueue'); const TRUSTED_BOARD_ROOTS_FILE = 'trusted-board-roots.json'; const OPEN_BOARDS_STATE_FILE = 'open-boards.json'; @@ -9,7 +10,9 @@ const DEFAULT_BOARD_SCAN_DEPTH = 2; const DEFAULT_BOARD_SCAN_LIMIT = 100; const MAX_BOARD_SCAN_DEPTH = 8; const MAX_BOARD_SCAN_LIMIT = 500; -const SKIPPED_DIRECTORY_NAMES = new Set(['.git', '.svn', '.hg', 'node_modules']); +const MAX_BOARD_SCAN_DIRECTORIES = 5000; +const SKIPPED_DIRECTORY_NAMES = new Set(['.git', '.svn', '.hg', '.obsidian', '.cache', '.trash', 'node_modules', 'dist', 'target', '.venv']); +const INACCESSIBLE_DIR_ERROR_CODES = new Set(['ENOENT', 'ENOTDIR', 'EACCES', 'EPERM', 'ELOOP']); const boardSortCollator = new Intl.Collator(undefined, { usage: 'sort', @@ -19,14 +22,17 @@ const boardSortCollator = new Intl.Collator(undefined, { localeMatcher: 'lookup', }); +function pathIdentityKey(targetPath) { + return process.platform === 'win32' ? String(targetPath || '').toLowerCase() : String(targetPath || ''); +} + function normalizeAbsolutePath(rawPath) { const input = typeof rawPath === 'string' ? rawPath.trim() : ''; - if (!input) { + if (!input || !path.isAbsolute(input)) { return ''; } - const resolved = path.resolve(input); - return path.isAbsolute(resolved) ? resolved : ''; + return path.resolve(input); } function normalizePathList(paths) { @@ -35,11 +41,12 @@ function normalizePathList(paths) { for (const rawPath of Array.isArray(paths) ? paths : []) { const normalizedPath = normalizeAbsolutePath(rawPath); - if (!normalizedPath || seen.has(normalizedPath)) { + const key = pathIdentityKey(normalizedPath); + if (!normalizedPath || seen.has(key)) { continue; } - seen.add(normalizedPath); + seen.add(key); normalizedPaths.push(normalizedPath); } @@ -54,7 +61,7 @@ function isPathInside(parentPath, childPath) { } const relativePath = path.relative(normalizedParent, normalizedChild); - return relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath)); + return relativePath === '' || (relativePath !== '..' && !relativePath.startsWith(`..${path.sep}`) && !path.isAbsolute(relativePath)); } function isPathInsideAnyRoot(rootPaths, childPath) { @@ -75,13 +82,27 @@ async function pathExistsAsDirectory(directoryPath) { const stats = await fs.stat(directoryPath); return stats.isDirectory(); } catch (error) { - if (error && error.code === 'ENOENT') { + if (error && INACCESSIBLE_DIR_ERROR_CODES.has(error.code)) { return false; } throw error; } } +function entriesLookLikeSignboardBoardRoot(entries) { + return Array.isArray(entries) && entries.some((entry) => { + if (entry.isFile() && entry.name === 'board-settings.md') { + return true; + } + + if (!entry.isDirectory()) { + return false; + } + + return entry.name === 'XXX-Archive' || /^\d{3,}-/.test(entry.name); + }); +} + async function pathLooksLikeSignboardBoardRoot(directoryPath) { const boardRoot = normalizeAbsolutePath(directoryPath); if (!boardRoot) { @@ -99,17 +120,7 @@ async function pathLooksLikeSignboardBoardRoot(directoryPath) { return false; } - return entries.some((entry) => { - if (entry.isFile() && entry.name === 'board-settings.md') { - return true; - } - - if (!entry.isDirectory()) { - return false; - } - - return entry.name === 'XXX-Archive' || /^\d{3,}-/.test(entry.name); - }); + return entriesLookLikeSignboardBoardRoot(entries); } function normalizeOpenBoardsState(rawState = {}) { @@ -146,6 +157,7 @@ function getDefaultDesktopUserDataDir({ if (appDataDir) { return path.join(appDataDir, 'Signboard'); } + return resolvedHomeDir ? path.join(resolvedHomeDir, 'AppData', 'Roaming', 'Signboard') : ''; } if (platform === 'darwin') { @@ -165,9 +177,10 @@ function getDefaultDesktopUserDataDir({ async function readJsonFile(filePath, fallbackValue) { try { const raw = await fs.readFile(filePath, 'utf8'); - return JSON.parse(raw); + const cleanRaw = raw.startsWith('\uFEFF') ? raw.slice(1) : raw; + return JSON.parse(cleanRaw); } catch (error) { - if ((error && error.code === 'ENOENT') || error instanceof SyntaxError) { + if ((error && INACCESSIBLE_DIR_ERROR_CODES.has(error.code)) || error instanceof SyntaxError) { return fallbackValue; } throw error; @@ -200,14 +213,15 @@ function addBoardCandidate(candidateMap, rawBoardRoot, source, orderHint) { return null; } - let candidate = candidateMap.get(boardRoot); + const key = pathIdentityKey(boardRoot); + let candidate = candidateMap.get(key); if (!candidate) { candidate = { boardRoot, sources: new Set(), order: Number.isFinite(orderHint) ? orderHint : candidateMap.size + 1000, }; - candidateMap.set(boardRoot, candidate); + candidateMap.set(key, candidate); } candidate.sources.add(source); @@ -236,16 +250,21 @@ async function scanAllowedRootForBoards(allowedRoot, options = {}) { 1, MAX_BOARD_SCAN_LIMIT, ); + const maxDirectoriesVisited = normalizeInteger( + options.maxDirectoriesVisited, + MAX_BOARD_SCAN_DIRECTORIES, + 1, + 50000, + ); const matches = []; - const seen = new Set([rootPath]); - - if (await pathLooksLikeSignboardBoardRoot(rootPath)) { - return [rootPath]; - } - + const seen = new Set([pathIdentityKey(rootPath)]); const queue = [{ directoryPath: rootPath, depth: 0 }]; - while (queue.length > 0 && matches.length < limit) { - const current = queue.shift(); + let head = 0; + let visitedCount = 0; + + while (head < queue.length && matches.length < limit && visitedCount < maxDirectoriesVisited) { + const current = queue[head++]; + visitedCount += 1; let entries = []; try { @@ -254,37 +273,40 @@ async function scanAllowedRootForBoards(allowedRoot, options = {}) { continue; } + if (entriesLookLikeSignboardBoardRoot(entries)) { + matches.push(current.directoryPath); + continue; + } + + if (current.depth >= maxDepth) { + continue; + } + entries.sort((left, right) => boardSortCollator.compare(left.name, right.name)); for (const entry of entries) { - if (matches.length >= limit) { - break; - } - - if (!entry.isDirectory() || SKIPPED_DIRECTORY_NAMES.has(entry.name)) { + if ( + !entry.isDirectory() || + entry.name.startsWith('.') || + SKIPPED_DIRECTORY_NAMES.has(entry.name) + ) { continue; } const candidatePath = path.resolve(current.directoryPath, entry.name); + const candidateKey = pathIdentityKey(candidatePath); if ( - seen.has(candidatePath) || + seen.has(candidateKey) || !isPathInside(current.directoryPath, candidatePath) ) { continue; } - seen.add(candidatePath); - if (await pathLooksLikeSignboardBoardRoot(candidatePath)) { - matches.push(candidatePath); - continue; - } - - if (current.depth < maxDepth) { - queue.push({ - directoryPath: candidatePath, - depth: current.depth + 1, - }); - } + seen.add(candidateKey); + queue.push({ + directoryPath: candidatePath, + depth: current.depth + 1, + }); } } @@ -294,20 +316,23 @@ async function scanAllowedRootForBoards(allowedRoot, options = {}) { async function buildBoardRecord(candidate, context) { const sources = Array.from(candidate.sources).sort(); const boardRoot = candidate.boardRoot; - const exists = await pathExistsAsDirectory(boardRoot); - const isBoardRoot = exists ? await pathLooksLikeSignboardBoardRoot(boardRoot) : false; + const boardKey = pathIdentityKey(boardRoot); + const exists = candidate.knownExists === true ? true : await pathExistsAsDirectory(boardRoot); + const isBoardRoot = candidate.knownIsBoardRoot === true + ? true + : (exists ? await pathLooksLikeSignboardBoardRoot(boardRoot) : false); const isAllowed = context.allowedRoots.length === 0 ? context.allowWhenNoAllowedRoots - : await assertAllowedPath(context.allowedRoots, boardRoot).then(() => true, () => false); + : await assertAllowedPath(context.allowedRoots, boardRoot, 'boardRoot', context.canonicalAllowedRoots).then(() => true, () => false); return { name: path.basename(boardRoot), boardRoot, sources, isOpen: sources.includes('desktop-open'), - isActive: boardRoot === context.activeBoard, - isCurrent: boardRoot === context.currentBoard, - isTrusted: context.trustedBoardRootSet.has(boardRoot), + isActive: boardKey === context.activeBoardKey, + isCurrent: boardKey === context.currentBoardKey, + isTrusted: context.trustedBoardRootKeySet.has(boardKey), isAllowed, exists, isBoardRoot, @@ -358,10 +383,21 @@ async function discoverBoards(options = {}) { if (includeAllowedRootScan) { let scanOrder = 1000; for (const allowedRoot of allowedRoots) { - const matches = await scanAllowedRootForBoards(allowedRoot, { maxDepth, limit }); + if (candidateMap.size >= limit) { + break; + } + const remainingLimit = Math.max(1, limit - candidateMap.size); + const matches = await scanAllowedRootForBoards(allowedRoot, { maxDepth, limit: remainingLimit }); for (const match of matches) { - const source = match === allowedRoot ? 'mcp-allowed-root' : 'mcp-allowed-root-scan'; + const source = pathIdentityKey(match) === pathIdentityKey(allowedRoot) + ? 'mcp-allowed-root' + : 'mcp-allowed-root-scan'; addBoardCandidate(candidateMap, match, source, scanOrder); + const existingCandidate = candidateMap.get(pathIdentityKey(match)) || candidateMap.get(match); + if (existingCandidate) { + existingCandidate.knownExists = true; + existingCandidate.knownIsBoardRoot = true; + } scanOrder += 1; if (candidateMap.size >= limit) { break; @@ -370,15 +406,22 @@ async function discoverBoards(options = {}) { } } + const canonicalAllowedRoots = allowedRoots.length > 0 + ? await resolveCanonicalRoots(allowedRoots) + : []; const context = { activeBoard, + activeBoardKey: pathIdentityKey(activeBoard), currentBoard, - trustedBoardRootSet: new Set(trustedBoardRoots), + currentBoardKey: pathIdentityKey(currentBoard), + trustedBoardRootKeySet: new Set(trustedBoardRoots.map(pathIdentityKey)), allowedRoots, + canonicalAllowedRoots, allowWhenNoAllowedRoots: options.allowWhenNoAllowedRoots === true, }; - const boards = await Promise.all( - Array.from(candidateMap.values()).map((candidate) => buildBoardRecord(candidate, context)) + const boards = await mapFileReads( + Array.from(candidateMap.values()), + (candidate) => buildBoardRecord(candidate, context), ); boards.sort((left, right) => { diff --git a/lib/boardDuplication.js b/lib/boardDuplication.js index 28b8697..5ade5be 100644 --- a/lib/boardDuplication.js +++ b/lib/boardDuplication.js @@ -3,6 +3,7 @@ const path = require('path'); const { randomBytes } = require('crypto'); const cardFrontmatter = require('./cardFrontmatter'); const boardLabels = require('./boardLabels'); +const { mapFileReads } = require('./fileReadQueue'); const obsidianIntegration = require('./obsidianIntegration'); const CARD_ID_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; @@ -28,7 +29,7 @@ function isPathInsideRoot(rootPath, targetPath) { } const relative = path.relative(root, target); - return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative)); + return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)); } function sanitizeBoardDirectoryName(rawName) { @@ -140,12 +141,11 @@ async function renameCopiedCardsWithFreshIds(boardRoot) { } function rewriteSignboardCardUris(value, idMap) { - const source = trimString(value); - if (!source || !(idMap instanceof Map) || idMap.size === 0) { + if (typeof value !== 'string' || !value.trim() || !(idMap instanceof Map) || idMap.size === 0) { return value; } - return source.replace(SIGNBOARD_CARD_URI_PATTERN, (match, queryString) => { + return value.replace(SIGNBOARD_CARD_URI_PATTERN, (match, queryString) => { const params = new URLSearchParams(queryString); const currentId = params.get('id') || ''; const nextId = idMap.get(currentId); @@ -196,7 +196,7 @@ function rewriteLinkedObjects(linkedObjects, context) { } async function refreshCopiedCardMetadata(boardRoot, cards, context) { - for (const card of cards) { + await mapFileReads(cards, async (card) => { const currentCard = await cardFrontmatter.readCard(card.newPath); const rewrittenLinkedObjects = rewriteLinkedObjects(currentCard.frontmatter.linked_objects, context); const rewrittenBody = rewriteSignboardCardUris(currentCard.body, context.idMap); @@ -218,7 +218,7 @@ async function refreshCopiedCardMetadata(boardRoot, cards, context) { frontmatter: nextFrontmatter, body: rewrittenBody, }); - } + }); } async function resetCopiedManagedObsidianBase(boardRoot) { @@ -272,25 +272,42 @@ async function duplicateBoard(options = {}) { recursive: true, force: false, errorOnExist: true, + filter: (sourcePath) => { + const baseName = path.basename(sourcePath); + if ( + baseName === '.signboard-list-order.json' || + baseName.endsWith('.sb-lock') || + baseName.endsWith('.sb-lock.reap') || + baseName.endsWith('.tmp') + ) { + return false; + } + return true; + }, }); - const cards = await renameCopiedCardsWithFreshIds(destinationBoardRoot); - const idMap = new Map(cards.map((card) => [card.oldId, card.newId]).filter(([oldId, newId]) => oldId && newId)); - await refreshCopiedCardMetadata(destinationBoardRoot, cards, { - sourceBoardRoot, - destinationBoardRoot, - idMap, - }); - const resetManagedObsidianBase = await resetCopiedManagedObsidianBase(destinationBoardRoot); - - return { - ok: true, - boardRoot: destinationBoardRoot, - boardName, - cardsDuplicated: cards.length, - cardIdMap: Object.fromEntries(idMap.entries()), - resetManagedObsidianBase, - }; + try { + const cards = await renameCopiedCardsWithFreshIds(destinationBoardRoot); + const idMap = new Map(cards.map((card) => [card.oldId, card.newId]).filter(([oldId, newId]) => oldId && newId)); + await refreshCopiedCardMetadata(destinationBoardRoot, cards, { + sourceBoardRoot, + destinationBoardRoot, + idMap, + }); + const resetManagedObsidianBase = await resetCopiedManagedObsidianBase(destinationBoardRoot); + + return { + ok: true, + boardRoot: destinationBoardRoot, + boardName, + cardsDuplicated: cards.length, + cardIdMap: Object.fromEntries(idMap.entries()), + resetManagedObsidianBase, + }; + } catch (error) { + await fs.rm(destinationBoardRoot, { recursive: true, force: true }).catch(() => {}); + throw error; + } } module.exports = { diff --git a/lib/boardLabels.js b/lib/boardLabels.js index 10e060e..4f9e306 100644 --- a/lib/boardLabels.js +++ b/lib/boardLabels.js @@ -2,10 +2,11 @@ const fs = require('fs').promises; const path = require('path'); const yaml = require('js-yaml'); const { atomicWriteFile } = require('./atomicFile'); +const { withFileTransaction } = require('./fileTransaction'); const SETTINGS_FILE_NAME = 'board-settings.md'; const LEGACY_SETTINGS_FILE_NAME = 'labels.md'; -const YAML_FRONTMATTER_REGEX = /^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/; +const YAML_FRONTMATTER_REGEX = /^---[ \t]*\r?\n(?:([\s\S]*?)\r?\n)?---(\r?\n|$)/; const DEFAULT_LABELS = Object.freeze([ Object.freeze({ @@ -156,7 +157,7 @@ function normalizeThemeOverrides(rawThemeOverrides) { function normalizeNotificationTime(value) { const candidate = String(value || '').trim(); - if (/^(?:0[1-9]|1\d|2[0-4]):[0-5]\d$/.test(candidate)) { + if (/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(candidate)) { return candidate; } @@ -348,25 +349,30 @@ function themeOverridesHasValues(themeOverrides) { ); } -function parseBoardSettings(rawContent) { - const match = String(rawContent || '').match(YAML_FRONTMATTER_REGEX); +function parseBoardSettingsWithStatus(rawContent) { + const cleanContent = String(rawContent || '').replace(/^\uFEFF/, ''); + const match = cleanContent.match(YAML_FRONTMATTER_REGEX); if (!match) { - return {}; + return { parsed: {}, hadParseError: Boolean(cleanContent.trim()) }; } - const yamlSource = match[1]; + const yamlSource = match[1] || ''; if (!yamlSource.trim()) { - return {}; + return { parsed: {}, hadParseError: false }; } try { const parsed = yaml.load(yamlSource, { schema: yaml.JSON_SCHEMA }); - return isObject(parsed) ? parsed : {}; - } catch { - return {}; + return { parsed: isObject(parsed) ? parsed : {}, hadParseError: false }; + } catch (error) { + return { parsed: {}, hadParseError: true, error }; } } +function parseBoardSettings(rawContent) { + return parseBoardSettingsWithStatus(rawContent).parsed; +} + function normalizeBoardSettings(rawSettings = {}) { const source = isObject(rawSettings) ? rawSettings : {}; return { @@ -576,10 +582,10 @@ async function readBoardSettings(boardRoot, options = {}) { }; } - const parsed = parseBoardSettings(existing.raw); + const { parsed, hadParseError } = parseBoardSettingsWithStatus(existing.raw); const normalized = normalizeBoardSettings(parsed); - if (ensureFile) { + if (ensureFile && !hadParseError) { const shouldRewrite = existing.sourcePath !== primaryPath || !areLabelCollectionsEqual(parsed.labels, normalized.labels) || @@ -600,60 +606,88 @@ async function readBoardSettings(boardRoot, options = {}) { }; } -async function updateBoardLabels(boardRoot, labels = []) { - const current = await readBoardSettings(boardRoot, { ensureFile: true }); - const nextSettings = { - ...current, - labels, +async function readBoardSettingsForMutation(boardRoot) { + const existing = await loadExistingBoardSettings(boardRoot); + if (!existing) { + return { + settingsPath: getPrimarySettingsPath(boardRoot), + ...normalizeBoardSettings({}), + }; + } + + const { parsed, hadParseError, error } = parseBoardSettingsWithStatus(existing.raw); + if (hadParseError) { + throw new Error( + `Failed to parse ${path.basename(existing.sourcePath)}: ${error && error.message ? error.message : 'invalid frontmatter'}`, + ); + } + + return { + settingsPath: getPrimarySettingsPath(boardRoot), + ...normalizeBoardSettings(parsed), }; +} - return writeBoardSettings(boardRoot, nextSettings); +async function updateBoardLabels(boardRoot, labels = []) { + return withFileTransaction(getPrimarySettingsPath(boardRoot), async () => { + const current = await readBoardSettingsForMutation(boardRoot); + const nextSettings = { + ...current, + labels, + }; + + return writeBoardSettings(boardRoot, nextSettings); + }); } async function updateBoardThemeOverrides(boardRoot, themeOverrides = {}) { - const current = await readBoardSettings(boardRoot, { ensureFile: true }); - const nextSettings = { - ...current, - themeOverrides: cloneThemeOverrides(themeOverrides), - }; + return withFileTransaction(getPrimarySettingsPath(boardRoot), async () => { + const current = await readBoardSettingsForMutation(boardRoot); + const nextSettings = { + ...current, + themeOverrides: cloneThemeOverrides(themeOverrides), + }; - return writeBoardSettings(boardRoot, nextSettings); + return writeBoardSettings(boardRoot, nextSettings); + }); } async function updateBoardSettings(boardRoot, partialSettings = {}) { - const current = await readBoardSettings(boardRoot, { ensureFile: true }); - const nextSettings = { - ...current, - ...partialSettings, - }; + return withFileTransaction(getPrimarySettingsPath(boardRoot), async () => { + const current = await readBoardSettingsForMutation(boardRoot); + const nextSettings = { + ...current, + ...partialSettings, + }; - if ('labels' in partialSettings) { - nextSettings.labels = partialSettings.labels; - } + if ('labels' in partialSettings) { + nextSettings.labels = partialSettings.labels; + } - if ('colorScheme' in partialSettings) { - nextSettings.colorScheme = typeof partialSettings.colorScheme === 'string' - ? partialSettings.colorScheme - : ''; - } + if ('colorScheme' in partialSettings) { + nextSettings.colorScheme = typeof partialSettings.colorScheme === 'string' + ? partialSettings.colorScheme + : ''; + } - if ('themeOverrides' in partialSettings) { - nextSettings.themeOverrides = cloneThemeOverrides(partialSettings.themeOverrides); - } + if ('themeOverrides' in partialSettings) { + nextSettings.themeOverrides = cloneThemeOverrides(partialSettings.themeOverrides); + } - if ('workflow' in partialSettings) { - nextSettings.workflow = cloneWorkflowSettings(partialSettings.workflow); - } + if ('workflow' in partialSettings) { + nextSettings.workflow = cloneWorkflowSettings(partialSettings.workflow); + } - if ('externalPublishedCalendar' in partialSettings) { - nextSettings.externalPublishedCalendar = cloneExternalPublishedCalendarSettings(partialSettings.externalPublishedCalendar); - } + if ('externalPublishedCalendar' in partialSettings) { + nextSettings.externalPublishedCalendar = cloneExternalPublishedCalendarSettings(partialSettings.externalPublishedCalendar); + } - if ('obsidianBase' in partialSettings) { - nextSettings.obsidianBase = cloneObsidianBaseSettings(partialSettings.obsidianBase); - } + if ('obsidianBase' in partialSettings) { + nextSettings.obsidianBase = cloneObsidianBaseSettings(partialSettings.obsidianBase); + } - return writeBoardSettings(boardRoot, nextSettings); + return writeBoardSettings(boardRoot, nextSettings); + }); } async function readLegacyBoardAppSettings(boardRoot) { diff --git a/lib/boardSnapshot.js b/lib/boardSnapshot.js index 58b041f..6653f9f 100644 --- a/lib/boardSnapshot.js +++ b/lib/boardSnapshot.js @@ -70,7 +70,7 @@ async function listBoardDirectories(boardRoot, options = {}) { const includeArchive = options.includeArchive === true; const entries = await withFileReadLimit(() => fs.readdir(boardRoot, { withFileTypes: true })); return entries - .filter((entry) => entry.isDirectory()) + .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.')) .map((entry) => entry.name) .filter((entryName) => includeArchive || entryName !== ARCHIVE_DIRECTORY_NAME) .sort(compareNames); @@ -79,7 +79,7 @@ async function listBoardDirectories(boardRoot, options = {}) { async function listMarkdownCardFileNames(listPath) { const entries = await withFileReadLimit(() => fs.readdir(listPath, { withFileTypes: true })); return entries - .filter((entry) => entry.isFile() && entry.name.endsWith('.md')) + .filter((entry) => entry.isFile() && !entry.name.startsWith('.') && entry.name.endsWith('.md')) .map((entry) => entry.name) .sort(compareNames); } diff --git a/lib/cardFrontmatter.js b/lib/cardFrontmatter.js index 3851362..5ed8bd6 100644 --- a/lib/cardFrontmatter.js +++ b/lib/cardFrontmatter.js @@ -2,9 +2,10 @@ const fs = require('fs').promises; const path = require('path'); const yaml = require('js-yaml'); const { atomicWriteFile } = require('./atomicFile'); +const { withFileTransaction } = require('./fileTransaction'); const LEGACY_DELIMITER = '**********'; -const YAML_FRONTMATTER_REGEX = /^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/; +const YAML_FRONTMATTER_REGEX = /^---[ \t]*\r?\n(?:([\s\S]*?)\r?\n)?---(\r?\n|$)/; const ORDERED_KEYS = [ 'title', 'start', @@ -186,14 +187,20 @@ function deriveTitleFromPath(filePath) { return withoutOrderPrefix || 'Untitled'; } -function parseYamlCard(rawContent) { - const match = rawContent.match(YAML_FRONTMATTER_REGEX); +function stripBom(rawContent) { + const source = typeof rawContent === 'string' ? rawContent : String(rawContent || ''); + return source.startsWith('\uFEFF') ? source.slice(1) : source; +} + +function parseYamlCard(rawContent, options = {}) { + const cleanContent = stripBom(rawContent); + const match = cleanContent.match(YAML_FRONTMATTER_REGEX); if (!match) { return null; } - const yamlSource = match[1]; - const body = rawContent.slice(match[0].length); + const yamlSource = match[1] || ''; + const body = cleanContent.slice(match[0].length); let frontmatter = {}; if (yamlSource.trim()) { @@ -202,7 +209,10 @@ function parseYamlCard(rawContent) { if (isObject(parsed)) { frontmatter = parsed; } - } catch { + } catch (error) { + if (options.strict) { + throw new Error(`Invalid YAML frontmatter: ${error && error.message ? error.message : String(error)}`); + } return null; } } @@ -279,8 +289,9 @@ function parseLegacyCard(rawContent) { }; } -function parseCardContent(rawContent) { - return parseYamlCard(rawContent) || parseLegacyCard(rawContent); +function parseCardContent(rawContent, options = {}) { + const cleanContent = stripBom(rawContent); + return parseYamlCard(cleanContent, options) || parseLegacyCard(cleanContent); } function frontmatterForWrite(frontmatter, filePath) { @@ -364,20 +375,28 @@ async function writeCard(filePath, card = {}) { } async function updateFrontmatter(filePath, partialFrontmatter = {}) { - const currentCard = await readCard(filePath); - const nextFrontmatter = { - ...currentCard.frontmatter, - ...(isObject(partialFrontmatter) ? partialFrontmatter : {}), - }; + return withFileTransaction(filePath, async () => { + const rawContent = await fs.readFile(filePath, 'utf8'); + const parsed = parseCardContent(rawContent, { strict: true }); + const currentFrontmatter = normalizeFrontmatter(parsed.frontmatter); + if (!currentFrontmatter.title) { + currentFrontmatter.title = deriveTitleFromPath(filePath); + } - const normalized = normalizeFrontmatter(nextFrontmatter); + const nextFrontmatter = { + ...currentFrontmatter, + ...(isObject(partialFrontmatter) ? partialFrontmatter : {}), + }; - await writeCard(filePath, { - frontmatter: normalized, - body: currentCard.body, - }); + const normalized = normalizeFrontmatter(nextFrontmatter); - return normalized; + await writeCard(filePath, { + frontmatter: normalized, + body: parsed.body, + }); + + return normalized; + }); } module.exports = { diff --git a/lib/cardOrdering.js b/lib/cardOrdering.js index 9ea02fd..ffa1529 100644 --- a/lib/cardOrdering.js +++ b/lib/cardOrdering.js @@ -1,8 +1,9 @@ const fs = require('fs').promises; const path = require('path'); const yaml = require('js-yaml'); -const { atomicWriteFile } = require('./atomicFile'); +const { atomicWriteFile, renameWithWindowsRetry } = require('./atomicFile'); const cardFrontmatter = require('./cardFrontmatter'); +const { mapFileReads } = require('./fileReadQueue'); const { getIncompleteTaskListDueDates } = require('./taskList'); const { assertNoListOrderRecovery, prepareListOrderRecovery } = require('./listOrderRecovery'); @@ -48,11 +49,15 @@ function applyNumberedPrefix(entryName, prefix) { async function listCardFiles(listPath) { const entries = await fs.readdir(listPath, { withFileTypes: true }); return entries - .filter((entry) => entry.isFile() && entry.name.endsWith('.md')) + .filter((entry) => entry.isFile() && !entry.name.startsWith('.') && entry.name.endsWith('.md')) .map((entry) => entry.name) .sort((left, right) => cardSortCollator.compare(left, right)); } +function pathKey(targetPath) { + return process.platform === 'win32' ? targetPath.toLowerCase() : targetPath; +} + async function pathExists(targetPath) { try { await fs.access(targetPath); @@ -68,7 +73,7 @@ async function pathExists(targetPath) { async function restoreRenameIfPossible(fromPath, toPath) { try { if ((await pathExists(fromPath)) && !(await pathExists(toPath))) { - await fs.rename(fromPath, toPath); + await renameWithWindowsRetry(fromPath, toPath); } } catch { // Best-effort rollback only; keep the original failure as the actionable error. @@ -83,7 +88,7 @@ async function getDirectoryEntryNames(directoryPath, predicate) { .sort((left, right) => cardSortCollator.compare(left, right)); } -async function getExistingOrderedSources(sourcePaths) { +async function getExistingOrderedSources(sourcePaths, knownExistingKeys = null) { const sources = []; const seen = new Set(); @@ -94,15 +99,16 @@ async function getExistingOrderedSources(sourcePaths) { } const normalizedPath = path.resolve(sourcePathText); - if (seen.has(normalizedPath)) { + const normalizedKey = pathKey(normalizedPath); + if (seen.has(normalizedKey)) { continue; } - if (!(await pathExists(normalizedPath))) { + if (!(knownExistingKeys && knownExistingKeys.has(normalizedKey)) && !(await pathExists(normalizedPath))) { continue; } - seen.add(normalizedPath); + seen.add(normalizedKey); sources.push(normalizedPath); } @@ -112,10 +118,11 @@ async function getExistingOrderedSources(sourcePaths) { function assertNoDuplicateFinalNames(finalNames) { const seen = new Set(); for (const finalName of finalNames) { - if (seen.has(finalName)) { + const collisionKey = process.platform === 'win32' ? finalName.toLowerCase() : finalName; + if (seen.has(collisionKey)) { throw new Error(`ORDER_COLLISION:${finalName}`); } - seen.add(finalName); + seen.add(collisionKey); } } @@ -130,14 +137,16 @@ async function reorderEntriesInDirectory({ const resolvedDirectoryPath = path.resolve(directoryPath); const currentEntries = Array.isArray(currentEntryNames) ? currentEntryNames : []; const currentPaths = currentEntries.map((entryName) => path.join(resolvedDirectoryPath, entryName)); - const currentPathSet = new Set(currentPaths); - const finalSources = await getExistingOrderedSources(orderedSourcePaths); - const finalSourceSet = new Set(finalSources); + const currentPathByKey = new Map(currentPaths.map((entryPath) => [pathKey(entryPath), entryPath])); + const finalSources = (await getExistingOrderedSources(orderedSourcePaths, currentPathByKey)) + .map((sourcePath) => currentPathByKey.get(pathKey(sourcePath)) || sourcePath); + const finalSourceKeySet = new Set(finalSources.map((sourcePath) => pathKey(sourcePath))); for (const currentPath of currentPaths) { - if (!finalSourceSet.has(currentPath)) { + const key = pathKey(currentPath); + if (!finalSourceKeySet.has(key)) { finalSources.push(currentPath); - finalSourceSet.add(currentPath); + finalSourceKeySet.add(key); } } @@ -147,7 +156,7 @@ async function reorderEntriesInDirectory({ originalSourcePath: sourcePath, finalEntryName: finalNames[index], finalPath: path.join(resolvedDirectoryPath, finalNames[index]), - wasExistingEntry: currentPathSet.has(sourcePath), + wasExistingEntry: currentPathByKey.has(pathKey(sourcePath)), })); const changedCurrentPathSet = new Set( finalEntries @@ -168,7 +177,7 @@ async function reorderEntriesInDirectory({ }); const recovery = prepareRecovery && plannedStages.length ? await prepareRecovery(finalEntries, plannedStages) : null; - const rename = recovery ? recovery.rename : (...args) => fs.rename(...args); + const rename = recovery ? recovery.rename : (from, to) => renameWithWindowsRetry(from, to); try { for (const stagedEntry of plannedStages) { @@ -192,7 +201,7 @@ async function reorderEntriesInDirectory({ finalEntryName, finalPath, restorePath: stagedEntry ? stagedEntry.tempPath : sourcePath, - wasExistingEntry: currentPathSet.has(sourcePath), + wasExistingEntry: currentPathByKey.has(pathKey(sourcePath)), }); } if (commit) await commit(); @@ -231,57 +240,16 @@ async function reorderEntriesInDirectory({ async function insertCardFileAtTop(listPath, sourcePath, sourceFileName) { const resolvedListPath = path.resolve(listPath); const resolvedSourcePath = path.resolve(sourcePath); - const existingCardFiles = (await listCardFiles(resolvedListPath)) - .filter((fileName) => path.resolve(path.join(resolvedListPath, fileName)) !== resolvedSourcePath); - const stagedCards = []; - const tempToken = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; - const insertedFileName = applyCardPrefix(sourceFileName, 0); - const insertedPath = path.join(resolvedListPath, insertedFileName); - const finalizedCards = []; - - try { - for (let index = 0; index < existingCardFiles.length; index += 1) { - const originalFileName = existingCardFiles[index]; - const tempFileName = `__sbtmp-${tempToken}-${String(index).padStart(3, '0')}.tmp`; - await fs.rename( - path.join(resolvedListPath, originalFileName), - path.join(resolvedListPath, tempFileName), - ); - stagedCards.push({ originalFileName, tempFileName }); - } - - await fs.rename(resolvedSourcePath, insertedPath); - - for (let index = 0; index < stagedCards.length; index += 1) { - const stagedCard = stagedCards[index]; - const finalFileName = applyCardPrefix(stagedCard.originalFileName, index + 1); - await fs.rename( - path.join(resolvedListPath, stagedCard.tempFileName), - path.join(resolvedListPath, finalFileName), - ); - finalizedCards.push({ originalFileName: stagedCard.originalFileName, finalFileName }); - } - } catch (error) { - await restoreRenameIfPossible(insertedPath, resolvedSourcePath); - - for (const finalizedCard of finalizedCards.slice().reverse()) { - await restoreRenameIfPossible( - path.join(resolvedListPath, finalizedCard.finalFileName), - path.join(resolvedListPath, finalizedCard.originalFileName), - ); - } - - for (const stagedCard of stagedCards.slice().reverse()) { - await restoreRenameIfPossible( - path.join(resolvedListPath, stagedCard.tempFileName), - path.join(resolvedListPath, stagedCard.originalFileName), - ); - } - - throw error; - } + const currentCardFiles = await listCardFiles(resolvedListPath); + const insertedFileName = applyCardPrefix(sourceFileName || path.basename(resolvedSourcePath), 0); + const finalizedEntries = await reorderEntriesInDirectory({ + directoryPath: resolvedListPath, + orderedSourcePaths: [resolvedSourcePath], + currentEntryNames: currentCardFiles, + applyPrefix: (entryName, index) => (index === 0 ? insertedFileName : applyCardPrefix(entryName, index)), + }); - return insertedFileName; + return finalizedEntries[0] ? finalizedEntries[0].finalEntryName : insertedFileName; } async function reorderCardFilesInList(listPath, orderedCardPaths) { @@ -318,7 +286,7 @@ async function reorderCardFilesInListByDueDate(listPath, options = {}) { ? options.readCard : cardFrontmatter.readCard; const currentCardFiles = await listCardFiles(resolvedListPath); - const orderedCards = await Promise.all(currentCardFiles.map(async (cardFile, originalIndex) => { + const orderedCards = await mapFileReads(currentCardFiles, async (cardFile, originalIndex) => { const sourcePath = path.join(resolvedListPath, cardFile); const card = await readCard(sourcePath); @@ -327,7 +295,7 @@ async function reorderCardFilesInListByDueDate(listPath, options = {}) { dueDate: getCardDueDateForOrdering(card), originalIndex, }; - })); + }); orderedCards.sort((left, right) => { if (left.dueDate && right.dueDate && left.dueDate !== right.dueDate) { @@ -374,9 +342,10 @@ async function prepareListOrderSettings(boardRoot, entries) { return null; }); if (original === null) continue; - const match = original.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/); + const cleanOriginal = original.replace(/^\uFEFF/, ''); + const match = cleanOriginal.match(/^---[ \t]*\r?\n(?:([\s\S]*?)\r?\n)?---(?:\r?\n|$)/); if (!match) return null; - const settings = yaml.load(match[1], { schema: yaml.JSON_SCHEMA }); + const settings = yaml.load(match[1] || '', { schema: yaml.JSON_SCHEMA }); let changed = false; for (const key of ['completedListNames', 'completedLists', 'ignoredCompletedListNames']) { if (!Array.isArray(settings?.workflow?.[key])) continue; @@ -387,7 +356,7 @@ async function prepareListOrderSettings(boardRoot, entries) { }); } if (!changed) return null; - const next = `---\n${yaml.dump(settings, { schema: yaml.JSON_SCHEMA, lineWidth: -1, noRefs: true })}---\n${original.slice(match[0].length)}`; + const next = `---\n${yaml.dump(settings, { schema: yaml.JSON_SCHEMA, lineWidth: -1, noRefs: true })}---\n${cleanOriginal.slice(match[0].length)}`; return async () => { if (await fs.readFile(file, 'utf8') !== original) throw new Error('Board settings changed during list reorder; retry.'); await atomicWriteFile(file, next, 'utf8'); @@ -401,7 +370,7 @@ async function reorderListDirectories(boardRoot, orderedListPaths) { await assertNoListOrderRecovery(resolvedBoardRoot); const currentListDirectories = await getDirectoryEntryNames( resolvedBoardRoot, - (entry) => entry.isDirectory() && entry.name !== 'XXX-Archive', + (entry) => entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'XXX-Archive', ); if (currentListDirectories.some((name) => name.startsWith('__sbtmp-'))) { throw new Error('Unfinished list renames were found. Preserve the board folders and recover their original names before reordering.'); diff --git a/lib/cardTimestamps.js b/lib/cardTimestamps.js index ea5d874..76cc4a0 100644 --- a/lib/cardTimestamps.js +++ b/lib/cardTimestamps.js @@ -11,7 +11,8 @@ function normalizeTimestamp(value) { } if (value instanceof Date) { - return Number.isNaN(value.getTime()) ? '' : value.toISOString(); + const time = value.getTime(); + return Number.isNaN(time) || time <= 0 ? '' : value.toISOString(); } if (typeof value === 'number') { diff --git a/lib/cliApp.js b/lib/cliApp.js index 928a537..9fb6604 100644 --- a/lib/cliApp.js +++ b/lib/cliApp.js @@ -1,13 +1,7 @@ const fs = require('fs').promises; -const automation = require('./automation'); const { getBuildInfo, formatBuildInfo } = require('./buildInfo'); const path = require('path'); const boardLabels = require('./boardLabels'); -const { - importTrello, - importObsidian, - importTasksMd, -} = require('./importers'); const { archiveCard, archiveList, @@ -34,15 +28,26 @@ const { getCurrentBoard, setCurrentBoard, } = require('./cliState'); -const { createBoard: createBoardOnDisk } = require('./boardCreation'); -const { - discoverBoards, - readDesktopOpenBoardsState, - readDesktopTrustedBoardRoots, -} = require('./boardDiscovery'); const CLI_GROUPS = new Set(['use', 'boards', 'lists', 'cards', 'archive', 'settings', 'import']); const CLI_NEAR_MISSES = new Set(['board', 'list', 'card']); +const BOOLEAN_CLI_FLAGS = new Set([ + 'help', + 'version', + 'json', + 'include-archive', + 'dry-run', + 'clear-labels', + 'timestamp', + 'no-welcome', + 'use', +]); + +function sameBoardPath(left, right) { + const a = path.resolve(String(left || '')); + const b = path.resolve(String(right || '')); + return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b; +} const CARD_SUBCOMMANDS = new Set(['list', 'read', 'create', 'edit', 'duplicate', 'notes', 'archive', 'reorder']); const IMPORT_SUBCOMMANDS = new Set(['trello', 'obsidian', 'tasksmd']); const APP_PASSTHROUGH_PREFIXES = ['-psn_']; @@ -82,6 +87,8 @@ function parseArgv(argv) { if (equalIndex >= 0) { key = arg.slice(2, equalIndex); value = arg.slice(equalIndex + 1); + } else if (BOOLEAN_CLI_FLAGS.has(key)) { + value = true; } else { const nextArg = argv[index + 1]; if (nextArg != null && !nextArg.startsWith('--')) { @@ -743,12 +750,18 @@ async function runBoardsListCommand(positionals, options, context, usage) { assertAllowedOptions(options, ['json', 'board'], usage); assertNoExtraPositionals(positionals, 0, usage); + const { + discoverBoards, + readDesktopOpenBoardsState, + readDesktopTrustedBoardRoots, + } = require('./boardDiscovery'); + const explicitBoard = getOption(options, 'board'); - const currentBoardRoot = explicitBoard - ? path.resolve(String(explicitBoard)) - : await getCurrentBoard(context.stateOptions); - const trustedBoardRoots = await readDesktopTrustedBoardRoots(); - const openBoardsState = await readDesktopOpenBoardsState(); + const [currentBoardRoot, trustedBoardRoots, openBoardsState] = await Promise.all([ + explicitBoard ? Promise.resolve(path.resolve(String(explicitBoard))) : getCurrentBoard(context.stateOptions), + readDesktopTrustedBoardRoots(context.stateOptions), + readDesktopOpenBoardsState(context.stateOptions), + ]); const discovery = await discoverBoards({ trustedBoardRoots, openBoardRoots: openBoardsState.openBoardRoots, @@ -779,6 +792,7 @@ async function runBoardsCommand(action, positionals, options, context) { } if (['rename', 'move', 'duplicate'].includes(action)) { + const automation = require('./automation'); const commandUsage = `Usage: signboard boards ${action} ${action === 'rename' ? '' : '--parent '}${action === 'duplicate' ? ' --name ' : ''} [--board ] [--json]`; assertAllowedOptions(options, ['board', 'json', ...(action === 'rename' ? [] : ['parent']), ...(action === 'duplicate' ? ['name'] : [])], commandUsage); assertNoExtraPositionals(positionals, action === 'rename' ? 1 : 0, commandUsage); @@ -787,7 +801,7 @@ async function runBoardsCommand(action, positionals, options, context) { const result = action === 'duplicate' ? await automation.copyBoard(boardRoot, path.resolve(String(getOption(options, 'parent'))), getOption(options, 'name')) : await automation.relocateBoard(boardRoot, { name: positionals[0], parent: getOption(options, 'parent') }); - if (action !== 'duplicate' && (await getCurrentBoard(context.stateOptions)) === path.resolve(boardRoot)) { + if (action !== 'duplicate' && sameBoardPath(await getCurrentBoard(context.stateOptions), boardRoot)) { await setCurrentBoard(result.newBoardRoot, context.stateOptions); } return writeOperationResult(context, options, result, `Board ${action} complete: ${result.newBoardRoot || result.boardRoot}`); @@ -800,6 +814,7 @@ async function runBoardsCommand(action, positionals, options, context) { assertAllowedOptions(options, ['json', 'use', 'no-welcome', 'parent', 'parent-root', 'name', 'board-name'], usage); assertNoExtraPositionals(positionals, 1, usage); + const { createBoard: createBoardOnDisk } = require('./boardCreation'); const boardRoot = resolveBoardCreateRoot(positionals, options, usage); const created = await createBoardOnDisk(boardRoot, { seedWelcomeCard: getOption(options, 'no-welcome') !== true, @@ -858,6 +873,7 @@ async function runListsCommand(action, positionals, options, context) { const usage = 'Usage: signboard lists reorder --list [--list ...] [--json]'; assertAllowedOptions(options, ['list', 'json', 'board'], usage); assertNoExtraPositionals(positionals, 0, usage); + const automation = require('./automation'); const result = await automation.orderLists(boardRoot, getOptionList(options, 'list')); return writeOperationResult(context, options, result, 'List order saved.'); } @@ -957,6 +973,7 @@ async function runCardsCommand(action, positionals, options, context) { assertAllowedOptions(options, ['list', 'card', 'by', 'json', 'board'], usage); assertNoExtraPositionals(positionals, 0, usage); if (!getOption(options, 'list') || (getOption(options, 'by') && getOption(options, 'by') !== 'due')) throw new Error(usage); + const automation = require('./automation'); const result = await automation.orderCards(boardRoot, getOption(options, 'list'), getOptionList(options, 'card'), getOption(options, 'by') === 'due'); return writeOperationResult(context, options, result, 'Card order saved.'); } @@ -1346,6 +1363,7 @@ async function runSettingsCommand(action, positionals, options, context) { assertAllowedOptions(options, ['file', 'board', 'json'], usage); assertNoExtraPositionals(positionals, 0, usage); if (typeof getOption(options, 'file') !== 'string') throw new Error(usage); + const automation = require('./automation'); const patch = automation.validateSettingsPatch(JSON.parse(await fs.readFile(getOption(options, 'file'), 'utf8'))); const settings = await boardLabels.updateBoardSettings(boardRoot, patch); return writeOperationResult(context, options, { ok: true, boardRoot, settings }, 'Board settings updated.'); @@ -1364,6 +1382,7 @@ async function runImportCommand(action, positionals, options, context) { assertAllowedOptions(options, ['file', 'json', 'board'], 'Usage: signboard import trello --file [--json]'); assertNoExtraPositionals(positionals, 0, 'Usage: signboard import trello --file [--json]'); const sourcePath = normalizeImportPath(getOption(options, 'file'), '--file'); + const { importTrello } = require('./importers/trello'); const summary = await importTrello({ boardRoot, sourcePath, @@ -1379,12 +1398,16 @@ async function runImportCommand(action, positionals, options, context) { } if (action === 'tasksmd') { - assertAllowedOptions(options, ['source', 'json', 'board'], 'Usage: signboard import tasksmd --source [--json]'); - assertNoExtraPositionals(positionals, 0, 'Usage: signboard import tasksmd --source [--json]'); - const sourcePath = normalizeImportPath(getOption(options, 'source'), '--source'); + assertAllowedOptions(options, ['source', 'json', 'board'], 'Usage: signboard import tasksmd --source [--source ...] [--json]'); + assertNoExtraPositionals(positionals, 0, 'Usage: signboard import tasksmd --source [--source ...] [--json]'); + const sourcePaths = getOptionList(options, 'source').map((value) => normalizeImportPath(value, '--source')); + if (sourcePaths.length === 0) { + throw new Error('At least one --source path is required.'); + } + const { importTasksMd } = require('./importers/tasksmd'); const summary = await importTasksMd({ boardRoot, - sourcePaths: [sourcePath], + sourcePaths, }); if (getOption(options, 'json') === true) { @@ -1403,6 +1426,7 @@ async function runImportCommand(action, positionals, options, context) { throw new Error('At least one --source path is required.'); } + const { importObsidian } = require('./importers/obsidian'); const summary = await importObsidian({ boardRoot, sourcePaths, diff --git a/lib/cliBoard.js b/lib/cliBoard.js index fa2b5c7..d37a510 100644 --- a/lib/cliBoard.js +++ b/lib/cliBoard.js @@ -1,6 +1,7 @@ const fs = require('fs').promises; const path = require('path'); const { mapFileReads } = require('./fileReadQueue'); +const { withFileTransaction } = require('./fileTransaction'); const { renameManagedDirectory } = require('./directoryRename'); const cardFrontmatter = require('./cardFrontmatter'); const boardLabels = require('./boardLabels'); @@ -16,11 +17,6 @@ const { const { parseIsoDateStringToLocalDate, getTaskListMetadata, - getTaskListSummary, - getTaskListStartDates, - getIncompleteTaskListStartDates, - getTaskListDueDates, - getIncompleteTaskListDueDates, } = require('./taskList'); const ARCHIVE_DIRECTORY_NAME = 'XXX-Archive'; @@ -34,14 +30,7 @@ const listSortCollator = new Intl.Collator(undefined, { ignorePunctuation: true, localeMatcher: 'lookup', }); - -const cardSortCollator = new Intl.Collator(undefined, { - usage: 'sort', - sensitivity: 'base', - numeric: true, - ignorePunctuation: true, - localeMatcher: 'lookup', -}); +const cardSortCollator = listSortCollator; function normalizeBoardRoot(boardRoot) { const normalized = String(boardRoot || '').trim(); @@ -331,10 +320,10 @@ async function listLists(boardRoot, options = {}) { const includeArchive = options.includeArchive === true; const withCardCounts = options.withCardCounts !== false; const entries = await fs.readdir(resolvedBoardRoot, { withFileTypes: true }); - const lists = []; + const rawLists = []; for (const entry of entries) { - if (!entry.isDirectory()) { + if (!entry.isDirectory() || entry.name.startsWith('.')) { continue; } @@ -345,24 +334,26 @@ async function listLists(boardRoot, options = {}) { } const listPath = path.join(resolvedBoardRoot, directoryName); - let cardCount = null; - - if (withCardCounts) { - const cardEntries = await fs.readdir(listPath, { withFileTypes: true }); - cardCount = cardEntries.filter((cardEntry) => cardEntry.isFile() && cardEntry.name.endsWith('.md')).length; - } - - lists.push({ + rawLists.push({ directoryName, displayName: getListDisplayName(directoryName), path: listPath, isArchive, - cardCount, + cardCount: null, }); } - lists.sort((left, right) => listSortCollator.compare(left.directoryName, right.directoryName)); - return lists; + if (withCardCounts && rawLists.length > 0) { + await mapFileReads(rawLists, async (listItem) => { + const cardEntries = await fs.readdir(listItem.path, { withFileTypes: true }); + listItem.cardCount = cardEntries.filter( + (cardEntry) => cardEntry.isFile() && !cardEntry.name.startsWith('.') && cardEntry.name.endsWith('.md'), + ).length; + }); + } + + rawLists.sort((left, right) => listSortCollator.compare(left.directoryName, right.directoryName)); + return rawLists; } function normalizeMatchValue(value) { @@ -401,7 +392,7 @@ function resolveUniqueMatch(items, ref, matchers, label) { async function resolveList(boardRoot, listRef, options = {}) { const lists = await listLists(boardRoot, { includeArchive: options.includeArchive === true, - withCardCounts: options.withCardCounts, + withCardCounts: options.withCardCounts === true, }); return resolveListFromEntries(lists, listRef); @@ -556,15 +547,69 @@ async function loadCardRecord(boardRoot, listEntry, fileName) { }; } +function resolveLabelIdsFromSettings(boardSettings, labelRefs) { + const labels = Array.isArray(boardSettings && boardSettings.labels) ? boardSettings.labels : []; + + return labelRefs.map((labelRef) => { + const normalizedRef = normalizeMatchValue(labelRef); + if (!normalizedRef) { + throw new Error('Label reference cannot be empty.'); + } + + const exactById = labels.find((label) => normalizeMatchValue(label.id) === normalizedRef); + if (exactById) { + return exactById.id; + } + + const exactByName = labels.find((label) => normalizeMatchValue(label.name) === normalizedRef); + if (exactByName) { + return exactByName.id; + } + + const partialMatches = labels.filter((label) => ( + normalizeMatchValue(label.id).includes(normalizedRef) || + normalizeMatchValue(label.name).includes(normalizedRef) + )); + + if (partialMatches.length === 1) { + return partialMatches[0].id; + } + + if (partialMatches.length > 1) { + throw new Error(`Ambiguous label reference "${labelRef}".`); + } + + throw new Error(`Could not find label: ${labelRef}`); + }); +} + +function labelNamesFromSettings(boardSettings, labelIds) { + const labels = Array.isArray(boardSettings && boardSettings.labels) ? boardSettings.labels : []; + const labelMap = new Map(labels.map((label) => [label.id, label.name])); + return (Array.isArray(labelIds) ? labelIds : []) + .map((labelId) => labelMap.get(labelId) || labelId) + .sort((left, right) => listSortCollator.compare(left, right)); +} + async function listCards(boardRoot, options = {}) { const resolvedBoardRoot = await ensureBoardRoot(boardRoot); const includeArchive = options.includeArchive === true; const listRefs = Array.isArray(options.listRefs) ? options.listRefs.filter(Boolean) : (options.listRef ? [options.listRef] : []); - const selectedLists = listRefs.length > 0 - ? await Promise.all(listRefs.map((listRef) => resolveList(resolvedBoardRoot, listRef, { includeArchive }))) - : await listLists(resolvedBoardRoot, { includeArchive, withCardCounts: false }); + const allLists = await listLists(resolvedBoardRoot, { includeArchive, withCardCounts: false }); + let selectedLists = allLists; + if (listRefs.length > 0) { + const seenListPaths = new Set(); + selectedLists = []; + for (const listRef of listRefs) { + const resolvedList = resolveListFromEntries(allLists, listRef); + if (!seenListPaths.has(resolvedList.path)) { + seenListPaths.add(resolvedList.path); + selectedLists.push(resolvedList); + } + } + } const boardSettings = await boardLabels.readBoardSettings(resolvedBoardRoot, { ensureFile: false }); const labelMap = new Map(boardSettings.labels.map((label) => [label.id, label.name])); const dueMatcher = buildDueMatcher(options.due); @@ -572,22 +617,41 @@ async function listCards(boardRoot, options = {}) { const taskStatus = normalizeTaskStatus(options.taskStatus, options.due); const labelMode = String(options.labelMode || 'any').toLowerCase() === 'all' ? 'all' : 'any'; const labelIds = options.labelRefs && options.labelRefs.length > 0 - ? await resolveLabelIds(resolvedBoardRoot, options.labelRefs) + ? resolveLabelIdsFromSettings(boardSettings, options.labelRefs) : []; const records = []; for (const listEntry of selectedLists) { - const entries = await fs.readdir(listEntry.path, { withFileTypes: true }); + let entries; + try { + entries = await fs.readdir(listEntry.path, { withFileTypes: true }); + } catch (error) { + if (error && error.code === 'ENOENT') { + continue; + } + throw error; + } const cardNames = entries - .filter((entry) => entry.isFile() && entry.name.endsWith('.md')) + .filter((entry) => entry.isFile() && !entry.name.startsWith('.') && entry.name.endsWith('.md')) .map((entry) => entry.name) .sort((left, right) => cardSortCollator.compare(left, right)); - const loaded = await mapFileReads( - cardNames, (fileName) => loadCardRecord(resolvedBoardRoot, listEntry, fileName) - ); + const loaded = await mapFileReads(cardNames, async (fileName) => { + try { + return await loadCardRecord(resolvedBoardRoot, listEntry, fileName); + } catch (error) { + if (error && error.code === 'ENOENT') { + return null; + } + throw error; + } + }); for (const record of loaded) { + if (!record) { + continue; + } + const normalizedLabelNames = record.labels .map((labelId) => labelMap.get(labelId) || labelId) .sort((left, right) => listSortCollator.compare(left, right)); @@ -623,39 +687,58 @@ async function listCards(boardRoot, options = {}) { } const sortBy = String(options.sort || 'list').toLowerCase(); + const sortKeyByRecord = new Map(); + if (sortBy === 'due') { + for (const record of records) { + sortKeyByRecord.set(record, getEarliestDueDate(record, dueSource, taskStatus)); + } + } else if (sortBy === 'updated' || sortBy === 'updated-newest' || sortBy === 'updated-oldest') { + for (const record of records) { + const ts = getCardSortTimestamp(record, 'updatedAt'); + sortKeyByRecord.set(record, ts ? Date.parse(ts) : Number.NaN); + } + } else if (sortBy === 'created' || sortBy === 'created-oldest' || sortBy === 'created-newest') { + for (const record of records) { + const ts = getCardSortTimestamp(record, 'createdAt'); + sortKeyByRecord.set(record, ts ? Date.parse(ts) : Number.NaN); + } + } + records.sort((left, right) => { if (sortBy === 'title') { return listSortCollator.compare(left.title, right.title); } if (sortBy === 'due') { - const leftEarliest = getEarliestDueDate(left, dueSource, taskStatus); - const rightEarliest = getEarliestDueDate(right, dueSource, taskStatus); - const dueComparison = compareOptionalIsoDates(leftEarliest, rightEarliest); + const dueComparison = compareOptionalIsoDates(sortKeyByRecord.get(left), sortKeyByRecord.get(right)); if (dueComparison !== 0) { return dueComparison; } } if (sortBy === 'updated' || sortBy === 'updated-newest' || sortBy === 'updated-oldest') { - const updatedComparison = compareOptionalTimestamps( - getCardSortTimestamp(left, 'updatedAt'), - getCardSortTimestamp(right, 'updatedAt'), - sortBy !== 'updated-oldest', - ); - if (updatedComparison !== 0) { - return updatedComparison; + const leftMs = sortKeyByRecord.get(left); + const rightMs = sortKeyByRecord.get(right); + const leftValid = Number.isFinite(leftMs); + const rightValid = Number.isFinite(rightMs); + if (leftValid !== rightValid) { + return leftValid ? -1 : 1; + } + if (leftValid && leftMs !== rightMs) { + return sortBy !== 'updated-oldest' ? rightMs - leftMs : leftMs - rightMs; } } if (sortBy === 'created' || sortBy === 'created-oldest' || sortBy === 'created-newest') { - const createdComparison = compareOptionalTimestamps( - getCardSortTimestamp(left, 'createdAt'), - getCardSortTimestamp(right, 'createdAt'), - sortBy === 'created-newest', - ); - if (createdComparison !== 0) { - return createdComparison; + const leftMs = sortKeyByRecord.get(left); + const rightMs = sortKeyByRecord.get(right); + const leftValid = Number.isFinite(leftMs); + const rightValid = Number.isFinite(rightMs); + if (leftValid !== rightValid) { + return leftValid ? -1 : 1; + } + if (leftValid && leftMs !== rightMs) { + return sortBy === 'created-newest' ? rightMs - leftMs : leftMs - rightMs; } } @@ -687,39 +770,7 @@ function getEarliestDueDate(record, dueSource = 'any', taskStatus = 'any') { async function resolveLabelIds(boardRoot, labelRefs) { const boardSettings = await boardLabels.readBoardSettings(boardRoot, { ensureFile: false }); - const labels = Array.isArray(boardSettings.labels) ? boardSettings.labels : []; - - return labelRefs.map((labelRef) => { - const normalizedRef = normalizeMatchValue(labelRef); - if (!normalizedRef) { - throw new Error('Label reference cannot be empty.'); - } - - const exactById = labels.find((label) => normalizeMatchValue(label.id) === normalizedRef); - if (exactById) { - return exactById.id; - } - - const exactByName = labels.find((label) => normalizeMatchValue(label.name) === normalizedRef); - if (exactByName) { - return exactByName.id; - } - - const partialMatches = labels.filter((label) => ( - normalizeMatchValue(label.id).includes(normalizedRef) || - normalizeMatchValue(label.name).includes(normalizedRef) - )); - - if (partialMatches.length === 1) { - return partialMatches[0].id; - } - - if (partialMatches.length > 1) { - throw new Error(`Ambiguous label reference "${labelRef}".`); - } - - throw new Error(`Could not find label: ${labelRef}`); - }); + return resolveLabelIdsFromSettings(boardSettings, labelRefs); } async function resolveCard(boardRoot, options = {}) { @@ -730,20 +781,54 @@ async function resolveCard(boardRoot, options = {}) { throw new Error('card reference is required.'); } - // Exact filenames take precedence over title/partial matches. Resolve against - // the directory inventory to preserve case-insensitive ambiguity detection. - if (options.listRef && cardRef.toLowerCase().endsWith('.md')) { - const list = await resolveList(resolvedBoardRoot, options.listRef, { includeArchive, withCardCounts: false }); - const entries = await fs.readdir(list.path, { withFileTypes: true }); - const matches = entries.filter((entry) => entry.isFile() && entry.name.endsWith('.md') - && normalizeMatchValue(entry.name) === normalizeMatchValue(cardRef)); - if (matches.length > 1) throw new Error(`Ambiguous card reference "${cardRef}".`); - if (matches.length === 1) { - const record = await loadCardRecord(resolvedBoardRoot, list, matches[0].name); - const settings = await boardLabels.readBoardSettings(resolvedBoardRoot, { ensureFile: false }); - const labels = new Map(settings.labels.map((label) => [label.id, label.name])); - return { ...record, labelNames: record.labels.map((id) => labels.get(id) || id) - .sort((left, right) => listSortCollator.compare(left, right)) }; + // Exact filenames and exact 5-character card IDs take precedence over title/partial + // matches. Scan directory entries first so ID/filename lookups avoid reading unrelated cards. + const normalizedRef = normalizeMatchValue(cardRef); + const isExactFileRef = normalizedRef.endsWith('.md'); + const isExactCardIdRef = /^[a-z0-9]{5}$/.test(normalizedRef); + + if (isExactFileRef || isExactCardIdRef) { + const candidateLists = options.listRef + ? [await resolveList(resolvedBoardRoot, options.listRef, { includeArchive, withCardCounts: false })] + : await listLists(resolvedBoardRoot, { includeArchive, withCardCounts: false }); + + const matchedEntries = []; + await mapFileReads(candidateLists, async (listEntry) => { + let entries; + try { + entries = await fs.readdir(listEntry.path, { withFileTypes: true }); + } catch (error) { + if (error && error.code === 'ENOENT') { + return; + } + throw error; + } + for (const entry of entries) { + if (!entry.isFile() || entry.name.startsWith('.') || !entry.name.endsWith('.md')) { + continue; + } + const matched = isExactFileRef + ? normalizeMatchValue(entry.name) === normalizedRef + : normalizeMatchValue(getCardId(entry.name)) === normalizedRef; + if (matched) { + matchedEntries.push({ listEntry, fileName: entry.name }); + } + } + }); + + if (matchedEntries.length > 1) { + throw new Error(`Ambiguous card reference "${cardRef}".`); + } + if (matchedEntries.length === 1) { + const { listEntry, fileName } = matchedEntries[0]; + const [record, settings] = await Promise.all([ + loadCardRecord(resolvedBoardRoot, listEntry, fileName), + boardLabels.readBoardSettings(resolvedBoardRoot, { ensureFile: false }), + ]); + return { + ...record, + labelNames: labelNamesFromSettings(settings, record.labels), + }; } } @@ -800,7 +885,10 @@ function normalizeStartInput(startValue) { async function createCard(boardRoot, options = {}) { const resolvedBoardRoot = await ensureBoardRoot(boardRoot); - const listEntry = await resolveList(resolvedBoardRoot, options.listRef, { includeArchive: true }); + const [listEntry, boardSettings] = await Promise.all([ + resolveList(resolvedBoardRoot, options.listRef, { includeArchive: true }), + boardLabels.readBoardSettings(resolvedBoardRoot, { ensureFile: false }), + ]); const title = String(options.title || '').trim(); if (!title) { throw new Error('Card title is required.'); @@ -812,7 +900,7 @@ async function createCard(boardRoot, options = {}) { const start = normalizeStartInput(options.start); const due = normalizeDueInput(options.due); const labelIds = options.labelRefs && options.labelRefs.length > 0 - ? await resolveLabelIds(resolvedBoardRoot, options.labelRefs) + ? resolveLabelIdsFromSettings(boardSettings, options.labelRefs) : []; const frontmatter = obsidianIntegration.normalizeSignboardCardFrontmatter({ boardRoot: resolvedBoardRoot, @@ -841,15 +929,11 @@ async function createCard(boardRoot, options = {}) { start: start || '', due: due || '', labels: labelIds, - labelNames: await labelNamesForIds(resolvedBoardRoot, labelIds), + labelNames: labelNamesFromSettings(boardSettings, labelIds), frontmatter, body, timestamps: resolveCardTimestamps(frontmatter), - taskSummary: getTaskListSummary(body), - taskStartDates: getTaskListStartDates(body), - incompleteTaskStartDates: getIncompleteTaskListStartDates(body), - taskDueDates: getTaskListDueDates(body), - incompleteTaskDueDates: getIncompleteTaskListDueDates(body), + ...getTaskListMetadata(body), }; } @@ -858,25 +942,28 @@ async function createCard(boardRoot, options = {}) { body, }); - return loadCardRecord(resolvedBoardRoot, listEntry, fileName); + const created = await loadCardRecord(resolvedBoardRoot, listEntry, fileName); + return { + ...created, + labelNames: labelNamesFromSettings(boardSettings, created.labels), + }; } async function labelNamesForIds(boardRoot, labelIds) { const boardSettings = await boardLabels.readBoardSettings(boardRoot, { ensureFile: false }); - const labelMap = new Map(boardSettings.labels.map((label) => [label.id, label.name])); - return (Array.isArray(labelIds) ? labelIds : []) - .map((labelId) => labelMap.get(labelId) || labelId) - .sort((left, right) => listSortCollator.compare(left, right)); + return labelNamesFromSettings(boardSettings, labelIds); } async function duplicateCard(boardRoot, options = {}) { const resolvedBoardRoot = await ensureBoardRoot(boardRoot); - const sourceRecord = await resolveCard(resolvedBoardRoot, { - cardRef: options.cardRef, - listRef: options.fromListRef, - includeArchive: true, - }); - const sourceCard = await cardFrontmatter.readCard(sourceRecord.filePath); + const [sourceRecord, boardSettings] = await Promise.all([ + resolveCard(resolvedBoardRoot, { + cardRef: options.cardRef, + listRef: options.fromListRef, + includeArchive: true, + }), + boardLabels.readBoardSettings(resolvedBoardRoot, { ensureFile: false }), + ]); const targetList = options.targetListRef ? await resolveList(resolvedBoardRoot, options.targetListRef, { includeArchive: true }) : { @@ -884,23 +971,24 @@ async function duplicateCard(boardRoot, options = {}) { displayName: sourceRecord.listDisplayName, path: sourceRecord.listPath, }; - const sourceTitle = String(sourceCard.frontmatter?.title || sourceRecord.title || 'Untitled').trim() || 'Untitled'; + const sourceTitle = String(sourceRecord.frontmatter?.title || sourceRecord.title || 'Untitled').trim() || 'Untitled'; + const titlePrefix = options.titlePrefix !== undefined ? String(options.titlePrefix) : 'Copy of '; const title = Object.prototype.hasOwnProperty.call(options, 'title') ? String(options.title || '').trim() - : `${String(options.titlePrefix || 'Copy of ')}${sourceTitle}`.trim(); + : `${titlePrefix}${sourceTitle}`.trim(); if (!title) { throw new Error('Card title cannot be empty.'); } const removeLabelIds = options.removeLabelRefs && options.removeLabelRefs.length > 0 - ? new Set(await resolveLabelIds(resolvedBoardRoot, options.removeLabelRefs)) + ? new Set(resolveLabelIdsFromSettings(boardSettings, options.removeLabelRefs)) : new Set(); const addLabelIds = options.addLabelRefs && options.addLabelRefs.length > 0 - ? await resolveLabelIds(resolvedBoardRoot, options.addLabelRefs) + ? resolveLabelIdsFromSettings(boardSettings, options.addLabelRefs) : []; - const sourceLabels = Array.isArray(sourceCard.frontmatter?.labels) - ? sourceCard.frontmatter.labels.map((labelId) => String(labelId)) + const sourceLabels = Array.isArray(sourceRecord.frontmatter?.labels) + ? sourceRecord.frontmatter.labels.map((labelId) => String(labelId)) : []; const labelSet = new Set(options.clearLabels === true ? [] : sourceLabels); @@ -915,12 +1003,12 @@ async function duplicateCard(boardRoot, options = {}) { const labels = [...labelSet]; const body = Object.prototype.hasOwnProperty.call(options, 'body') ? String(options.body || '') - : sourceCard.body; + : sourceRecord.body; const prefix = await nextCardPrefix(targetList.path); const fileName = `${prefix}-${sanitizeCardSlug(title).slice(0, 25)}-${randomSuffix()}.md`; const filePath = path.join(targetList.path, fileName); const frontmatterSource = { - ...sourceCard.frontmatter, + ...sourceRecord.frontmatter, title, labels, }; @@ -960,15 +1048,11 @@ async function duplicateCard(boardRoot, options = {}) { start: String(frontmatter.start || ''), due: String(frontmatter.due || ''), labels, - labelNames: await labelNamesForIds(resolvedBoardRoot, labels), + labelNames: labelNamesFromSettings(boardSettings, labels), frontmatter, body, timestamps: resolveCardTimestamps(frontmatter), - taskSummary: getTaskListSummary(body), - taskStartDates: getTaskListStartDates(body), - incompleteTaskStartDates: getIncompleteTaskListStartDates(body), - taskDueDates: getTaskListDueDates(body), - incompleteTaskDueDates: getIncompleteTaskListDueDates(body), + ...getTaskListMetadata(body), }; } @@ -977,83 +1061,95 @@ async function duplicateCard(boardRoot, options = {}) { body, }); - return loadCardRecord(resolvedBoardRoot, targetList, fileName); + const duplicated = await loadCardRecord(resolvedBoardRoot, targetList, fileName); + return { + ...duplicated, + labelNames: labelNamesFromSettings(boardSettings, duplicated.labels), + }; } async function editCard(boardRoot, options = {}) { const resolvedBoardRoot = await ensureBoardRoot(boardRoot); - const cardRecord = await resolveCard(resolvedBoardRoot, { - cardRef: options.cardRef, - listRef: options.listRef, - includeArchive: true, - }); - const current = await cardFrontmatter.readCard(cardRecord.filePath); - const nextFrontmatter = { ...current.frontmatter }; - const currentLabels = Array.isArray(nextFrontmatter.labels) - ? nextFrontmatter.labels.map((labelId) => String(labelId)) - : []; - let nextBody = current.body; + const [cardRecord, boardSettings] = await Promise.all([ + resolveCard(resolvedBoardRoot, { + cardRef: options.cardRef, + listRef: options.listRef, + includeArchive: true, + }), + boardLabels.readBoardSettings(resolvedBoardRoot, { ensureFile: false }), + ]); - if (Object.prototype.hasOwnProperty.call(options, 'title')) { - const title = String(options.title || '').trim(); - if (!title) { - throw new Error('Card title cannot be empty.'); + const computeEditedCard = (current) => { + const nextFrontmatter = { ...current.frontmatter }; + const currentLabels = Array.isArray(nextFrontmatter.labels) + ? nextFrontmatter.labels.map((labelId) => String(labelId)) + : []; + let nextBody = current.body; + + if (Object.prototype.hasOwnProperty.call(options, 'title')) { + const title = String(options.title || '').trim(); + if (!title) { + throw new Error('Card title cannot be empty.'); + } + nextFrontmatter.title = title; } - nextFrontmatter.title = title; - } - if (Object.prototype.hasOwnProperty.call(options, 'body')) { - nextBody = String(options.body || ''); - } + if (Object.prototype.hasOwnProperty.call(options, 'body')) { + nextBody = String(options.body || ''); + } - if (typeof options.appendBody === 'string' && options.appendBody.length > 0) { - nextBody = nextBody ? `${nextBody}\n${options.appendBody}` : options.appendBody; - } + if (typeof options.appendBody === 'string' && options.appendBody.length > 0) { + nextBody = nextBody ? `${nextBody}\n${options.appendBody}` : options.appendBody; + } - if (options.replaceSection) { - nextBody = replaceSection(nextBody, options.replaceSection.heading, options.replaceSection.body); - } + if (options.replaceSection) { + nextBody = replaceSection(nextBody, options.replaceSection.heading, options.replaceSection.body); + } - if (options.insertAfterHeading) { - nextBody = insertAfterHeading(nextBody, options.insertAfterHeading.heading, options.insertAfterHeading.text); - } + if (options.insertAfterHeading) { + nextBody = insertAfterHeading(nextBody, options.insertAfterHeading.heading, options.insertAfterHeading.text); + } - if (options.note) { - nextBody = appendNote(nextBody, options.note.text, { - section: options.note.section, - timestamp: options.note.timestamp === true, - }); - } + if (options.note) { + nextBody = appendNote(nextBody, options.note.text, { + section: options.note.section, + timestamp: options.note.timestamp === true, + }); + } - if (Object.prototype.hasOwnProperty.call(options, 'due')) { - nextFrontmatter.due = normalizeDueInput(options.due); - } + if (Object.prototype.hasOwnProperty.call(options, 'due')) { + nextFrontmatter.due = normalizeDueInput(options.due); + } - if (Object.prototype.hasOwnProperty.call(options, 'start')) { - nextFrontmatter.start = normalizeStartInput(options.start); - } + if (Object.prototype.hasOwnProperty.call(options, 'start')) { + nextFrontmatter.start = normalizeStartInput(options.start); + } - if (options.setLabelRefs && options.setLabelRefs.length > 0) { - nextFrontmatter.labels = await resolveLabelIds(resolvedBoardRoot, options.setLabelRefs); - } else { - const nextLabelSet = new Set(options.clearLabels === true ? [] : currentLabels); + if (options.setLabelRefs && options.setLabelRefs.length > 0) { + nextFrontmatter.labels = resolveLabelIdsFromSettings(boardSettings, options.setLabelRefs); + } else { + const nextLabelSet = new Set(options.clearLabels === true ? [] : currentLabels); - if (options.addLabelRefs && options.addLabelRefs.length > 0) { - for (const labelId of await resolveLabelIds(resolvedBoardRoot, options.addLabelRefs)) { - nextLabelSet.add(labelId); + if (options.addLabelRefs && options.addLabelRefs.length > 0) { + for (const labelId of resolveLabelIdsFromSettings(boardSettings, options.addLabelRefs)) { + nextLabelSet.add(labelId); + } } - } - if (options.removeLabelRefs && options.removeLabelRefs.length > 0) { - for (const labelId of await resolveLabelIds(resolvedBoardRoot, options.removeLabelRefs)) { - nextLabelSet.delete(labelId); + if (options.removeLabelRefs && options.removeLabelRefs.length > 0) { + for (const labelId of resolveLabelIdsFromSettings(boardSettings, options.removeLabelRefs)) { + nextLabelSet.delete(labelId); + } } + + nextFrontmatter.labels = [...nextLabelSet]; } - nextFrontmatter.labels = [...nextLabelSet]; - } + return { nextFrontmatter, nextBody }; + }; if (options.dryRun === true) { + const { nextFrontmatter, nextBody } = computeEditedCard(cardRecord); const targetList = options.moveToListRef ? await resolveList(resolvedBoardRoot, options.moveToListRef, { includeArchive: true }) : { @@ -1085,7 +1181,7 @@ async function editCard(boardRoot, options = {}) { start: String(normalizedFrontmatter.start || ''), due: String(normalizedFrontmatter.due || ''), labels: Array.isArray(normalizedFrontmatter.labels) ? normalizedFrontmatter.labels : [], - labelNames: await labelNamesForIds(resolvedBoardRoot, normalizedFrontmatter.labels), + labelNames: labelNamesFromSettings(boardSettings, normalizedFrontmatter.labels), frontmatter: normalizedFrontmatter, body: nextBody, timestamps: { @@ -1093,24 +1189,11 @@ async function editCard(boardRoot, options = {}) { updatedAt: cardRecord.timestamps ? cardRecord.timestamps.updatedAt : '', updatedAtSource: cardRecord.timestamps ? cardRecord.timestamps.updatedAtSource : '', }, - taskSummary: getTaskListSummary(nextBody), - taskStartDates: getTaskListStartDates(nextBody), - incompleteTaskStartDates: getIncompleteTaskListStartDates(nextBody), - taskDueDates: getTaskListDueDates(nextBody), - incompleteTaskDueDates: getIncompleteTaskListDueDates(nextBody), + ...getTaskListMetadata(nextBody), wouldMove: Boolean(options.moveToListRef), }; } - await cardFrontmatter.writeCard(cardRecord.filePath, { - frontmatter: obsidianIntegration.normalizeSignboardCardFrontmatter({ - boardRoot: resolvedBoardRoot, - cardPath: cardRecord.filePath, - frontmatter: nextFrontmatter, - }), - body: nextBody, - }); - let finalFilePath = cardRecord.filePath; let finalListEntry = { directoryName: cardRecord.listDirectoryName, @@ -1122,36 +1205,53 @@ async function editCard(boardRoot, options = {}) { const targetList = await resolveList(resolvedBoardRoot, options.moveToListRef, { includeArchive: true }); const movedFileName = await insertCardFileAtTop(targetList.path, cardRecord.filePath, cardRecord.fileName); const nextPath = path.join(targetList.path, movedFileName); - if (nextPath !== cardRecord.filePath) { - const movedCard = await cardFrontmatter.readCard(nextPath); - let movedFrontmatter = movedCard.frontmatter; + await withFileTransaction(nextPath, async () => { + const current = await cardFrontmatter.readCard(nextPath); + const { nextFrontmatter, nextBody } = computeEditedCard(current); + let finalFrontmatter = nextFrontmatter; if ( + nextPath !== cardRecord.filePath && cardRecord.listDirectoryName !== ARCHIVE_DIRECTORY_NAME && targetList.directoryName !== ARCHIVE_DIRECTORY_NAME ) { - movedFrontmatter = applyCardListMove(movedFrontmatter, { + finalFrontmatter = applyCardListMove(finalFrontmatter, { fromListDirectoryName: cardRecord.listDirectoryName, fromListDisplayName: getListDisplayName(cardRecord.listDirectoryName), toListDirectoryName: targetList.directoryName, toListDisplayName: targetList.displayName, }); } - await cardFrontmatter.writeCard(nextPath, { frontmatter: obsidianIntegration.normalizeSignboardCardFrontmatter({ boardRoot: resolvedBoardRoot, cardPath: nextPath, - frontmatter: movedFrontmatter, + frontmatter: finalFrontmatter, }), - body: movedCard.body, + body: nextBody, }); - - finalFilePath = nextPath; - finalListEntry = targetList; - } + }); + finalFilePath = nextPath; + finalListEntry = targetList; + } else { + await withFileTransaction(cardRecord.filePath, async () => { + const current = await cardFrontmatter.readCard(cardRecord.filePath); + const { nextFrontmatter, nextBody } = computeEditedCard(current); + await cardFrontmatter.writeCard(cardRecord.filePath, { + frontmatter: obsidianIntegration.normalizeSignboardCardFrontmatter({ + boardRoot: resolvedBoardRoot, + cardPath: cardRecord.filePath, + frontmatter: nextFrontmatter, + }), + body: nextBody, + }); + }); } - return loadCardRecord(resolvedBoardRoot, finalListEntry, path.basename(finalFilePath)); + const updated = await loadCardRecord(resolvedBoardRoot, finalListEntry, path.basename(finalFilePath)); + return { + ...updated, + labelNames: labelNamesFromSettings(boardSettings, updated.labels), + }; } async function addCardNote(boardRoot, options = {}) { diff --git a/lib/cliInstall.js b/lib/cliInstall.js index 96f51e9..b4dcc45 100644 --- a/lib/cliInstall.js +++ b/lib/cliInstall.js @@ -1,6 +1,7 @@ const fs = require('fs').promises; const os = require('os'); const path = require('path'); +const { atomicWriteFile } = require('./atomicFile'); const CLI_WRAPPER_MARKER = '# Generated by Signboard CLI installer'; const PROFILE_BLOCK_START = '# >>> Signboard CLI >>>'; @@ -24,19 +25,34 @@ function getShellName(shellPath, platform = process.platform) { return 'sh'; } -function renderUnixWrapper({ executablePath, appPath, isPackaged }) { +function renderUnixWrapper({ executablePath, appPath, isPackaged, platform = process.platform }) { const cliScriptPath = path.join(String(appPath || ''), 'bin', 'signboard.js'); + if (platform === 'linux') { + return [ + '#!/bin/sh', + CLI_WRAPPER_MARKER, + `SIGNBOARD_ELECTRON_EXEC=${shellQuote(executablePath)}`, + `SIGNBOARD_CLI_SCRIPT=${shellQuote(cliScriptPath)}`, + 'exec env ELECTRON_RUN_AS_NODE=1 "$SIGNBOARD_ELECTRON_EXEC" "$SIGNBOARD_CLI_SCRIPT" "$@"', + '', + ].join('\n'); + } + return [ '#!/bin/sh', CLI_WRAPPER_MARKER, `SIGNBOARD_ELECTRON_EXEC=${shellQuote(executablePath)}`, `SIGNBOARD_CLI_SCRIPT=${shellQuote(cliScriptPath)}`, - 'SIGNBOARD_CLI_STDERR="$(mktemp -t signboard-cli-stderr.XXXXXX)" || exit 1', + 'SIGNBOARD_CLI_STDERR="$(mktemp -t signboard-cli-stderr.XXXXXX 2>/dev/null)" || exec env ELECTRON_RUN_AS_NODE=1 "$SIGNBOARD_ELECTRON_EXEC" "$SIGNBOARD_CLI_SCRIPT" "$@"', 'trap \'rm -f "$SIGNBOARD_CLI_STDERR"\' EXIT HUP INT TERM', 'ELECTRON_RUN_AS_NODE=1 "$SIGNBOARD_ELECTRON_EXEC" "$SIGNBOARD_CLI_SCRIPT" "$@" 2>"$SIGNBOARD_CLI_STDERR"', 'status=$?', - 'grep -v "electron/shell/common/mac/codesign_util\\.cc:79.*task_name_for_pid" "$SIGNBOARD_CLI_STDERR" >&2 || true', + 'if command -v grep >/dev/null 2>&1; then', + ' grep -v "electron/shell/common/mac/codesign_util\\.cc:79.*task_name_for_pid" "$SIGNBOARD_CLI_STDERR" >&2 || true', + 'else', + ' cat "$SIGNBOARD_CLI_STDERR" >&2', + 'fi', 'exit "$status"', '', ].join('\n'); @@ -123,8 +139,10 @@ function upsertProfileBlock(existingContent, block) { const endIndex = source.indexOf(PROFILE_BLOCK_END); if (startIndex >= 0 && endIndex >= startIndex) { - const before = source.slice(0, startIndex).replace(/\s*$/, '\n'); - const after = source.slice(endIndex + PROFILE_BLOCK_END.length).replace(/^\s*/, '\n'); + const rawBefore = source.slice(0, startIndex); + const rawAfter = source.slice(endIndex + PROFILE_BLOCK_END.length); + const before = rawBefore.trim() ? rawBefore.replace(/\s*$/, '\n\n') : ''; + const after = rawAfter.trim() ? rawAfter.replace(/^\s*/, '\n') : ''; return `${before}${block}${after}`.replace(/\n{3,}/g, '\n\n'); } @@ -152,7 +170,7 @@ async function writeProfileBlock(profilePath, block) { if (changed) { await fs.mkdir(path.dirname(profilePath), { recursive: true }); - await fs.writeFile(profilePath, nextContent, 'utf8'); + await atomicWriteFile(profilePath, nextContent, 'utf8'); } return changed; @@ -174,7 +192,7 @@ async function writeWrapperScript(scriptPath, content) { } if (existing !== content) { - await fs.writeFile(scriptPath, content, 'utf8'); + await atomicWriteFile(scriptPath, content, 'utf8'); } await fs.chmod(scriptPath, 0o755); @@ -206,6 +224,7 @@ async function installCliForCurrentUser({ executablePath: resolvedExecutablePath, appPath: resolvedAppPath, isPackaged: isPackaged !== false, + platform, }); await fs.mkdir(profilePlan.targetDir, { recursive: true }); diff --git a/lib/cliState.js b/lib/cliState.js index 6231d61..651691c 100644 --- a/lib/cliState.js +++ b/lib/cliState.js @@ -2,6 +2,7 @@ const fs = require('fs').promises; const os = require('os'); const path = require('path'); const { atomicWriteFile } = require('./atomicFile'); +const { withFileTransaction } = require('./fileTransaction'); const CLI_STATE_FILE_NAME = 'cli-state.json'; @@ -39,7 +40,8 @@ async function readCliState(options = {}) { try { const raw = await fs.readFile(statePath, 'utf8'); - const parsed = JSON.parse(raw); + const cleanRaw = raw.startsWith('\uFEFF') ? raw.slice(1) : raw; + const parsed = JSON.parse(cleanRaw); return parsed && typeof parsed === 'object' ? parsed : {}; } catch (error) { if (error && error.code === 'ENOENT') { @@ -74,19 +76,27 @@ async function ensureDirectoryExists(directoryPath, label) { } async function setCurrentBoard(boardRoot, options = {}) { - const resolvedBoardRoot = path.resolve(String(boardRoot || '').trim()); - if (!resolvedBoardRoot || resolvedBoardRoot === path.sep) { + const rawBoardRoot = String(boardRoot || '').trim(); + if (!rawBoardRoot) { + throw new Error('Board path is required.'); + } + + const resolvedBoardRoot = path.resolve(rawBoardRoot); + if (!resolvedBoardRoot || resolvedBoardRoot === path.dirname(resolvedBoardRoot)) { throw new Error('Board path is required.'); } await ensureDirectoryExists(resolvedBoardRoot, 'Board root'); - const currentState = await readCliState(options); - const nextState = { - ...currentState, - currentBoard: resolvedBoardRoot, - }; - const statePath = await writeCliState(nextState, options); + const statePath = getCliStatePath(options); + await withFileTransaction(statePath, async () => { + const currentState = await readCliState(options); + const nextState = { + ...currentState, + currentBoard: resolvedBoardRoot, + }; + await writeCliState(nextState, options); + }); return { currentBoard: resolvedBoardRoot, diff --git a/lib/directoryRename.js b/lib/directoryRename.js index 30263e7..58614c6 100644 --- a/lib/directoryRename.js +++ b/lib/directoryRename.js @@ -1,14 +1,22 @@ const fs = require('fs').promises; const path = require('path'); const yaml = require('js-yaml'); -const { atomicWriteFile } = require('./atomicFile'); +const { atomicWriteFile, renameWithWindowsRetry } = require('./atomicFile'); const cardFrontmatter = require('./cardFrontmatter'); const { normalizeSignboardCardFrontmatter } = require('./obsidianIntegration'); const { mapFileReads } = require('./fileReadQueue'); +function samePath(left, right) { + if (process.platform === 'win32') { + return left.toLowerCase() === right.toLowerCase(); + } + return left === right; +} + async function collectCards(directory, recursive = false) { const result = []; for (const entry of await fs.readdir(directory, { withFileTypes: true })) { + if (entry.name.startsWith('.')) continue; const target = path.join(directory, entry.name); if (entry.isSymbolicLink()) { // Metadata reconciliation must not replace links or edit their targets. @@ -25,15 +33,15 @@ async function renameManagedDirectory(boardRoot, sourcePath, destinationPath) { sourcePath = path.resolve(sourcePath); destinationPath = path.resolve(destinationPath); if (sourcePath === destinationPath) return; - const movingBoard = boardRoot === sourcePath; - if (!movingBoard && (path.dirname(sourcePath) !== boardRoot || path.dirname(destinationPath) !== boardRoot)) { + const movingBoard = samePath(boardRoot, sourcePath); + if (!movingBoard && (!samePath(path.dirname(sourcePath), boardRoot) || !samePath(path.dirname(destinationPath), boardRoot))) { throw new Error('A renamed list must remain directly inside its board.'); } const sourceEntry = await fs.lstat(sourcePath, { bigint: true }); if (sourceEntry.isSymbolicLink()) throw new Error('Cannot rename a linked directory.'); try { const destinationEntry = await fs.lstat(destinationPath, { bigint: true }); - const caseOnly = path.dirname(sourcePath) === path.dirname(destinationPath) + const caseOnly = samePath(path.dirname(sourcePath), path.dirname(destinationPath)) && path.basename(sourcePath).toLowerCase() === path.basename(destinationPath).toLowerCase(); // On Windows and default macOS volumes both spellings name the same entry. // Only permit that exact entry; a distinct destination remains a collision. @@ -69,9 +77,10 @@ async function renameManagedDirectory(boardRoot, sourcePath, destinationPath) { return null; }); if (original == null) continue; - const match = original.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/); + const cleanOriginal = original.replace(/^\uFEFF/, ''); + const match = cleanOriginal.match(/^---[ \t]*\r?\n(?:([\s\S]*?)\r?\n)?---(?:\r?\n|$)/); if (!match) break; - const settings = yaml.load(match[1], { schema: yaml.JSON_SCHEMA }); + const settings = yaml.load(match[1] || '', { schema: yaml.JSON_SCHEMA }); let changed = false; for (const field of ['completedListNames', 'completedLists', 'ignoredCompletedListNames']) { if (!Array.isArray(settings?.workflow?.[field])) continue; @@ -82,11 +91,11 @@ async function renameManagedDirectory(boardRoot, sourcePath, destinationPath) { }); } if (changed) plans.push({ file, target: file, original, - next: `---\n${yaml.dump(settings, { schema: yaml.JSON_SCHEMA, lineWidth: -1, noRefs: true })}---\n${original.slice(match[0].length)}` }); + next: `---\n${yaml.dump(settings, { schema: yaml.JSON_SCHEMA, lineWidth: -1, noRefs: true })}---\n${cleanOriginal.slice(match[0].length)}` }); break; } } - await fs.rename(sourcePath, destinationPath); + await renameWithWindowsRetry(sourcePath, destinationPath); const written = []; try { for (const plan of plans) { @@ -106,7 +115,7 @@ async function renameManagedDirectory(boardRoot, sourcePath, destinationPath) { } catch (rollbackError) { failures.push(rollbackError); } } if (!failures.length) { - try { await fs.rename(destinationPath, sourcePath); } catch (rollbackError) { failures.push(rollbackError); } + try { await renameWithWindowsRetry(destinationPath, sourcePath); } catch (rollbackError) { failures.push(rollbackError); } } if (failures.length) throw new AggregateError([error, ...failures], `Rename recovery incomplete; inspect ${destinationPath}.`); throw error; diff --git a/lib/externalPublishedCalendar.js b/lib/externalPublishedCalendar.js index c70a334..21c80b9 100644 --- a/lib/externalPublishedCalendar.js +++ b/lib/externalPublishedCalendar.js @@ -76,18 +76,33 @@ function escapeIcsText(value) { .replace(/,/g, '\\,'); } +const { mapFileReads } = require('./fileReadQueue'); + function foldIcsLine(line) { const source = String(line || ''); + if (!source) { + return ['']; + } + const folded = []; - let cursor = 0; - const firstLineLength = 74; - const continuationLength = 73; - - while (cursor < source.length) { - const maxLength = folded.length === 0 ? firstLineLength : continuationLength; - const chunk = source.slice(cursor, cursor + maxLength); - folded.push(`${folded.length === 0 ? '' : ' '}${chunk}`); - cursor += maxLength; + let current = ''; + let currentBytes = 0; + + for (const ch of source) { + const charBytes = Buffer.byteLength(ch, 'utf8'); + const maxBytes = folded.length === 0 ? 74 : 73; + if (current && currentBytes + charBytes > maxBytes) { + folded.push(`${folded.length === 0 ? '' : ' '}${current}`); + current = ch; + currentBytes = charBytes; + } else { + current += ch; + currentBytes += charBytes; + } + } + + if (current) { + folded.push(`${folded.length === 0 ? '' : ' '}${current}`); } return folded.length > 0 ? folded : ['']; @@ -212,9 +227,25 @@ async function collectExternalPublishedCalendarEvents(options = {}) { const listPath = path.join(boardRoot, listName); const listDisplayName = getListDisplayName(listName); const cardNames = await listCards(listPath); - for (const cardName of Array.isArray(cardNames) ? cardNames : []) { + const cardList = Array.isArray(cardNames) ? cardNames : []; + const loadedCards = await mapFileReads(cardList, async (cardName) => { const cardPath = path.join(listPath, cardName); - const card = await readCard(cardPath); + try { + const card = await readCard(cardPath); + return { cardPath, card }; + } catch (error) { + if (!isMissingCalendarSourceError(error)) { + console.error(`Unable to read card for calendar feed: ${cardPath}`, error); + } + return null; + } + }); + + for (const entry of loadedCards) { + if (!entry) { + continue; + } + const { cardPath, card } = entry; const frontmatter = card && card.frontmatter && typeof card.frontmatter === 'object' ? card.frontmatter : {}; diff --git a/lib/fileReadQueue.js b/lib/fileReadQueue.js index f049e14..86e3f04 100644 --- a/lib/fileReadQueue.js +++ b/lib/fileReadQueue.js @@ -2,7 +2,8 @@ // read may also stat the file, so leave headroom for the rest of the process. const MAX_CONCURRENT_READS = 16; let active = 0; -const waiting = []; +let waiting = []; +let waitingHead = 0; async function withFileReadLimit(operation) { if (active >= MAX_CONCURRENT_READS) { @@ -13,9 +14,21 @@ async function withFileReadLimit(operation) { try { return await operation(); } finally { - const next = waiting.shift(); - if (next) next(); - else active -= 1; + if (waitingHead < waiting.length) { + const next = waiting[waitingHead]; + waiting[waitingHead] = null; + waitingHead += 1; + if (waitingHead === waiting.length) { + waiting = []; + waitingHead = 0; + } else if (waitingHead >= 256 && waitingHead * 2 >= waiting.length) { + waiting = waiting.slice(waitingHead); + waitingHead = 0; + } + next(); + } else { + active -= 1; + } } } diff --git a/lib/fileTransaction.js b/lib/fileTransaction.js index 7159759..88f81e7 100644 --- a/lib/fileTransaction.js +++ b/lib/fileTransaction.js @@ -1,15 +1,25 @@ const fs = require('fs').promises; const path = require('path'); +const STALE_LOCK_GRACE_MS = 30000; +const RETRYABLE_LOCK_CODES = new Set(['EEXIST', 'ENOENT', 'EPERM', 'EACCES', 'EBUSY']); const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (error) { return error.code !== 'ESRCH'; } }; +async function isStaleLockFile(lockPath) { + const raw = await fs.readFile(lockPath, 'utf8'); + const owner = Number(String(raw || '').trim()); + const stat = await fs.stat(lockPath); + return (owner > 0 && !alive(owner)) || (!owner && Date.now() - stat.mtimeMs > STALE_LOCK_GRACE_MS); +} + // Cooperating desktop/CLI/TUI writers serialize read-modify-write operations. // Atomic replacement alone cannot protect a read from a concurrent writer. async function withFileTransaction(filePath, action, { timeoutMs = 10000, createDirectory = true } = {}) { const lock = `${path.resolve(filePath)}.sb-lock`; + const reapLock = `${lock}.reap`; if (createDirectory) await fs.mkdir(path.dirname(lock), { recursive: true }); const deadline = Date.now() + timeoutMs; let handle; @@ -18,30 +28,59 @@ async function withFileTransaction(filePath, action, { timeoutMs = 10000, create handle = await fs.open(lock, 'wx', 0o600); await handle.writeFile(String(process.pid)); } catch (error) { - if (error.code !== 'EEXIST') { - if (handle) { await handle.close(); await fs.unlink(lock).catch(() => {}); } + const retryableAcquire = error && ( + error.code === 'EEXIST' + || (process.platform === 'win32' && ['EPERM', 'EACCES', 'EBUSY'].includes(error.code)) + ); + if (!retryableAcquire) { + if (handle) { + await handle.close().catch(() => {}); + await fs.unlink(lock).catch(() => {}); + } throw error; } + if (handle) { + await handle.close().catch(() => {}); + handle = null; + } // Only one contender may recover a dead owner's lock at a time. let reaper; try { - reaper = await fs.open(`${lock}.reap`, 'wx', 0o600); - const owner = Number(await fs.readFile(lock, 'utf8')); - const stat = await fs.stat(lock); - if ((owner > 0 && !alive(owner)) || (!owner && Date.now() - stat.mtimeMs > 30000)) { + reaper = await fs.open(reapLock, 'wx', 0o600); + await reaper.writeFile(String(process.pid)); + if (await isStaleLockFile(lock)) { await fs.unlink(lock); } } catch (failure) { - if (!['EEXIST', 'ENOENT'].includes(failure.code)) throw failure; + if (failure && failure.code === 'EEXIST') { + try { + if (await isStaleLockFile(reapLock)) { + await fs.unlink(reapLock); + } + } catch (reapRecoveryError) { + if (!reapRecoveryError || !RETRYABLE_LOCK_CODES.has(reapRecoveryError.code)) { + throw reapRecoveryError; + } + } + } else if (!failure || !RETRYABLE_LOCK_CODES.has(failure.code)) { + throw failure; + } } finally { - if (reaper) { await reaper.close(); await fs.unlink(`${lock}.reap`).catch(() => {}); } + if (reaper) { + await reaper.close().catch(() => {}); + await fs.unlink(reapLock).catch(() => {}); + } } if (Date.now() >= deadline) throw new Error(`Another Signboard process is saving ${path.basename(filePath)}. Retry shortly.`); - await pause(20); + await pause(15 + Math.floor(Math.random() * 20)); } } - try { return await action(); } - finally { await handle.close(); await fs.unlink(lock).catch(() => {}); } + try { + return await action(); + } finally { + await handle.close().catch(() => {}); + await fs.unlink(lock).catch(() => {}); + } } module.exports = { withFileTransaction }; diff --git a/lib/importers/obsidian.js b/lib/importers/obsidian.js index 2e5fa90..5dd0182 100644 --- a/lib/importers/obsidian.js +++ b/lib/importers/obsidian.js @@ -294,7 +294,8 @@ function createTaskBody(task, metadataSection, extraSections = []) { } function parseObsidianKanbanColumns(rawContent, filePath) { - const lines = String(rawContent || '').split(/\r?\n/); + const cleanedContent = String(rawContent || '').replace(OBSIDIAN_KANBAN_SETTINGS_PATTERN, ''); + const lines = cleanedContent.split(/\r?\n/); const columns = []; let currentColumn = null; let currentCard = null; @@ -334,9 +335,10 @@ function parseObsidianKanbanColumns(rawContent, filePath) { const match = rawLine.match(TASK_LINE_PATTERN); if (match && String(match[1] || '').length === 0) { finalizeCard(); + const checkGlyph = String(match[3] || '').replace(/\s+/g, '').toLowerCase(); currentCard = { rawLine: String(match[4] || ''), - checked: String(match[3] || '').replace(/\s+/g, '').toLowerCase() === 'x', + checked: checkGlyph === 'x' || checkGlyph === '✓' || checkGlyph === '✔', bodyLines: [], }; continue; @@ -474,20 +476,21 @@ function normalizeCardBoardColumn(rawColumn = {}, index = 0) { }; } + const isExplicitNumber = (val) => val != null && val !== '' && typeof val !== 'boolean' && Number.isFinite(Number(val)); const from = rawColumn.from ?? rawColumn.start ?? rawColumn.left ?? rawColumn.lower; const to = rawColumn.to ?? rawColumn.end ?? rawColumn.right ?? rawColumn.upper; const before = rawColumn.before ?? rawColumn.max ?? rawColumn.dayBefore; const after = rawColumn.after ?? rawColumn.min ?? rawColumn.dayAfter; - if (Number.isFinite(Number(from)) && Number.isFinite(Number(to))) { + if (isExplicitNumber(from) && isExplicitNumber(to)) { return { kind: 'between', name, from: Number(from), to: Number(to), raw: rawColumn }; } - if (Number.isFinite(Number(before))) { + if (isExplicitNumber(before)) { return { kind: 'before', name, before: Number(before), raw: rawColumn }; } - if (Number.isFinite(Number(after))) { + if (isExplicitNumber(after)) { return { kind: 'after', name, after: Number(after), raw: rawColumn }; } @@ -754,6 +757,7 @@ async function importGenericTaskScope(context, scope, shouldPrefix) { return columnTasks.get(name); } + const hasExplicitTaskListKanbanColumns = tasks.some((entry) => entry.columnTags.length > 0); for (const task of tasks) { if (task.checked) { getOrCreateBucket('Done').push(task); @@ -765,7 +769,6 @@ async function importGenericTaskScope(context, scope, shouldPrefix) { continue; } - const hasExplicitTaskListKanbanColumns = tasks.some((entry) => entry.columnTags.length > 0); getOrCreateBucket(hasExplicitTaskListKanbanColumns ? 'Uncategorised' : 'Tasks').push(task); } diff --git a/lib/importers/shared.js b/lib/importers/shared.js index c2f13ba..e9d1df0 100644 --- a/lib/importers/shared.js +++ b/lib/importers/shared.js @@ -511,9 +511,18 @@ async function walkMarkdownFiles(rootPath, options = {}) { } const queue = [resolvedRoot]; - while (queue.length > 0) { - const currentPath = queue.shift(); - const entries = await readDirectoryEntries(currentPath); + let head = 0; + while (head < queue.length) { + const currentPath = queue[head++]; + let entries; + try { + entries = await readDirectoryEntries(currentPath); + } catch (error) { + if (error && (error.code === 'EACCES' || error.code === 'EPERM' || error.code === 'ENOENT')) { + continue; + } + throw error; + } for (const entry of entries) { if (ignoreNames.has(entry.name)) { continue; @@ -525,7 +534,7 @@ async function walkMarkdownFiles(rootPath, options = {}) { continue; } - if (entry.isFile() && entry.name.endsWith('.md')) { + if (entry.isFile() && entry.name.toLowerCase().endsWith('.md')) { results.push(nextPath); } } diff --git a/lib/importers/tasksmd.js b/lib/importers/tasksmd.js index 6621cf3..6cc2f1e 100644 --- a/lib/importers/tasksmd.js +++ b/lib/importers/tasksmd.js @@ -239,8 +239,8 @@ function buildTasksMdMetadataSection(projectRoot, laneName, filePath, stats, raw 'Tasks.md project': path.basename(projectRoot), 'Original lane': laneName, 'Tasks.md path': toPosixRelative(projectRoot, filePath), - Created: stats?.birthtime ? stats.birthtime.toISOString() : '', - 'Last updated': stats?.mtime ? stats.mtime.toISOString() : '', + Created: stats && Number(stats.birthtimeMs) > 0 && stats.birthtime ? stats.birthtime.toISOString() : '', + 'Last updated': stats && Number(stats.mtimeMs) > 0 && stats.mtime ? stats.mtime.toISOString() : '', 'Raw due marker': rawDueValue || '', }; diff --git a/lib/linuxPackageInstaller.js b/lib/linuxPackageInstaller.js index 62399e9..b0027fc 100644 --- a/lib/linuxPackageInstaller.js +++ b/lib/linuxPackageInstaller.js @@ -1,5 +1,6 @@ -const { spawnSync } = require('child_process'); +const { spawn, spawnSync } = require('child_process'); const fs = require('fs'); +const fsPromises = fs.promises; const path = require('path'); function isPacmanPackagePath(filePath) { @@ -13,8 +14,36 @@ function defaultCommandRunner(command, args) { }); } -function runCheckedCommand(command, args, commandRunner = defaultCommandRunner) { - const result = commandRunner(command, args); +function defaultAsyncCommandRunner(command, args) { + return new Promise((resolve) => { + let stdout = ''; + let stderr = ''; + let settled = false; + const child = spawn(command, args, { + stdio: ['ignore', 'pipe', 'pipe'], + }); + if (child.stdout) { + child.stdout.setEncoding('utf8'); + child.stdout.on('data', (chunk) => { stdout += chunk; }); + } + if (child.stderr) { + child.stderr.setEncoding('utf8'); + child.stderr.on('data', (chunk) => { stderr += chunk; }); + } + child.on('error', (error) => { + if (settled) return; + settled = true; + resolve({ error, status: null, stdout, stderr }); + }); + child.on('close', (status) => { + if (settled) return; + settled = true; + resolve({ status, stdout, stderr }); + }); + }); +} + +function formatCheckedCommandResult(command, result) { if (result && result.error) { throw result.error; } @@ -29,6 +58,15 @@ function runCheckedCommand(command, args, commandRunner = defaultCommandRunner) return result; } +function runCheckedCommand(command, args, commandRunner = defaultCommandRunner) { + return formatCheckedCommandResult(command, commandRunner(command, args)); +} + +async function runCheckedCommandAsync(command, args, commandRunner = defaultAsyncCommandRunner) { + const result = await commandRunner(command, args); + return formatCheckedCommandResult(command, result); +} + function validatePacmanPackageWithSystem(filePath, commandRunner = defaultCommandRunner) { const resolvedPath = path.resolve(String(filePath || '')); if (!isPacmanPackagePath(resolvedPath) || !fs.existsSync(resolvedPath) || !fs.statSync(resolvedPath).isFile()) { @@ -38,6 +76,24 @@ function validatePacmanPackageWithSystem(filePath, commandRunner = defaultComman return resolvedPath; } +async function validatePacmanPackageWithSystemAsync(filePath, commandRunner = defaultAsyncCommandRunner) { + const resolvedPath = path.resolve(String(filePath || '')); + if (!isPacmanPackagePath(resolvedPath)) { + throw new Error('The downloaded Arch package is missing or has an invalid filename.'); + } + let stats = null; + try { + stats = await fsPromises.stat(resolvedPath); + } catch { + stats = null; + } + if (!stats || !stats.isFile()) { + throw new Error('The downloaded Arch package is missing or has an invalid filename.'); + } + await runCheckedCommandAsync('pacman', ['-Qp', resolvedPath], commandRunner); + return resolvedPath; +} + function installPacmanPackage(filePath, commandRunner = defaultCommandRunner) { const resolvedPath = validatePacmanPackageWithSystem(filePath, commandRunner); // Deliberately use only `pacman -U`. Never refresh package databases with @@ -46,10 +102,22 @@ function installPacmanPackage(filePath, commandRunner = defaultCommandRunner) { return { ok: true, packagePath: resolvedPath }; } +async function installPacmanPackageAsync(filePath, commandRunner = defaultAsyncCommandRunner) { + const resolvedPath = await validatePacmanPackageWithSystemAsync(filePath, commandRunner); + // Deliberately use only `pacman -U`. Never refresh package databases with + // `pacman -Sy`, which can create an unsupported partial-upgrade state. + await runCheckedCommandAsync('pkexec', ['pacman', '-U', '--noconfirm', resolvedPath], commandRunner); + return { ok: true, packagePath: resolvedPath }; +} + module.exports = { + defaultAsyncCommandRunner, defaultCommandRunner, installPacmanPackage, + installPacmanPackageAsync, isPacmanPackagePath, runCheckedCommand, + runCheckedCommandAsync, validatePacmanPackageWithSystem, + validatePacmanPackageWithSystemAsync, }; diff --git a/lib/listOrderRecovery.js b/lib/listOrderRecovery.js index 63f2a0f..d3b6047 100644 --- a/lib/listOrderRecovery.js +++ b/lib/listOrderRecovery.js @@ -1,5 +1,6 @@ const fs = require('fs').promises; const path = require('path'); +const { syncDirectory } = require('./atomicFile'); const RECOVERY_FILE = '.signboard-list-order.json'; const retryDelays = [50, 150, 300]; @@ -14,6 +15,16 @@ async function renameListWithRetry(from, to) { } } +async function unlinkWithRetry(filePath) { + for (let attempt = 0; ; attempt += 1) { + try { return await fs.unlink(filePath); } + catch (error) { + if (!['EPERM', 'EACCES', 'EBUSY'].includes(error.code) || attempt >= retryDelays.length) throw error; + await new Promise((resolve) => setTimeout(resolve, retryDelays[attempt])); + } + } +} + async function assertNoListOrderRecovery(boardRoot) { try { await fs.lstat(path.join(boardRoot, RECOVERY_FILE)); } catch (error) { if (error.code === 'ENOENT') return; throw error; } @@ -31,7 +42,8 @@ async function prepareListOrderRecovery(boardRoot, entries, stagedEntries) { final: entry.finalEntryName, })) }, null, 2) + '\n'); await handle.sync(); - } finally { await handle.close(); } + } finally { await handle.close().catch(() => {}); } + await syncDirectory(boardRoot); return { rename: renameListWithRetry, async restore(from, to) { @@ -43,7 +55,7 @@ async function prepareListOrderRecovery(boardRoot, entries, stagedEntries) { } throw new Error(`Cannot restore ${path.basename(from)}: ${path.basename(to)} already exists.`); }, - async finish() { await fs.unlink(file); }, + async finish() { await unlinkWithRetry(file); }, incomplete(error, failures) { return new AggregateError([error, ...failures], `List order recovery is incomplete. Preserve ${RECOVERY_FILE} and the board folders; original and temporary names are recorded there.`); diff --git a/lib/mcpLaunch.js b/lib/mcpLaunch.js index d12508a..fbdb7d0 100644 --- a/lib/mcpLaunch.js +++ b/lib/mcpLaunch.js @@ -19,10 +19,14 @@ function buildMcpConfigTemplate({ const command = path.resolve(rawExecutablePath); const resolvedAppPath = path.resolve(rawAppPath); + const normalizedAllowedRoots = Array.isArray(allowedRoots) + ? allowedRoots.map((entry) => String(entry || '').trim()).filter(Boolean).join(path.delimiter) + : String(allowedRoots || ''); + const env = { ELECTRON_RUN_AS_NODE: '1', SIGNBOARD_MCP_READ_ONLY: readOnly ? 'true' : 'false', - SIGNBOARD_MCP_ALLOWED_ROOTS: String(allowedRoots || ''), + SIGNBOARD_MCP_ALLOWED_ROOTS: normalizedAllowedRoots, }; const normalizedUserDataDir = String(desktopUserDataDir || '').trim(); if (normalizedUserDataDir) { diff --git a/lib/mcpServer.js b/lib/mcpServer.js index a5e02a5..997689f 100644 --- a/lib/mcpServer.js +++ b/lib/mcpServer.js @@ -2,7 +2,9 @@ const fs = require('fs').promises; const path = require('path'); const automation = require('./automation'); const cliBoard = require('./cliBoard'); -const { assertAllowedPath, assertAllowedTree } = require('./allowedPaths'); +const { assertAllowedPath, assertAllowedTree, resolveCanonicalRoots } = require('./allowedPaths'); +const { renameWithWindowsRetry } = require('./atomicFile'); +const { withFileTransaction } = require('./fileTransaction'); const { normalizeSignboardCardFrontmatter } = require('./obsidianIntegration'); const { parseLocalIsoDate } = require('../shared/localDate'); const cardFrontmatter = require('./cardFrontmatter'); @@ -678,26 +680,27 @@ function parseBoolean(value, fallback = false) { return fallback; } +function pathIdentityKey(value) { + return process.platform === 'win32' ? String(value || '').toLowerCase() : String(value || ''); +} + function normalizeAllowedRootList(values) { const seen = new Set(); const roots = []; for (const value of Array.isArray(values) ? values : []) { const candidate = String(value || '').trim(); - if (!candidate) { + if (!candidate || !path.isAbsolute(candidate)) { continue; } const resolved = path.resolve(candidate); - if (!path.isAbsolute(resolved)) { - continue; - } - - if (seen.has(resolved)) { + const key = pathIdentityKey(resolved); + if (seen.has(key)) { continue; } - seen.add(resolved); + seen.add(key); roots.push(resolved); } @@ -721,7 +724,7 @@ function mergeAllowedRoots(...rootGroups) { function isPathInside(parentPath, childPath) { const relativePath = path.relative(parentPath, childPath); - return relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath)); + return relativePath === '' || (relativePath !== '..' && !relativePath.startsWith(`..${path.sep}`) && !path.isAbsolute(relativePath)); } function validateNameSegment(value, fieldName) { @@ -810,7 +813,14 @@ async function assertInsideAllowedRoots(config, candidatePath, fieldName) { if (!config.allowedRoots.length) { throw new Error(`${fieldName} requires SIGNBOARD_MCP_ALLOWED_ROOTS to be configured.`); } - await assertAllowedPath(config.allowedRoots, candidatePath, fieldName); + await assertAllowedPath(config.allowedRoots, candidatePath, fieldName, config._canonicalAllowedRoots || null); +} + +async function assertTreeInsideAllowedRoots(config, rootPath) { + if (!config.allowedRoots.length) { + throw new Error('Path requires SIGNBOARD_MCP_ALLOWED_ROOTS to be configured.'); + } + await assertAllowedTree(config.allowedRoots, rootPath, new Set(), config._canonicalAllowedRoots || null); } function normalizeCardDateInput(value, fieldName) { @@ -826,65 +836,93 @@ function resolveAbsolutePathInput(pathInput, fieldName) { throw new Error(`${fieldName} is required.`); } - const resolvedPath = path.resolve(candidatePath); - if (!path.isAbsolute(resolvedPath)) { + if (!path.isAbsolute(candidatePath)) { throw new Error(`${fieldName} must be an absolute path.`); } - return resolvedPath; + return path.resolve(candidatePath); } async function resolveBoardRoot(config, boardRootInput) { const resolvedBoardRoot = resolveAbsolutePathInput(boardRootInput, 'boardRoot'); - await ensureExistingDirectory(resolvedBoardRoot, `Board root does not exist: ${resolvedBoardRoot}`); await assertInsideAllowedRoots(config, resolvedBoardRoot, 'boardRoot'); + await ensureExistingDirectory(resolvedBoardRoot, `Board root does not exist: ${resolvedBoardRoot}`); - await assertInsideAllowedRoots(config, path.join(resolvedBoardRoot, 'board-settings.md'), 'board settings'); - await assertInsideAllowedRoots(config, path.join(resolvedBoardRoot, 'labels.md'), 'legacy board settings'); - await assertInsideAllowedRoots(config, path.join(resolvedBoardRoot, ARCHIVE_DIRECTORY_NAME), 'archive'); + await Promise.all([ + assertInsideAllowedRoots(config, path.join(resolvedBoardRoot, 'board-settings.md'), 'board settings'), + assertInsideAllowedRoots(config, path.join(resolvedBoardRoot, 'labels.md'), 'legacy board settings'), + assertInsideAllowedRoots(config, path.join(resolvedBoardRoot, ARCHIVE_DIRECTORY_NAME), 'archive'), + ]); return resolvedBoardRoot; } async function resolveExistingDirectoryPath(config, directoryPathInput, fieldName) { const resolvedDirectoryPath = resolveAbsolutePathInput(directoryPathInput, fieldName); - await ensureExistingDirectory(resolvedDirectoryPath, `${fieldName} does not exist: ${resolvedDirectoryPath}`); await assertInsideAllowedRoots(config, resolvedDirectoryPath, fieldName); + await ensureExistingDirectory(resolvedDirectoryPath, `${fieldName} does not exist: ${resolvedDirectoryPath}`); return resolvedDirectoryPath; } async function resolveExistingFilePath(config, filePathInput, fieldName) { const resolvedFilePath = resolveAbsolutePathInput(filePathInput, fieldName); - await ensureExistingFile(resolvedFilePath, `${fieldName} does not exist: ${resolvedFilePath}`); await assertInsideAllowedRoots(config, resolvedFilePath, fieldName); + await ensureExistingFile(resolvedFilePath, `${fieldName} does not exist: ${resolvedFilePath}`); return resolvedFilePath; } async function resolveExistingPath(config, pathInput, fieldName) { const resolvedPath = resolveAbsolutePathInput(pathInput, fieldName); - await ensureExistingFileOrDirectory(resolvedPath, `${fieldName} does not exist: ${resolvedPath}`); await assertInsideAllowedRoots(config, resolvedPath, fieldName); + await ensureExistingFileOrDirectory(resolvedPath, `${fieldName} does not exist: ${resolvedPath}`); return resolvedPath; } async function resolveExistingImportSourcePath(config, sourcePathInput, fieldName) { const resolvedSourcePath = resolveAbsolutePathInput(sourcePathInput, fieldName); - await ensureExistingFileOrDirectory(resolvedSourcePath, `${fieldName} does not exist: ${resolvedSourcePath}`); await assertInsideAllowedRoots(config, resolvedSourcePath, fieldName); + await ensureExistingFileOrDirectory(resolvedSourcePath, `${fieldName} does not exist: ${resolvedSourcePath}`); return resolvedSourcePath; } function normalizeCardBodyInput(value) { const body = String(value || ''); - if (!body || !/(\\r\\n|\\n|\\N|\\r)/.test(body)) { + if (!body) { return body; } - return body - .replace(/\\r\\n/g, '\n') - .replace(/\\n/g, '\n') - .replace(/\\N/g, '\n') - .replace(/\\r/g, '\n'); + // Legacy MCP clients occasionally double-escape an entire single-line body using literal "\n". + // Only unescape when the body has no real newlines and does not look like a Windows path. + if ( + !/[\r\n]/.test(body) && + /(\\r\\n|\\n)/.test(body) && + !/(?:^|[\s"'`(])(?:[A-Za-z]:\\|\\\\[^\\]+\\)/.test(body) + ) { + return body + .replace(/\\r\\n/g, '\n') + .replace(/\\n/g, '\n'); + } + + return body.replace(/\r\n/g, '\n'); +} + +async function isCaseOnlySameEntry(sourcePath, destinationPath) { + if ( + pathIdentityKey(path.dirname(sourcePath)) !== pathIdentityKey(path.dirname(destinationPath)) || + path.basename(sourcePath).toLowerCase() !== path.basename(destinationPath).toLowerCase() + ) { + return false; + } + + try { + const [sourceStat, destStat] = await Promise.all([ + fs.lstat(sourcePath, { bigint: true }), + fs.lstat(destinationPath, { bigint: true }), + ]); + return sourceStat.ino !== 0n && sourceStat.ino === destStat.ino && sourceStat.dev === destStat.dev; + } catch { + return false; + } } async function validateDestinationBoardRoot(config, boardRoot, destinationBoardRoot, fieldName) { @@ -899,16 +937,15 @@ async function validateDestinationBoardRoot(config, boardRoot, destinationBoardR await assertInsideAllowedRoots(config, destinationBoardRoot, fieldName); const destinationParent = path.dirname(destinationBoardRoot); - await ensureExistingDirectory(destinationParent, `Destination parent directory does not exist: ${destinationParent}`); await assertInsideAllowedRoots(config, destinationParent, 'destination parent directory'); + await ensureExistingDirectory(destinationParent, `Destination parent directory does not exist: ${destinationParent}`); - if (await pathExists(destinationBoardRoot)) { + if (await pathExists(destinationBoardRoot) && !(await isCaseOnlySameEntry(boardRoot, destinationBoardRoot))) { throw new Error(`${fieldName} already exists: ${destinationBoardRoot}`); } } -async function resolveListPath(config, boardRootInput, listNameInput) { - const boardRoot = await resolveBoardRoot(config, boardRootInput); +async function resolveListPathInValidatedBoard(config, boardRoot, listNameInput) { const listName = validateNameSegment(listNameInput, 'listName'); const listPath = path.resolve(path.join(boardRoot, listName)); @@ -920,10 +957,12 @@ async function resolveListPath(config, boardRootInput, listNameInput) { return { boardRoot, listName, listPath }; } -async function resolveCardPath(config, boardRootInput, listNameInput, cardFileInput) { - const { boardRoot, listName, listPath } = await resolveListPath(config, boardRootInput, listNameInput); - await ensureExistingDirectory(listPath, `List does not exist: ${listName}`); +async function resolveListPath(config, boardRootInput, listNameInput) { + const boardRoot = await resolveBoardRoot(config, boardRootInput); + return resolveListPathInValidatedBoard(config, boardRoot, listNameInput); +} +async function resolveCardPathInValidatedList(config, boardRoot, listName, listPath, cardFileInput) { const cardFile = validateNameSegment(cardFileInput, 'cardFile'); if (!cardFile.endsWith('.md')) { throw new Error('cardFile must end with .md.'); @@ -938,6 +977,12 @@ async function resolveCardPath(config, boardRootInput, listNameInput, cardFileIn return { boardRoot, listName, listPath, cardFile, cardPath }; } +async function resolveCardPath(config, boardRootInput, listNameInput, cardFileInput) { + const { boardRoot, listName, listPath } = await resolveListPath(config, boardRootInput, listNameInput); + await ensureExistingDirectory(listPath, `List does not exist: ${listName}`); + return resolveCardPathInValidatedList(config, boardRoot, listName, listPath, cardFileInput); +} + function slugifyTitle(title) { const cleaned = String(title || '') .toLowerCase() @@ -1105,7 +1150,13 @@ function compactText(text) { return value; } - return `${value.slice(0, TOOL_CALL_OUTPUT_LIMIT)}\n\n...[truncated]`; + let cut = TOOL_CALL_OUTPUT_LIMIT; + const lastCode = value.charCodeAt(cut - 1); + if (lastCode >= 0xD800 && lastCode <= 0xDBFF) { + cut -= 1; + } + + return `${value.slice(0, cut)}\n\n...[truncated]`; } function buildToolResult(payload, fallbackMessage) { @@ -1243,13 +1294,15 @@ async function handleToolCall(config, name, args = {}) { case 'signboard.search_cards': { const boardRoot = await resolveBoardRoot(config, args.boardRoot); - await assertAllowedTree(config.allowedRoots, boardRoot); if (args.listNames !== undefined) { if (!Array.isArray(args.listNames)) throw new Error('listNames must be an array.'); for (const name of args.listNames) { - const list = await resolveListPath(config, boardRoot, name); + const list = await resolveListPathInValidatedBoard(config, boardRoot, name); await ensureExistingDirectory(list.listPath, 'List does not exist.'); + await assertTreeInsideAllowedRoots(config, list.listPath); } + } else { + await assertTreeInsideAllowedRoots(config, boardRoot); } for (const [field, values] of Object.entries({ labelMode: ['any', 'all'], dueSource: ['any', 'card', 'task'], taskStatus: ['any', 'open'], @@ -1282,7 +1335,7 @@ async function handleToolCall(config, name, args = {}) { assertWriteAllowed(config, toPublicToolName(toolName)); const { boardRoot, listName, listPath } = await resolveListPath(config, args.boardRoot, args.listName); await ensureExistingDirectory(listPath, 'List does not exist.'); - await assertAllowedTree(config.allowedRoots, boardRoot); + await assertTreeInsideAllowedRoots(config, listPath); if (typeof args.newName !== 'string' || !args.newName.trim()) throw new Error('newName is required.'); return { ok: true, boardRoot, ...(await cliBoard.renameList(boardRoot, listName, args.newName)) }; } @@ -1293,19 +1346,19 @@ async function handleToolCall(config, name, args = {}) { const parent = await resolveExistingDirectoryPath(config, args.targetParentRoot, 'targetParentRoot'); const name = validateNameSegment(args.newBoardName, 'newBoardName'); await validateDestinationBoardRoot(config, boardRoot, path.join(parent, name), 'destination'); - await assertAllowedTree(config.allowedRoots, boardRoot); + await assertTreeInsideAllowedRoots(config, boardRoot); return automation.copyBoard(boardRoot, parent, name); } case 'signboard.reorder_cards': { assertWriteAllowed(config, toPublicToolName(toolName)); const { boardRoot, listName, listPath } = await resolveListPath(config, args.boardRoot, args.listName); - await assertAllowedTree(config.allowedRoots, boardRoot); await ensureExistingDirectory(listPath, 'List does not exist.'); + await assertTreeInsideAllowedRoots(config, listPath); if (args.orderBy !== undefined && args.orderBy !== 'due') throw new Error('orderBy must be due.'); if (args.cardFiles !== undefined && !Array.isArray(args.cardFiles)) throw new Error('cardFiles must be an array.'); for (const file of args.cardFiles || []) { - const card = await resolveCardPath(config, boardRoot, listName, file); + const card = await resolveCardPathInValidatedList(config, boardRoot, listName, listPath, file); await ensureExistingFile(card.cardPath, 'Card does not exist.'); } return automation.orderCards(boardRoot, listName, args.cardFiles || [], args.orderBy === 'due'); @@ -1314,10 +1367,10 @@ async function handleToolCall(config, name, args = {}) { case 'signboard.reorder_lists': { assertWriteAllowed(config, toPublicToolName(toolName)); const boardRoot = await resolveBoardRoot(config, args.boardRoot); - await assertAllowedTree(config.allowedRoots, boardRoot); + await assertTreeInsideAllowedRoots(config, boardRoot); if (!Array.isArray(args.listNames)) throw new Error('listNames must be an array.'); for (const name of args.listNames) { - const list = await resolveListPath(config, boardRoot, name); + const list = await resolveListPathInValidatedBoard(config, boardRoot, name); await ensureExistingDirectory(list.listPath, 'List does not exist.'); } return automation.orderLists(boardRoot, args.listNames); @@ -1695,7 +1748,10 @@ async function handleToolCall(config, name, args = {}) { }; } - await assertAllowedTree(config.allowedRoots, source.boardRoot); + await assertTreeInsideAllowedRoots(config, source.cardPath); + if (await pathExists(path.join(source.boardRoot, ARCHIVE_DIRECTORY_NAME))) { + await assertTreeInsideAllowedRoots(config, path.join(source.boardRoot, ARCHIVE_DIRECTORY_NAME)); + } const archived = await archiveCardOnDisk(source.boardRoot, source.cardPath); return { @@ -1726,7 +1782,10 @@ async function handleToolCall(config, name, args = {}) { }; } - await assertAllowedTree(config.allowedRoots, boardRoot); + await assertTreeInsideAllowedRoots(config, listPath); + if (await pathExists(path.join(boardRoot, ARCHIVE_DIRECTORY_NAME))) { + await assertTreeInsideAllowedRoots(config, path.join(boardRoot, ARCHIVE_DIRECTORY_NAME)); + } const archived = await archiveListOnDisk(boardRoot, listPath); return { ok: true, @@ -1740,7 +1799,7 @@ async function handleToolCall(config, name, args = {}) { case 'signboard.list_archive_entries': { const boardRoot = await resolveBoardRoot(config, args.boardRoot); if (await pathExists(path.join(boardRoot, ARCHIVE_DIRECTORY_NAME))) { - await assertAllowedTree(config.allowedRoots, path.join(boardRoot, ARCHIVE_DIRECTORY_NAME)); + await assertTreeInsideAllowedRoots(config, path.join(boardRoot, ARCHIVE_DIRECTORY_NAME)); } return listArchiveEntriesOnDisk(boardRoot); } @@ -1748,7 +1807,7 @@ async function handleToolCall(config, name, args = {}) { case 'signboard.read_archive_entry': { const boardRoot = await resolveBoardRoot(config, args.boardRoot); const entryPath = await resolveExistingPath(config, args.entryPath, 'entryPath'); - await assertAllowedTree(config.allowedRoots, entryPath); + await assertTreeInsideAllowedRoots(config, entryPath); return readArchiveEntryOnDisk(boardRoot, entryPath); } @@ -1757,11 +1816,11 @@ async function handleToolCall(config, name, args = {}) { const boardRoot = await resolveBoardRoot(config, args.boardRoot); const archivedCardPath = await resolveExistingPath(config, args.archivedCardPath, 'archivedCardPath'); - const { listName: targetListName, listPath: targetListPath } = await resolveListPath(config, boardRoot, args.targetListName); - await assertInsideAllowedRoots(config, targetListPath, 'target list'); + const { listName: targetListName, listPath: targetListPath } = await resolveListPathInValidatedBoard(config, boardRoot, args.targetListName); await ensureExistingDirectory(targetListPath, `List does not exist: ${targetListName}`); - await assertAllowedTree(config.allowedRoots, boardRoot); + await assertTreeInsideAllowedRoots(config, targetListPath); + await assertTreeInsideAllowedRoots(config, archivedCardPath); const restored = await restoreArchivedCardOnDisk(boardRoot, archivedCardPath, targetListPath); return { ok: true, @@ -1783,7 +1842,7 @@ async function handleToolCall(config, name, args = {}) { const restoredDirectoryName = Object.prototype.hasOwnProperty.call(args, 'restoredDirectoryName') ? String(args.restoredDirectoryName || '') : ''; - await assertAllowedTree(config.allowedRoots, boardRoot); + await assertTreeInsideAllowedRoots(config, archivedListPath); const restored = await restoreArchivedListOnDisk(boardRoot, archivedListPath, restoredDirectoryName); return { @@ -1810,11 +1869,16 @@ async function handleToolCall(config, name, args = {}) { throw new Error('List path resolved outside boardRoot.'); } + await assertInsideAllowedRoots(config, fromListPath, 'fromListName'); + await assertInsideAllowedRoots(config, toListPath, 'toListName'); await ensureExistingDirectory(fromListPath, `List does not exist: ${fromListName}`); await ensureExistingDirectory(toListPath, `List does not exist: ${toListName}`); const sourceFile = validateNameSegment(args.cardFile, 'cardFile'); - const destinationFile = args.newCardFile ? validateNameSegment(args.newCardFile, 'newCardFile') : sourceFile; + const hasExplicitNewCardFile = Object.prototype.hasOwnProperty.call(args, 'newCardFile') + && args.newCardFile != null + && String(args.newCardFile).trim() !== ''; + const destinationFile = hasExplicitNewCardFile ? validateNameSegment(args.newCardFile, 'newCardFile') : sourceFile; if (!sourceFile.endsWith('.md') || !destinationFile.endsWith('.md')) { throw new Error('cardFile and newCardFile must end with .md.'); @@ -1829,32 +1893,39 @@ async function handleToolCall(config, name, args = {}) { await assertInsideAllowedRoots(config, sourcePath, 'source card'); await assertInsideAllowedRoots(config, destinationPath, 'destination card'); + await ensureExistingFile(sourcePath, `Card does not exist: ${fromListName}/${sourceFile}`); let finalDestinationFile = destinationFile; - if (Object.prototype.hasOwnProperty.call(args, 'newCardFile')) { - if (sourcePath !== destinationPath && await pathExists(destinationPath)) { + if (hasExplicitNewCardFile) { + if ( + sourcePath !== destinationPath && + await pathExists(destinationPath) && + !(await isCaseOnlySameEntry(sourcePath, destinationPath)) + ) { throw new Error(`Destination card already exists: ${toListName}/${destinationFile}`); } if (sourcePath !== destinationPath) { - await fs.rename(sourcePath, destinationPath); + await renameWithWindowsRetry(sourcePath, destinationPath); } } else { finalDestinationFile = await insertCardFileAtTop(toListPath, sourcePath, sourceFile); } const finalDestinationPath = path.join(toListPath, finalDestinationFile); - const movedCard = await cardFrontmatter.readCard(finalDestinationPath); - let nextFrontmatter = movedCard.frontmatter; - if (fromListName !== toListName && fromListName !== ARCHIVE_DIRECTORY_NAME && toListName !== ARCHIVE_DIRECTORY_NAME) { - nextFrontmatter = applyCardListMove(nextFrontmatter, { - fromListDirectoryName: fromListName, - fromListDisplayName: getListDisplayName(fromListName), - toListDirectoryName: toListName, - toListDisplayName: getListDisplayName(toListName), + await withFileTransaction(finalDestinationPath, async () => { + const movedCard = await cardFrontmatter.readCard(finalDestinationPath); + let nextFrontmatter = movedCard.frontmatter; + if (fromListName !== toListName && fromListName !== ARCHIVE_DIRECTORY_NAME && toListName !== ARCHIVE_DIRECTORY_NAME) { + nextFrontmatter = applyCardListMove(nextFrontmatter, { + fromListDirectoryName: fromListName, + fromListDisplayName: getListDisplayName(fromListName), + toListDirectoryName: toListName, + toListDisplayName: getListDisplayName(toListName), + }); + } + await cardFrontmatter.writeCard(finalDestinationPath, { + frontmatter: normalizeSignboardCardFrontmatter({ boardRoot, cardPath: finalDestinationPath, frontmatter: nextFrontmatter }), + body: movedCard.body, }); - } - await cardFrontmatter.writeCard(finalDestinationPath, { - frontmatter: normalizeSignboardCardFrontmatter({ boardRoot, cardPath: finalDestinationPath, frontmatter: nextFrontmatter }), - body: movedCard.body, }); return { @@ -2061,13 +2132,17 @@ function serializeMessage(payload, transportMode = DEFAULT_TRANSPORT) { return `${json}\n`; } +const MAX_MCP_HEADER_BYTES = 16 * 1024; +const MAX_MCP_MESSAGE_BYTES = 32 * 1024 * 1024; + function findHeaderBoundary(buffer) { const crlfBoundary = buffer.indexOf('\r\n\r\n'); - if (crlfBoundary >= 0) { + const lfBoundary = buffer.indexOf('\n\n'); + + if (crlfBoundary >= 0 && (lfBoundary < 0 || crlfBoundary < lfBoundary)) { return { index: crlfBoundary, separatorLength: 4 }; } - const lfBoundary = buffer.indexOf('\n\n'); if (lfBoundary >= 0) { return { index: lfBoundary, separatorLength: 2 }; } @@ -2080,8 +2155,16 @@ function startsWithHeaderPrefix(buffer) { return false; } - const preview = buffer.slice(0, 64).toString('utf8').trimStart().toLowerCase(); - return preview.startsWith('content-length:'); + const preview = buffer.slice(0, 64).toString('utf8').replace(/^\ufeff/, '').trimStart().toLowerCase(); + if (!preview || preview.startsWith('{') || preview.startsWith('[')) { + return false; + } + return ( + preview.startsWith('content-length:') || + preview.startsWith('content-type:') || + 'content-length:'.startsWith(preview) || + 'content-type:'.startsWith(preview) + ); } function parseContentLength(headerText) { @@ -2098,8 +2181,12 @@ function parseContentLength(headerText) { continue; } - const value = Number(line.slice(separatorIndex + 1).trim()); - if (Number.isInteger(value) && value >= 0) { + const rawValue = line.slice(separatorIndex + 1).trim(); + if (!/^\d+$/.test(rawValue)) { + return null; + } + const value = Number(rawValue); + if (Number.isSafeInteger(value) && value >= 0 && value <= MAX_MCP_MESSAGE_BYTES) { return value; } @@ -2144,7 +2231,7 @@ function createRpcErrorEnvelope(id, code, message, data) { function validateObject(value, fieldName) { if (!value || typeof value !== 'object' || Array.isArray(value)) { - throw new Error(`${fieldName} must be an object.`); + throw new JsonRpcError(-32602, `${fieldName} must be an object.`); } return value; @@ -2152,12 +2239,60 @@ function validateObject(value, fieldName) { async function startSignboardMcpServer(options = {}) { const config = buildServerConfig(options); + const refreshDesktopState = typeof options.refreshDesktopState === 'function' + ? options.refreshDesktopState + : null; + const pendingChunks = []; let inputBuffer = Buffer.alloc(0); let consumeChain = Promise.resolve(); let transportMode = DEFAULT_TRANSPORT; + let transportModeDetected = false; + let shuttingDown = false; + + const stopServer = (exitCode = 0) => { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (typeof options.onStop === 'function') { + options.onStop(); + return; + } + process.exitCode = exitCode; + }; const write = (payload) => { - process.stdout.write(serializeMessage(payload, transportMode)); + if (shuttingDown || process.stdout.destroyed || !process.stdout.writable) { + return; + } + try { + process.stdout.write(serializeMessage(payload, transportMode)); + } catch (error) { + if (error && (error.code === 'EPIPE' || error.code === 'ERR_STREAM_DESTROYED')) { + stopServer(0); + return; + } + logError('stdout write failed', error); + } + }; + + const refreshConfigForCall = async () => { + if (refreshDesktopState) { + try { + const refreshed = await refreshDesktopState(); + if (refreshed && typeof refreshed === 'object') { + const nextTrusted = normalizeAllowedRootList(refreshed.trustedBoardRoots); + config.trustedBoardRoots = nextTrusted; + config.desktopOpenBoardsState = normalizeOpenBoardsState(refreshed.desktopOpenBoardsState); + config.allowedRoots = mergeAllowedRoots(parseAllowedRoots(), nextTrusted); + } + } catch (error) { + logError('Failed to refresh desktop state.', error); + } + } + config._canonicalAllowedRoots = config.allowedRoots.length > 0 + ? await resolveCanonicalRoots(config.allowedRoots) + : []; }; const handleRequest = async (request) => { @@ -2204,10 +2339,23 @@ async function startSignboardMcpServer(options = {}) { const args = params.arguments == null ? {} : validateObject(params.arguments, 'params.arguments'); try { + await refreshConfigForCall(); const result = await handleToolCall(config, name, args); return buildToolResult(result, 'Done.'); } catch (error) { - return buildToolError(error && error.message ? error.message : String(error || 'Unknown error')); + const details = {}; + if (error && typeof error.code === 'string' && error.code) { + details.code = error.code; + } + if (error instanceof AggregateError && Array.isArray(error.errors) && error.errors.length > 0) { + details.causes = error.errors.map((cause) => (cause && cause.message ? cause.message : String(cause))); + } + return buildToolError( + error && error.message ? error.message : String(error || 'Unknown error'), + Object.keys(details).length > 0 ? details : undefined, + ); + } finally { + config._canonicalAllowedRoots = null; } } @@ -2265,8 +2413,32 @@ async function startSignboardMcpServer(options = {}) { } }; - const consumeInputBuffer = async () => { - while (true) { + const flushPendingChunks = () => { + if (pendingChunks.length === 0) { + return; + } + const toConcat = inputBuffer.length > 0 ? [inputBuffer, ...pendingChunks] : pendingChunks.slice(); + pendingChunks.length = 0; + inputBuffer = Buffer.concat(toConcat); + }; + + const resetEmptyBuffer = () => { + if (inputBuffer.length === 0) { + inputBuffer = Buffer.alloc(0); + } + }; + + const consumeInputBuffer = async (isEof = false) => { + flushPendingChunks(); + + while (inputBuffer.length > 0) { + if (inputBuffer.length > MAX_MCP_MESSAGE_BYTES + MAX_MCP_HEADER_BYTES) { + logError('Incoming MCP payload exceeded maximum size limit.'); + inputBuffer = Buffer.alloc(0); + write(createRpcErrorEnvelope(null, -32600, 'Request payload too large')); + return; + } + const boundary = findHeaderBoundary(inputBuffer); if (boundary) { const headerRaw = inputBuffer.slice(0, boundary.index).toString('utf8'); @@ -2281,57 +2453,115 @@ async function startSignboardMcpServer(options = {}) { } transportMode = HEADER_TRANSPORT; + transportModeDetected = true; const jsonPayload = inputBuffer.slice(messageStart, messageEnd).toString('utf8'); - inputBuffer = inputBuffer.slice(messageEnd); + inputBuffer = messageEnd >= inputBuffer.length + ? Buffer.alloc(0) + : Buffer.from(inputBuffer.subarray(messageEnd)); let parsed; try { parsed = JSON.parse(jsonPayload); } catch (error) { logError('Failed to parse JSON payload.', error); + write(createRpcErrorEnvelope(null, -32700, 'Parse error')); continue; } await processPayload(parsed); + flushPendingChunks(); continue; } if (startsWithHeaderPrefix(inputBuffer)) { - inputBuffer = Buffer.alloc(0); + const afterHeader = boundary.index + boundary.separatorLength; + inputBuffer = afterHeader >= inputBuffer.length + ? Buffer.alloc(0) + : Buffer.from(inputBuffer.subarray(afterHeader)); logError('Received payload with missing/invalid Content-Length header.'); - return; + write(createRpcErrorEnvelope(null, -32700, 'Invalid Content-Length header')); + continue; + } + } + + // If this buffer looks like a partial Content-Length/Content-Type header (or we already locked header framing), + // wait for the full header boundary instead of consuming the header line as NDJSON. + if (startsWithHeaderPrefix(inputBuffer) || (transportModeDetected && transportMode === HEADER_TRANSPORT)) { + if (inputBuffer.length > MAX_MCP_HEADER_BYTES) { + logError('Header block exceeded maximum size limit.'); + inputBuffer = Buffer.alloc(0); + write(createRpcErrorEnvelope(null, -32700, 'Header too large')); } + return; } const newlineIndex = inputBuffer.indexOf('\n'); if (newlineIndex < 0) { + if (!isEof) { + return; + } + const trailingLine = inputBuffer.toString('utf8').trim(); + inputBuffer = Buffer.alloc(0); + if (!trailingLine) { + return; + } + transportMode = NDJSON_TRANSPORT; + transportModeDetected = true; + let parsedTrailing; + try { + parsedTrailing = JSON.parse(trailingLine); + } catch (error) { + logError('Failed to parse trailing NDJSON payload.', error); + write(createRpcErrorEnvelope(null, -32700, 'Parse error')); + return; + } + await processPayload(parsedTrailing); return; } const jsonLine = inputBuffer.slice(0, newlineIndex).toString('utf8').trim(); - inputBuffer = inputBuffer.slice(newlineIndex + 1); + const afterLine = newlineIndex + 1; + inputBuffer = afterLine >= inputBuffer.length + ? Buffer.alloc(0) + : Buffer.from(inputBuffer.subarray(afterLine)); if (!jsonLine) { continue; } transportMode = NDJSON_TRANSPORT; + transportModeDetected = true; let parsedLine; try { parsedLine = JSON.parse(jsonLine); } catch (error) { logError('Failed to parse NDJSON payload.', error); + write(createRpcErrorEnvelope(null, -32700, 'Parse error')); continue; } await processPayload(parsedLine); + flushPendingChunks(); } + + resetEmptyBuffer(); }; + const handleOutputStreamError = (error) => { + if (error && (error.code === 'EPIPE' || error.code === 'ERR_STREAM_DESTROYED')) { + stopServer(0); + return; + } + logError('output stream error', error); + }; + + process.stdout.on('error', handleOutputStreamError); + process.stderr.on('error', handleOutputStreamError); + process.stdin.on('data', (chunk) => { const incomingChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8'); - inputBuffer = Buffer.concat([inputBuffer, incomingChunk]); - consumeChain = consumeChain.then(consumeInputBuffer).catch((error) => { + pendingChunks.push(incomingChunk); + consumeChain = consumeChain.then(() => consumeInputBuffer(false)).catch((error) => { logError('MCP input processing failed.', error); }); }); @@ -2341,30 +2571,40 @@ async function startSignboardMcpServer(options = {}) { }); process.stdin.on('end', () => { - if (typeof options.onStop === 'function') { - options.onStop(); - return; - } - - process.exit(0); + consumeChain = consumeChain + .then(() => consumeInputBuffer(true)) + .catch((error) => { + logError('MCP EOF drain failed.', error); + }) + .finally(() => { + if (typeof options.onStop === 'function') { + stopServer(0); + return; + } + if (process.stdout.writableNeedDrain) { + process.stdout.once('drain', () => process.exit(0)); + } else { + process.exit(0); + } + }); }); process.on('SIGINT', () => { if (typeof options.onStop === 'function') { - options.onStop(); + stopServer(0); return; } - process.exit(0); + consumeChain.finally(() => process.exit(0)); }); process.on('SIGTERM', () => { if (typeof options.onStop === 'function') { - options.onStop(); + stopServer(0); return; } - process.exit(0); + consumeChain.finally(() => process.exit(0)); }); process.stderr.write( diff --git a/lib/obsidianIntegration.js b/lib/obsidianIntegration.js index cc5a166..b62964c 100644 --- a/lib/obsidianIntegration.js +++ b/lib/obsidianIntegration.js @@ -191,23 +191,27 @@ function toObsidianLinkTarget(vaultRoot, notePath) { function pathIsInsideRoot(rootPath, targetPath) { const relativePath = path.relative(path.resolve(rootPath), path.resolve(targetPath)); - return relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath)); + return relativePath === '' || (relativePath !== '..' && !relativePath.startsWith(`..${path.sep}`) && !path.isAbsolute(relativePath)); } function hashBaseContent(content) { return createHash('sha256').update(String(content || ''), 'utf8').digest('hex'); } +function escapeObsidianBaseString(value) { + return String(value || '').replace(/\\/g, '\\\\').replace(/"/g, '\\"'); +} + function buildGeneratedBaseYaml(boardRoot, vaultRoot = '') { const boardName = getBoardDisplayName(boardRoot); const boardRelativeFolder = vaultRoot ? toVaultRelativePath(vaultRoot, boardRoot) : ''; const filters = [ 'file.ext == "md"', - `signboard_board == "${boardName.replace(/"/g, '\\"')}"`, + `signboard_board == "${escapeObsidianBaseString(boardName)}"`, ]; if (boardRelativeFolder && boardRelativeFolder !== '.') { - filters.push(`file.inFolder("${boardRelativeFolder.replace(/"/g, '\\"')}")`); + filters.push(`file.inFolder("${escapeObsidianBaseString(boardRelativeFolder)}")`); } const config = { @@ -535,6 +539,11 @@ async function fileExists(candidatePath) { } async function findVaultNoteByFileName(vaultRoot, fileName) { + const targetLower = String(fileName || '').toLowerCase(); + if (!targetLower) { + return ''; + } + const stack = [path.resolve(vaultRoot)]; while (stack.length > 0) { @@ -547,12 +556,12 @@ async function findVaultNoteByFileName(vaultRoot, fileName) { } for (const entry of entries) { - if (entry.name === '.obsidian') { + if (entry.name.startsWith('.') || entry.name === 'node_modules') { continue; } const entryPath = path.join(currentPath, entry.name); - if (entry.isFile() && entry.name.toLowerCase() === fileName.toLowerCase()) { + if (entry.isFile() && entry.name.toLowerCase() === targetLower) { return entryPath; } diff --git a/main.js b/main.js index 3eb60e3..f9246ce 100644 --- a/main.js +++ b/main.js @@ -13,6 +13,9 @@ const fsPromises = fs.promises; const http = require('http'); const path = require('path'); const { renameManagedDirectory } = require('./lib/directoryRename'); +const { atomicWriteFile } = require('./lib/atomicFile'); +const { mapFileReads } = require('./lib/fileReadQueue'); +const { withFileTransaction } = require('./lib/fileTransaction'); const { pathToFileURL } = require('url'); const cardFrontmatter = require('./lib/cardFrontmatter'); const { readCardWithTimestamps } = require('./lib/cardTimestamps'); @@ -52,7 +55,7 @@ const { const { formatLocalIsoDate } = require('./shared/localDate'); const { formatReleaseNotesForDialog } = require('./lib/updateReleaseNotes'); const { inspectDebianPackageFile, inspectPacmanPackageFile } = require('./lib/releaseArtifactValidation'); -const { installPacmanPackage, isPacmanPackagePath } = require('./lib/linuxPackageInstaller'); +const { installPacmanPackageAsync, isPacmanPackagePath } = require('./lib/linuxPackageInstaller'); const { getInvalidLinuxPackagePresentation, getUpdaterErrorPresentation, @@ -235,7 +238,7 @@ function isPathInsideRoot(rootPath, targetPath) { } const relative = path.relative(normalizedRoot, normalizedTarget); - return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative)); + return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)); } function getTrustedBoardRootsPath() { @@ -429,10 +432,45 @@ function clearListWatchers(watchState) { watchState.listWatchers.clear(); } +function invalidateExternalPublishedCalendarCache() { + if (typeof externalPublishedCalendarFeedCache === 'object' && externalPublishedCalendarFeedCache) { + externalPublishedCalendarFeedCache.builtAt = 0; + } +} + function bumpBoardWatchToken(watchState) { if (watchState) { watchState.changeToken += 1; } + invalidateExternalPublishedCalendarCache(); +} + +const IGNORED_WATCH_BASENAMES = new Set(['.ds_store', 'thumbs.db', 'desktop.ini']); + +function shouldIgnoreWatchedFilename(rawFilename) { + if (!rawFilename) { + return false; + } + + const normalized = String(rawFilename).replace(/\\/g, '/'); + const segments = normalized.split('/').filter(Boolean); + if (segments.length === 0) { + return false; + } + + const baseName = segments[segments.length - 1]; + const lowerBase = baseName.toLowerCase(); + if ( + IGNORED_WATCH_BASENAMES.has(lowerBase) || + lowerBase.endsWith('.tmp') || + lowerBase.endsWith('.sb-lock') || + lowerBase.endsWith('.sb-lock.reap') || + lowerBase === '.signboard-list-order.json' + ) { + return true; + } + + return segments.some((segment) => segment.startsWith('.')); } function attachDirectoryWatcher(directoryPath, onChange, options = {}) { @@ -445,7 +483,10 @@ function attachDirectoryWatcher(directoryPath, onChange, options = {}) { } try { - const watcher = fs.watch(directoryPath, watchOptions, () => { + const watcher = fs.watch(directoryPath, watchOptions, (_eventType, filename) => { + if (options.filterNoise === true && shouldIgnoreWatchedFilename(filename)) { + return; + } onChange(); }); @@ -466,17 +507,28 @@ async function refreshBoardListWatchers(watchState) { return; } + const expectedRoot = watchState.activeRoot; + const expectedGeneration = watchState.generation || 0; + let entries = []; try { - entries = await fsPromises.readdir(watchState.activeRoot, { withFileTypes: true }); + entries = await fsPromises.readdir(expectedRoot, { withFileTypes: true }); } catch { return; } + if ( + watchState.activeRoot !== expectedRoot || + (watchState.generation || 0) !== expectedGeneration || + watchState.usingRecursiveRootWatch + ) { + return; + } + const expectedListPaths = new Set( entries - .filter((entry) => entry.isDirectory()) - .map((entry) => normalizeAbsolutePath(path.join(watchState.activeRoot, entry.name))), + .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.')) + .map((entry) => normalizeAbsolutePath(path.join(expectedRoot, entry.name))), ); for (const [listPath, watcher] of watchState.listWatchers.entries()) { @@ -493,7 +545,7 @@ async function refreshBoardListWatchers(watchState) { const watcher = attachDirectoryWatcher(listPath, () => { bumpBoardWatchToken(watchState); - }); + }, { filterNoise: true }); if (watcher) { watchState.listWatchers.set(listPath, watcher); @@ -520,6 +572,7 @@ async function stopBoardWatchForState(watchState) { return { ok: true }; } + watchState.generation = (watchState.generation || 0) + 1; clearBoardRescanTimer(watchState); clearListWatchers(watchState); closeWatcher(watchState.rootWatcher); @@ -551,10 +604,19 @@ async function startBoardWatchForSender(sender, boardRoot) { await stopBoardWatchForState(watchState); watchState.activeRoot = normalizedRoot; + const watchGeneration = watchState.generation || 0; const onRootWatchChange = () => { bumpBoardWatchToken(watchState); scheduleBoardWatchRescan(watchState); }; + const onRootWatchError = () => { + if ((watchState.generation || 0) !== watchGeneration) { + return; + } + closeWatcher(watchState.rootWatcher); + watchState.rootWatcher = null; + onRootWatchChange(); + }; let rootWatcher = null; watchState.usingRecursiveRootWatch = false; @@ -562,7 +624,8 @@ async function startBoardWatchForSender(sender, boardRoot) { if (SUPPORTS_RECURSIVE_WATCH) { rootWatcher = attachDirectoryWatcher(normalizedRoot, onRootWatchChange, { recursive: true, - onError: onRootWatchChange, + filterNoise: true, + onError: onRootWatchError, }); if (rootWatcher) { @@ -572,7 +635,8 @@ async function startBoardWatchForSender(sender, boardRoot) { if (!rootWatcher) { rootWatcher = attachDirectoryWatcher(normalizedRoot, onRootWatchChange, { - onError: onRootWatchChange, + filterNoise: true, + onError: onRootWatchError, }); } @@ -945,10 +1009,47 @@ async function tryCacheFaviconFromUrl(iconUrl, cacheBaseName) { const cacheDir = getLinkedObjectIconCacheDir(); await fsPromises.mkdir(cacheDir, { recursive: true }); const iconPath = path.join(cacheDir, `${cacheBaseName}${getFaviconExtension(contentType)}`); - await fsPromises.writeFile(iconPath, Buffer.from(arrayBuffer)); + await atomicWriteFile(iconPath, Buffer.from(arrayBuffer)); return iconPath; } +const LINKED_OBJECT_HTML_MAX_BYTES = 64 * 1024; + +async function readResponseTextBounded(response, maxBytes = LINKED_OBJECT_HTML_MAX_BYTES) { + if (!response || !response.body || typeof response.body.getReader !== 'function') { + const text = await response.text(); + return text.slice(0, maxBytes); + } + + const reader = response.body.getReader(); + const decoder = new TextDecoder('utf-8'); + let output = ''; + let bytesRead = 0; + + try { + while (bytesRead < maxBytes) { + const { value, done } = await reader.read(); + if (done) { + break; + } + if (value) { + const remaining = maxBytes - bytesRead; + const slice = value.byteLength > remaining ? value.subarray(0, remaining) : value; + bytesRead += slice.byteLength; + output += decoder.decode(slice, { stream: true }); + if (output.includes('')) { + break; + } + } + } + output += decoder.decode(); + } finally { + await reader.cancel().catch(() => {}); + } + + return output; +} + async function cacheFaviconForUrl(url) { if (process.env.SIGNBOARD_TEST_DISABLE_FAVICON_FETCH === '1') { return ''; @@ -986,7 +1087,7 @@ async function cacheFaviconForUrl(url) { }, }); if (pageResponse && pageResponse.ok && String(pageResponse.headers.get('content-type') || '').includes('html')) { - const html = await pageResponse.text(); + const html = await readResponseTextBounded(pageResponse); const iconMatch = html.match(/]+rel=["'][^"']*(?:icon|apple-touch-icon)[^"']*["'][^>]*>/i); const hrefMatch = iconMatch && iconMatch[0].match(/\shref=["']([^"']+)["']/i); if (hrefMatch && hrefMatch[1]) { @@ -1576,22 +1677,25 @@ function normalizeCardFrontmatterForBoardPath(sender, cardPath, frontmatter = {} async function refreshCardSignboardMetadata(boardRoot, cardPath) { if (!isBoardCardPath(boardRoot, cardPath)) { - return null; + return { frontmatter: null, updated: false }; } - const card = await cardFrontmatter.readCard(cardPath); + const originalRaw = await fsPromises.readFile(cardPath, 'utf8'); + const parsed = cardFrontmatter.parseCardContent(originalRaw); + const currentFrontmatter = cardFrontmatter.normalizeFrontmatter(parsed.frontmatter); const nextFrontmatter = obsidianIntegration.normalizeSignboardCardFrontmatter({ boardRoot, cardPath, - frontmatter: card.frontmatter, + frontmatter: currentFrontmatter, }); + const nextSerialized = cardFrontmatter.serializeCard(nextFrontmatter, parsed.body, cardPath); - await cardFrontmatter.writeCard(cardPath, { - frontmatter: nextFrontmatter, - body: card.body, - }); + if (nextSerialized === originalRaw) { + return { frontmatter: nextFrontmatter, updated: false }; + } - return nextFrontmatter; + await atomicWriteFile(cardPath, nextSerialized, 'utf8'); + return { frontmatter: nextFrontmatter, updated: true }; } async function refreshBoardSignboardMetadata(boardRoot) { @@ -1601,17 +1705,21 @@ async function refreshBoardSignboardMetadata(boardRoot) { } const listNames = await listBoardDirectories(normalizedBoardRoot); - let cardsUpdated = 0; + const cardPaths = []; for (const listName of listNames) { const listPath = path.join(normalizedBoardRoot, listName); const cardFileNames = await listMarkdownCardFileNames(listPath); for (const cardFileName of cardFileNames) { - await refreshCardSignboardMetadata(normalizedBoardRoot, path.join(listPath, cardFileName)); - cardsUpdated += 1; + cardPaths.push(path.join(listPath, cardFileName)); } } + const results = await mapFileReads(cardPaths, (cardPath) => ( + refreshCardSignboardMetadata(normalizedBoardRoot, cardPath) + )); + const cardsUpdated = results.filter((entry) => entry && entry.updated).length; + return { cardsUpdated }; } @@ -1746,25 +1854,30 @@ async function adoptLegacyBoardRootsForSender(sender, boardRoots) { }; } +const boardNameCollator = new Intl.Collator(undefined, { + usage: 'sort', + sensitivity: 'base', + numeric: true, + ignorePunctuation: true, + localeMatcher: 'lookup', +}); + async function listBoardDirectories(boardRoot, options = {}) { const includeArchive = options.includeArchive === true; const entries = await fsPromises.readdir(boardRoot, { withFileTypes: true }); return entries - .filter((entry) => entry.isDirectory()) + .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.')) .map((entry) => entry.name) - .filter((entryName) => includeArchive || entryName !== 'XXX-Archive'); + .filter((entryName) => includeArchive || entryName !== 'XXX-Archive') + .sort((left, right) => boardNameCollator.compare(left, right)); } async function listMarkdownCardFileNames(listPath) { const entries = await fsPromises.readdir(listPath, { withFileTypes: true }); return entries - .filter((entry) => entry.isFile() && entry.name.endsWith('.md')) + .filter((entry) => entry.isFile() && !entry.name.startsWith('.') && entry.name.endsWith('.md')) .map((entry) => entry.name) - .sort((left, right) => left.localeCompare(right, undefined, { - numeric: true, - sensitivity: 'base', - ignorePunctuation: true, - })); + .sort((left, right) => boardNameCollator.compare(left, right)); } function sanitizeImportedName(value) { @@ -1953,49 +2066,23 @@ async function resolveSignboardOpenBoardProtocolLink(boardPath) { }; } -async function findCardInBoardRootBySignboardId(boardRoot, cardId) { +async function scanBoardCardPathsForSignboardId(boardRoot, normalizedCardId) { const normalizedBoardRoot = normalizeBoardRootPath(boardRoot); - const normalizedCardId = String(cardId || '').trim(); if (!normalizedBoardRoot || !normalizedCardId) { - return null; + return { match: null, fallbackCardPaths: [] }; } let listEntries = []; try { listEntries = await fsPromises.readdir(normalizedBoardRoot, { withFileTypes: true }); } catch { - return null; + return { match: null, fallbackCardPaths: [] }; } - for (const listEntry of listEntries) { - if (!listEntry.isDirectory()) { - continue; - } - - const listPath = path.join(normalizedBoardRoot, listEntry.name); - let cardEntries = []; - try { - cardEntries = await fsPromises.readdir(listPath, { withFileTypes: true }); - } catch { - continue; - } - - const filenameMatch = cardEntries.find((cardEntry) => ( - cardEntry.isFile() && - cardEntry.name.endsWith('.md') && - obsidianIntegration.getCardFileId(cardEntry.name) === normalizedCardId - )); - - if (filenameMatch) { - return { - boardRoot: normalizedBoardRoot, - cardPath: path.join(listPath, filenameMatch.name), - }; - } - } + const fallbackCardPaths = []; for (const listEntry of listEntries) { - if (!listEntry.isDirectory()) { + if (!listEntry.isDirectory() || listEntry.name.startsWith('.')) { continue; } @@ -2008,26 +2095,25 @@ async function findCardInBoardRootBySignboardId(boardRoot, cardId) { } for (const cardEntry of cardEntries) { - if (!cardEntry.isFile() || !cardEntry.name.endsWith('.md')) { + if (!cardEntry.isFile() || cardEntry.name.startsWith('.') || !cardEntry.name.endsWith('.md')) { continue; } const cardPath = path.join(listPath, cardEntry.name); - try { - const card = await cardFrontmatter.readCard(cardPath); - if (String(card.frontmatter.signboard_id || '').trim() === normalizedCardId) { - return { + if (obsidianIntegration.getCardFileId(cardEntry.name) === normalizedCardId) { + return { + match: { boardRoot: normalizedBoardRoot, cardPath, - }; - } - } catch { - // Ignore malformed cards while resolving a deep link. + }, + fallbackCardPaths: [], + }; } + fallbackCardPaths.push({ boardRoot: normalizedBoardRoot, cardPath }); } } - return null; + return { match: null, fallbackCardPaths }; } async function resolveSignboardProtocolLink(candidateUrl) { @@ -2040,16 +2126,45 @@ async function resolveSignboardProtocolLink(candidateUrl) { return resolveSignboardOpenBoardProtocolLink(parsed.boardPath); } + const normalizedCardId = String(parsed.cardId || '').trim(); const trustedRoots = Array.from(readTrustedBoardRoots()); + const fallbackCandidates = []; + + // Pass 1: filename-only scan across all trusted boards before reading any card content. for (const boardRoot of trustedRoots) { - const match = await findCardInBoardRootBySignboardId(boardRoot, parsed.cardId); - if (match) { + const scan = await scanBoardCardPathsForSignboardId(boardRoot, normalizedCardId); + if (scan.match) { return { ok: true, - ...match, + ...scan.match, cardId: parsed.cardId, }; } + fallbackCandidates.push(...scan.fallbackCardPaths); + } + + // Pass 2: bounded frontmatter fallback for cards whose filename suffix does not match signboard_id. + let frontmatterMatch = null; + await mapFileReads(fallbackCandidates, async (candidate) => { + if (frontmatterMatch) { + return; + } + try { + const card = await cardFrontmatter.readCard(candidate.cardPath); + if (String(card.frontmatter.signboard_id || '').trim() === normalizedCardId && !frontmatterMatch) { + frontmatterMatch = candidate; + } + } catch { + // Ignore malformed cards while resolving a deep link. + } + }); + + if (frontmatterMatch) { + return { + ok: true, + ...frontmatterMatch, + cardId: parsed.cardId, + }; } return { @@ -2060,7 +2175,7 @@ async function resolveSignboardProtocolLink(candidateUrl) { }; } -async function dispatchSignboardProtocolUrl(candidateUrl) { +async function dispatchSignboardProtocolUrl(candidateUrl, options = {}) { if (!parseSignboardProtocolUrl(candidateUrl)) return; // macOS URL delivery need not also deliver activate. const win = ensureMainWindowVisible(); @@ -2069,12 +2184,21 @@ async function dispatchSignboardProtocolUrl(candidateUrl) { return; } + if (!options.fromFinishLoad && win.webContents.isLoading()) { + pendingSignboardProtocolUrl = candidateUrl; + return; + } + const resolved = await resolveSignboardProtocolLink(candidateUrl); if (!resolved) { return; } - if (win.webContents.isLoading()) { + if (win.isDestroyed()) { + return; + } + + if (!options.fromFinishLoad && win.webContents.isLoading()) { pendingSignboardProtocolUrl = candidateUrl; return; } @@ -2100,7 +2224,7 @@ async function flushPendingSignboardProtocolUrl() { const nextUrl = pendingSignboardProtocolUrl; pendingSignboardProtocolUrl = ''; if (nextUrl) { - await dispatchSignboardProtocolUrl(nextUrl); + await dispatchSignboardProtocolUrl(nextUrl, { fromFinishLoad: true }); } } @@ -2490,7 +2614,9 @@ function createWindow() { }); return { action: 'deny' }; } - shell.openExternal(url); + shell.openExternal(url).catch((error) => { + console.error('Failed to open external URL.', error); + }); return { action: 'deny' }; } @@ -2511,7 +2637,9 @@ function createWindow() { }); return; } - shell.openExternal(url); + shell.openExternal(url).catch((error) => { + console.error('Failed to open external URL.', error); + }); } }); @@ -2569,6 +2697,18 @@ function createWindow() { } mainWindow = null; + + const now = Date.now(); + recentRendererCrashTimestamps = recentRendererCrashTimestamps.filter((ts) => now - ts < 60000); + recentRendererCrashTimestamps.push(now); + if (recentRendererCrashTimestamps.length > 3) { + dialog.showErrorBox( + 'Signboard stopped unexpectedly', + 'The Signboard window crashed repeatedly. Please restart Signboard to continue.', + ); + return; + } + createWindow(); }); @@ -2824,16 +2964,31 @@ function closeOmarchyThemeWatcher() { omarchyThemeWatcher = null; } +let omarchyWatcherConsecutiveErrors = 0; +let lastOmarchyFocusCheckAt = 0; +let recentRendererCrashTimestamps = []; +let externalPublishedCalendarApplyQueue = Promise.resolve(); +let externalPublishedCalendarFeedCache = { + feed: '', + etag: '', + builtAt: 0, + inFlight: null, +}; +const EXTERNAL_CALENDAR_CACHE_TTL_MS = 3000; + function scheduleOmarchyThemeRefresh() { if (omarchyThemeRefreshTimer) { clearTimeout(omarchyThemeRefreshTimer); } + const delayMs = omarchyWatcherConsecutiveErrors > 0 + ? Math.min(5000, 120 * Math.pow(2, omarchyWatcherConsecutiveErrors)) + : 120; omarchyThemeRefreshTimer = setTimeout(() => { omarchyThemeRefreshTimer = null; refreshOmarchyThemeStatus({ notify: true, restartWatcher: true }).catch((error) => { console.error('Unable to refresh the Omarchy theme.', error); }); - }, 120); + }, delayMs); } function startOmarchyThemeWatcher() { @@ -2846,8 +3001,20 @@ function startOmarchyThemeWatcher() { const themeDirectory = omarchyThemeStatus.themeDirectory || omarchyTheme.getDefaultOmarchyThemeDirectory(); const watchDirectory = path.dirname(themeDirectory); - omarchyThemeWatcher = attachDirectoryWatcher(watchDirectory, scheduleOmarchyThemeRefresh, { - onError: scheduleOmarchyThemeRefresh, + if (!fs.existsSync(watchDirectory)) { + return; + } + omarchyThemeWatcher = attachDirectoryWatcher(watchDirectory, () => { + omarchyWatcherConsecutiveErrors = 0; + scheduleOmarchyThemeRefresh(); + }, { + onError: () => { + closeOmarchyThemeWatcher(); + omarchyWatcherConsecutiveErrors += 1; + if (omarchyWatcherConsecutiveErrors <= 5) { + scheduleOmarchyThemeRefresh(); + } + }, }); } @@ -2885,19 +3052,56 @@ async function stopExternalPublishedCalendarServer() { await new Promise((resolve) => { server.close(() => resolve()); + if (typeof server.closeIdleConnections === 'function') { + server.closeIdleConnections(); + } + if (typeof server.closeAllConnections === 'function') { + server.closeAllConnections(); + } }); } async function createExternalPublishedCalendarFeed() { - const boardRoots = Array.from(readTrustedBoardRoots()); - return buildExternalPublishedCalendarFeed({ - boardRoots, - readBoardSettings: (boardRoot) => boardLabels.readBoardSettings(boardRoot, { ensureFile: false }), - listLists: (boardRoot) => listBoardDirectories(boardRoot), - listCards: (listPath) => listMarkdownCardFileNames(listPath), - readCard: (cardPath) => cardFrontmatter.readCard(cardPath), - getBoardName: (boardRoot) => path.basename(String(boardRoot || '').replace(/[\\/]+$/, '')), - }); + const now = Date.now(); + if ( + externalPublishedCalendarFeedCache.feed && + now - externalPublishedCalendarFeedCache.builtAt < EXTERNAL_CALENDAR_CACHE_TTL_MS + ) { + return { + feed: externalPublishedCalendarFeedCache.feed, + etag: externalPublishedCalendarFeedCache.etag, + }; + } + + if (externalPublishedCalendarFeedCache.inFlight) { + return externalPublishedCalendarFeedCache.inFlight; + } + + const buildPromise = (async () => { + const boardRoots = Array.from(readTrustedBoardRoots()); + const feed = await buildExternalPublishedCalendarFeed({ + boardRoots, + readBoardSettings: (boardRoot) => boardLabels.readBoardSettings(boardRoot, { ensureFile: false }), + listLists: (boardRoot) => listBoardDirectories(boardRoot), + listCards: (listPath) => listMarkdownCardFileNames(listPath), + readCard: (cardPath) => cardFrontmatter.readCard(cardPath), + getBoardName: (boardRoot) => path.basename(String(boardRoot || '').replace(/[\\/]+$/, '')), + }); + const etag = `"${createHash('sha1').update(feed, 'utf8').digest('hex')}"`; + externalPublishedCalendarFeedCache.feed = feed; + externalPublishedCalendarFeedCache.etag = etag; + externalPublishedCalendarFeedCache.builtAt = Date.now(); + return { feed, etag }; + })(); + + externalPublishedCalendarFeedCache.inFlight = buildPromise; + try { + return await buildPromise; + } finally { + if (externalPublishedCalendarFeedCache.inFlight === buildPromise) { + externalPublishedCalendarFeedCache.inFlight = null; + } + } } async function handleExternalPublishedCalendarRequest(request, response) { @@ -2925,19 +3129,43 @@ async function handleExternalPublishedCalendarRequest(request, response) { return; } - const feed = request.method === 'HEAD' ? '' : await createExternalPublishedCalendarFeed(); + if (request.method === 'HEAD') { + response.writeHead(200, { + 'Cache-Control': 'no-store', + 'Content-Disposition': 'inline; filename="signboard-external-published-calendar.ics"', + 'Content-Type': 'text/calendar; charset=utf-8', + }); + response.end(''); + return; + } + + const { feed, etag } = await createExternalPublishedCalendarFeed(); + if (request.headers && request.headers['if-none-match'] === etag) { + response.writeHead(304, { + 'Cache-Control': 'no-store', + ETag: etag, + }); + response.end(); + return; + } + response.writeHead(200, { 'Cache-Control': 'no-store', 'Content-Disposition': 'inline; filename="signboard-external-published-calendar.ics"', 'Content-Type': 'text/calendar; charset=utf-8', + ETag: etag, }); response.end(feed); } catch (error) { console.error('Failed to serve External Published Calendar feed.', error); - response.writeHead(500, { - 'Content-Type': 'text/plain; charset=utf-8', - }); - response.end('Unable to build calendar feed'); + if (!response.headersSent && !response.writableEnded) { + response.writeHead(500, { + 'Content-Type': 'text/plain; charset=utf-8', + }); + response.end('Unable to build calendar feed'); + } else if (!response.writableEnded) { + response.end(); + } } } @@ -2965,8 +3193,12 @@ async function startExternalPublishedCalendarServer(settings) { await new Promise((resolve) => { const server = http.createServer((request, response) => { - handleExternalPublishedCalendarRequest(request, response); + handleExternalPublishedCalendarRequest(request, response).catch((error) => { + console.error('Unhandled error serving External Published Calendar feed.', error); + }); }); + server.keepAliveTimeout = 5000; + server.requestTimeout = 15000; server.on('error', (error) => { if (externalPublishedCalendarServer === server) { @@ -3000,22 +3232,29 @@ async function startExternalPublishedCalendarServer(settings) { } async function applyExternalPublishedCalendarSettings(settings = {}) { - const normalizedSettings = appSettings.normalizeAppSettings(settings).externalPublishedCalendar; - externalPublishedCalendarSettings = normalizedSettings; + const run = async () => { + const normalizedSettings = appSettings.normalizeAppSettings(settings).externalPublishedCalendar; + externalPublishedCalendarSettings = normalizedSettings; + externalPublishedCalendarFeedCache.builtAt = 0; - if (!normalizedSettings.enabled) { - await stopExternalPublishedCalendarServer(); - externalPublishedCalendarStatus = { - enabled: false, - running: false, - port: normalizedSettings.port, - url: '', - message: 'Disabled', - }; - return; - } + if (!normalizedSettings.enabled) { + await stopExternalPublishedCalendarServer(); + externalPublishedCalendarStatus = { + enabled: false, + running: false, + port: normalizedSettings.port, + url: '', + message: 'Disabled', + }; + return; + } - await startExternalPublishedCalendarServer(normalizedSettings); + await startExternalPublishedCalendarServer(normalizedSettings); + }; + + const next = externalPublishedCalendarApplyQueue.then(run, run); + externalPublishedCalendarApplyQueue = next.catch(() => {}); + return next; } async function ensureExternalPublishedCalendarToken(settings = {}) { @@ -3448,7 +3687,7 @@ async function saveUpdatePreferences() { const payload = { reminderByVersion: updateState.reminderByVersion, }; - await fsPromises.writeFile(prefsPath, JSON.stringify(payload, null, 2), 'utf8'); + await atomicWriteFile(prefsPath, JSON.stringify(payload, null, 2), 'utf8'); } function isReminderExpired(version) { @@ -3639,7 +3878,7 @@ async function showUpdateReadyDialog(info) { await clearReminder(info?.version); if (process.platform === 'linux' && isPacmanPackagePath(info?.downloadedFile)) { try { - installPacmanPackage(info.downloadedFile); + await installPacmanPackageAsync(info.downloadedFile); app.relaunch(); app.quit(); } catch (error) { @@ -3900,7 +4139,8 @@ function setupAutoUpdater() { }); // Check shortly after launch and then periodically while running. - setTimeout(() => { + updateState.startupCheckTimeoutId = setTimeout(() => { + updateState.startupCheckTimeoutId = null; checkForUpdates({ manual: false }); }, 10000); updateState.checkIntervalId = setInterval(() => { @@ -3948,7 +4188,9 @@ function buildApplicationMenu() { }); const createDocumentationMenuItem = () => ({ label: 'Documentation', - click: () => shell.openExternal(`https://github.com/${GITHUB_OWNER}/${GITHUB_REPO}#documentation`), + click: () => { + shell.openExternal(`https://github.com/${GITHUB_OWNER}/${GITHUB_REPO}#documentation`).catch(() => {}); + }, }); const createKeyboardShortcutsMenuItem = () => ({ label: 'Keyboard Shortcuts', @@ -4102,7 +4344,9 @@ function buildApplicationMenu() { : null, { label: 'Signboard Releases', - click: () => shell.openExternal(`https://github.com/${GITHUB_OWNER}/${GITHUB_REPO}/releases`), + click: () => { + shell.openExternal(`https://github.com/${GITHUB_OWNER}/${GITHUB_REPO}/releases`).catch(() => {}); + }, }, ].filter(Boolean), }); @@ -4390,23 +4634,27 @@ ipcMain.handle('board-call', async (event, payload = {}) => { ...card, frontmatter: normalizeCardFrontmatterForBoardPath(event.sender, filePath, card.frontmatter), }); - await autoSyncManagedObsidianBaseForCardPath(event.sender, filePath); + invalidateExternalPublishedCalendarCache(); return { ok: true }; } case 'updateFrontmatter': { const filePath = requireWritablePath(event.sender, args[0], { allowTrusted: true }); - const currentCard = await cardFrontmatter.readCard(filePath); - const nextFrontmatter = normalizeCardFrontmatterForBoardPath(event.sender, filePath, { - ...currentCard.frontmatter, - ...(args[1] && typeof args[1] === 'object' && !Array.isArray(args[1]) ? args[1] : {}), - }); - await cardFrontmatter.writeCard(filePath, { - frontmatter: nextFrontmatter, - body: currentCard.body, + const partial = args[1] && typeof args[1] === 'object' && !Array.isArray(args[1]) ? args[1] : {}; + const updated = await withFileTransaction(filePath, async () => { + const currentCard = await cardFrontmatter.readCard(filePath); + const nextFrontmatter = normalizeCardFrontmatterForBoardPath(event.sender, filePath, { + ...currentCard.frontmatter, + ...partial, + }); + await cardFrontmatter.writeCard(filePath, { + frontmatter: nextFrontmatter, + body: currentCard.body, + }); + return cardFrontmatter.normalizeFrontmatter(nextFrontmatter); }); - await autoSyncManagedObsidianBaseForCardPath(event.sender, filePath); - return cardFrontmatter.normalizeFrontmatter(nextFrontmatter); + invalidateExternalPublishedCalendarCache(); + return updated; } case 'normalizeFrontmatter': @@ -4419,7 +4667,9 @@ ipcMain.handle('board-call', async (event, payload = {}) => { case 'updateBoardLabels': { const boardRoot = requireWritableBoardRoot(event.sender, args[0], { allowTrusted: true }); - return boardLabels.updateBoardLabels(boardRoot, args[1]); + const updated = await boardLabels.updateBoardLabels(boardRoot, args[1]); + invalidateExternalPublishedCalendarCache(); + return updated; } case 'updateBoardThemeOverrides': { @@ -4429,7 +4679,9 @@ ipcMain.handle('board-call', async (event, payload = {}) => { case 'updateBoardSettings': { const boardRoot = requireWritableBoardRoot(event.sender, args[0], { allowTrusted: true }); - return boardLabels.updateBoardSettings(boardRoot, args[1]); + const updated = await boardLabels.updateBoardSettings(boardRoot, args[1]); + invalidateExternalPublishedCalendarCache(); + return updated; } case 'duplicateBoard': { @@ -4446,7 +4698,7 @@ ipcMain.handle('board-call', async (event, payload = {}) => { boardName: options.boardName, }); addTrustedBoardRoot(result.boardRoot); - await autoSyncManagedObsidianBaseForBoard(result.boardRoot, { refreshMetadata: true }); + await autoSyncManagedObsidianBaseForBoard(result.boardRoot); return result; } @@ -4469,7 +4721,6 @@ ipcMain.handle('board-call', async (event, payload = {}) => { frontmatter, body, }); - await autoSyncManagedObsidianBaseForCardPath(event.sender, filePath); return { ok: true }; } @@ -4594,20 +4845,14 @@ ipcMain.handle('board-call', async (event, payload = {}) => { } const reorderedCards = await reorderCardFilesInList(targetListPath, orderedCardPaths); - let movedAcrossLists = false; for (const cardEntry of reorderedCards) { const sourceListPath = path.dirname(cardEntry.sourcePath); if (sourceListPath !== targetListPath) { - movedAcrossLists = true; await recordCardListMove(boardRoot, cardEntry.cardPath, sourceListPath, targetListPath); } } - if (movedAcrossLists) { - await autoSyncManagedObsidianBaseForBoard(boardRoot); - } - return { ok: true, cards: reorderedCards, @@ -4687,12 +4932,8 @@ ipcMain.handle('board-call', async (event, payload = {}) => { if (sourceListPath !== targetListPath) { await recordCardListMove(boardRoot, movedCardPath, sourceListPath, targetListPath); - } else { - await refreshCardSignboardMetadata(boardRoot, movedCardPath); } - await autoSyncManagedObsidianBaseForBoard(boardRoot); - return { ok: true, cardFile: movedCardFile, @@ -4716,17 +4957,28 @@ ipcMain.handle('board-call', async (event, payload = {}) => { throw new Error('UNAUTHORIZED_PATH'); } - if (movingBoardRoot || operation === 'moveList') { - await renameManagedDirectory(activeBoardRoot, sourcePath, destinationPath); - } else { - await fsPromises.rename(sourcePath, destinationPath); + if (movingBoardRoot) { + // On Windows, an active recursive fs.watch handle on activeBoardRoot blocks fs.rename with EPERM/EBUSY. + await stopBoardWatchForSender(event.sender); + } + + try { + if (movingBoardRoot || operation === 'moveList') { + await renameManagedDirectory(activeBoardRoot, sourcePath, destinationPath); + } else { + await fsPromises.rename(sourcePath, destinationPath); + } + } catch (error) { + if (movingBoardRoot) { + await startBoardWatchForSender(event.sender, activeBoardRoot).catch(() => {}); + } + throw error; } if (movingBoardRoot) { replaceTrustedBoardRoot(sourcePath, destinationPath); senderState.activeBoardRoot = destinationPath; - await stopBoardWatchForSender(event.sender); - await autoSyncManagedObsidianBaseForBoard(destinationPath, { refreshMetadata: true }); + await autoSyncManagedObsidianBaseForBoard(destinationPath); } return { ok: true }; @@ -5152,9 +5404,17 @@ app.on('browser-window-focus', () => { } ensureApplicationMenu(); - refreshOmarchyThemeStatus({ notify: true, restartWatcher: !omarchyThemeWatcher }).catch((error) => { - console.error('Unable to refresh the Omarchy theme after focus.', error); - }); + const now = Date.now(); + const hasOmarchyEnv = Boolean(String(process.env.SIGNBOARD_OMARCHY_THEME_DIR || '').trim()); + if ( + (process.platform === 'linux' || hasOmarchyEnv) && + (omarchyThemeStatus.detected || omarchyThemeWatcher || hasOmarchyEnv || now - lastOmarchyFocusCheckAt >= 15000) + ) { + lastOmarchyFocusCheckAt = now; + refreshOmarchyThemeStatus({ notify: true, restartWatcher: !omarchyThemeWatcher }).catch((error) => { + console.error('Unable to refresh the Omarchy theme after focus.', error); + }); + } }); app.on('before-quit', () => { @@ -5165,14 +5425,26 @@ app.on('before-quit', () => { } mcpPowerSaveBlockerId = null; + if (updateState.startupCheckTimeoutId) { + clearTimeout(updateState.startupCheckTimeoutId); + updateState.startupCheckTimeoutId = null; + } + if (updateState.checkIntervalId) { clearInterval(updateState.checkIntervalId); updateState.checkIntervalId = null; } if (externalPublishedCalendarServer) { - externalPublishedCalendarServer.close(); + const server = externalPublishedCalendarServer; externalPublishedCalendarServer = null; + server.close(); + if (typeof server.closeIdleConnections === 'function') { + server.closeIdleConnections(); + } + if (typeof server.closeAllConnections === 'function') { + server.closeAllConnections(); + } } closeOmarchyThemeWatcher(); diff --git a/package-lock.json b/package-lock.json index bf3c2fa..ecd87fd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "signboard", - "version": "1.7.8", + "version": "1.7.9", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "signboard", - "version": "1.7.8", + "version": "1.7.9", "license": "MIT", "dependencies": { "electron-updater": "^6.8.3", diff --git a/package.json b/package.json index 4c47d8f..f7035b8 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "signboard", "productName": "Signboard", - "version": "1.7.8", + "version": "1.7.9", "description": "A fast, local-first Kanban board for Markdown files.", "homepage": "https://github.com/cdevroe/signboard", "repository": { @@ -112,7 +112,8 @@ "test:build-info": "node scripts/test-build-info.js", "test:list-actions": "node scripts/test-list-actions.js", "test:editor-paths": "node scripts/test-editor-paths.js", - "test:board-refresh": "node scripts/test-board-refresh.js" + "test:board-refresh": "node scripts/test-board-refresh.js", + "test:speed-reliability": "node scripts/test-speed-reliability.js" }, "devDependencies": { "@fiahfy/icns": "^0.0.7", diff --git a/preload.js b/preload.js index ca79b96..dba42b5 100644 --- a/preload.js +++ b/preload.js @@ -37,6 +37,47 @@ function getDroppedFilePaths(files) { .filter(Boolean); } +const dueDateFormatter = new Intl.DateTimeFormat('en-US', { + month: 'short', + day: 'numeric', +}); +const formattedDueDateCache = new Map(); + +function formatDueDateLocally(rawDateValue) { + const dateString = String(rawDateValue || '').trim(); + if (!dateString) { + return ''; + } + + if (formattedDueDateCache.has(dateString)) { + return formattedDueDateCache.get(dateString); + } + + const match = dateString.match(/^(\d{4})-(\d{2})-(\d{2})$/); + let formatted = dateString; + if (match) { + const year = Number(match[1]); + const monthIndex = Number(match[2]) - 1; + const day = Number(match[3]); + const dateToDisplay = new Date(year, monthIndex, day); + + if ( + !Number.isNaN(dateToDisplay.getTime()) && + dateToDisplay.getFullYear() === year && + dateToDisplay.getMonth() === monthIndex && + dateToDisplay.getDate() === day + ) { + formatted = dueDateFormatter.format(dateToDisplay); + } + } + + if (formattedDueDateCache.size >= 2000) { + formattedDueDateCache.clear(); + } + formattedDueDateCache.set(dateString, formatted); + return formatted; +} + contextBridge.exposeInMainWorld('board', { authorizeBoardSelection: async (selectionToken) => invokeBoard('authorizeBoardSelection', selectionToken), adoptLegacyBoardRoots: async (boardRoots) => invokeBoard('adoptLegacyBoardRoots', boardRoots), @@ -52,7 +93,7 @@ contextBridge.exposeInMainWorld('board', { return cardFileName.slice(cardFileName.length - 8, cardFileName.length - 3); }, getCardTitle: async (filePath) => invokeBoard('getCardTitle', filePath), - formatDueDate: async (dateString) => invokeBoard('formatDueDate', dateString), + formatDueDate: async (dateString) => formatDueDateLocally(dateString), getCardFileName: (filePath) => getNormalizedBaseName(filePath), getListDirectoryName: (filePath) => getNormalizedBaseName(filePath), listDirectories: async (root) => invokeBoard('listDirectories', root), diff --git a/scripts/test-speed-reliability.js b/scripts/test-speed-reliability.js new file mode 100644 index 0000000..e1fa182 --- /dev/null +++ b/scripts/test-speed-reliability.js @@ -0,0 +1,419 @@ +const assert = require('assert/strict'); +const { spawn } = require('child_process'); +const fs = require('fs').promises; +const os = require('os'); +const path = require('path'); + +const archive = require('../lib/archive'); +const appSettings = require('../lib/appSettings'); +const boardDuplication = require('../lib/boardDuplication'); +const boardLabels = require('../lib/boardLabels'); +const { readBoardSnapshot } = require('../lib/boardSnapshot'); +const cardFrontmatter = require('../lib/cardFrontmatter'); +const { insertCardFileAtTop, reorderListDirectories } = require('../lib/cardOrdering'); +const { resolveCardTimestamps } = require('../lib/cardTimestamps'); +const cliApp = require('../lib/cliApp'); +const cliBoard = require('../lib/cliBoard'); +const { installCliForCurrentUser } = require('../lib/cliInstall'); +const { buildExternalPublishedCalendarFeed } = require('../lib/externalPublishedCalendar'); +const { withFileTransaction } = require('../lib/fileTransaction'); +const { importObsidian } = require('../lib/importers/obsidian'); +const { installPacmanPackageAsync } = require('../lib/linuxPackageInstaller'); + +async function testDotEntriesExcludedFromSnapshotAndListReorder(tempRoot) { + const board = path.join(tempRoot, 'dot-guard-board'); + const listA = path.join(board, '000-Alpha-stock'); + const listB = path.join(board, '001-Beta-stock'); + const gitDir = path.join(board, '.git'); + const obsidianDir = path.join(board, '.obsidian'); + + await fs.mkdir(listA, { recursive: true }); + await fs.mkdir(listB, { recursive: true }); + await fs.mkdir(gitDir, { recursive: true }); + await fs.mkdir(obsidianDir, { recursive: true }); + await fs.writeFile(path.join(gitDir, 'HEAD'), 'ref: refs/heads/main\n', 'utf8'); + await fs.writeFile(path.join(listA, '._000-ghost-abcde.md'), 'appledouble', 'utf8'); + await cardFrontmatter.writeCard(path.join(listA, '000-real-card-ab123.md'), { + frontmatter: { title: 'Real Card' }, + body: 'Body', + }); + + const snapshot = await readBoardSnapshot(board); + assert.equal(snapshot.ok, true); + assert.deepEqual(snapshot.lists.map((l) => l.listName), ['000-Alpha-stock', '001-Beta-stock']); + assert.deepEqual(snapshot.lists[0].cards.map((c) => c.cardName), ['000-real-card-ab123.md']); + + await reorderListDirectories(board, [listB, listA]); + const entries = (await fs.readdir(board)).sort(); + assert(entries.includes('.git'), 'expected .git directory to remain untouched'); + assert(entries.includes('.obsidian'), 'expected .obsidian directory to remain untouched'); + assert(!entries.some((name) => /^\d+-\./.test(name)), `dot directory was renamed: ${entries.join(', ')}`); +} + +async function testSettingsAndFrontmatterBomAndCorruptionProtection(tempRoot) { + const board = path.join(tempRoot, 'bom-board'); + await fs.mkdir(board, { recursive: true }); + + // UTF-8 BOM on board-settings.md should parse cleanly without losing custom labels. + const settingsPath = path.join(board, 'board-settings.md'); + await fs.writeFile( + settingsPath, + '\uFEFF---\nlabels:\n - id: custom-1\n name: Custom Label\n colorLight: "#112233"\n colorDark: "#445566"\n---\n', + 'utf8', + ); + const bomSettings = await boardLabels.readBoardSettings(board, { ensureFile: true }); + assert.equal(bomSettings.labels.length, 1); + assert.equal(bomSettings.labels[0].id, 'custom-1'); + + // Corrupt YAML in board-settings.md must NOT be overwritten on read. + const corruptRaw = '---\nlabels: [\n---\n'; + await fs.writeFile(settingsPath, corruptRaw, 'utf8'); + await boardLabels.readBoardSettings(board, { ensureFile: true }); + assert.equal(await fs.readFile(settingsPath, 'utf8'), corruptRaw, 'corrupt board-settings.md must not be overwritten on read'); + + // Corrupt app-settings.json must NOT be silently overwritten on updateAppSettings. + const userData = path.join(tempRoot, 'corrupt-userdata'); + await fs.mkdir(userData, { recursive: true }); + const appSettingsPath = path.join(userData, 'app-settings.json'); + await fs.writeFile(appSettingsPath, '{ broken json', 'utf8'); + await assert.rejects(() => appSettings.updateAppSettings(userData, { tooltipsEnabled: false })); + assert.equal(await fs.readFile(appSettingsPath, 'utf8'), '{ broken json'); + + // UTF-8 BOM + empty YAML frontmatter on card files. + const cardPath = path.join(board, '000-bom-card-abc12.md'); + await fs.writeFile(cardPath, '\uFEFF---\ntitle: BOM Card\n---\nHello\n', 'utf8'); + const readBom = await cardFrontmatter.readCard(cardPath); + assert.equal(readBom.frontmatter.title, 'BOM Card'); + assert.equal(readBom.body, 'Hello\n'); + + const emptyFmPath = path.join(board, '001-empty-fm-abc13.md'); + await fs.writeFile(emptyFmPath, '---\n---\nBody with --- rule\n', 'utf8'); + const readEmpty = await cardFrontmatter.readCard(emptyFmPath); + assert.equal(readEmpty.body, 'Body with --- rule\n'); +} + +async function testFileTransactionStaleReapRecovery(tempRoot) { + const target = path.join(tempRoot, 'lock-target.md'); + const lock = `${path.resolve(target)}.sb-lock`; + const reap = `${lock}.reap`; + // Simulate a crashed owner PID and a crashed reaper PID. + await fs.writeFile(lock, '99999999', 'utf8'); + await fs.writeFile(reap, '99999998', 'utf8'); + + let ran = false; + await withFileTransaction(target, async () => { + ran = true; + }, { timeoutMs: 2000 }); + assert.equal(ran, true); +} + +async function testLinuxZeroBirthtimeFallback() { + const result = resolveCardTimestamps({}, { + birthtime: new Date(0), + ctime: new Date('2026-04-01T10:00:00.000Z'), + mtime: new Date('2026-04-02T12:00:00.000Z'), + }); + assert.equal(result.createdAt, '2026-04-01T10:00:00.000Z'); + assert.equal(result.updatedAt, '2026-04-02T12:00:00.000Z'); +} + +async function testInsertCardAtTopSkipsUnchangedExistingCards(tempRoot) { + const board = path.join(tempRoot, 'top-insert-board'); + const listA = path.join(board, '000-From-stock'); + const listB = path.join(board, '001-To-stock'); + await fs.mkdir(listA, { recursive: true }); + await fs.mkdir(listB, { recursive: true }); + + const moving = path.join(listA, '000-move-me-aa111.md'); + await cardFrontmatter.writeCard(moving, { frontmatter: { title: 'Move me' }, body: '' }); + await cardFrontmatter.writeCard(path.join(listB, '001-stay-one-bb222.md'), { frontmatter: { title: 'Stay 1' }, body: '' }); + await cardFrontmatter.writeCard(path.join(listB, '002-stay-two-cc333.md'), { frontmatter: { title: 'Stay 2' }, body: '' }); + + const originalRename = fs.rename; + let renameCount = 0; + fs.rename = async (...args) => { + renameCount += 1; + return originalRename(...args); + }; + try { + const movedFile = await insertCardFileAtTop(listB, moving, '000-move-me-aa111.md'); + assert.equal(movedFile, '000-move-me-aa111.md'); + // Only the moved card itself needs a rename; 001 and 002 already match their final names. + assert.equal(renameCount, 1, `expected 1 rename, got ${renameCount}`); + } finally { + fs.rename = originalRename; + } +} + +async function testArchiveRestoreWithDsStoreAndSafeAsValidation(tempRoot) { + const board = path.join(tempRoot, 'archive-edge-board'); + const listA = path.join(board, '000-Todo-stock'); + const listB = path.join(board, '001-Done-stock'); + await fs.mkdir(listA, { recursive: true }); + await fs.mkdir(listB, { recursive: true }); + await cardFrontmatter.writeCard(path.join(listA, '000-only-card-ab123.md'), { + frontmatter: { title: 'Only card' }, + body: '', + }); + + const archivedList = await archive.archiveList(board, listA); + // Drop a macOS .DS_Store inside the archived list folder before restoring its last card. + await fs.writeFile(path.join(archivedList.archivedListPath, '.DS_Store'), 'junk', 'utf8'); + + const restored = await archive.restoreArchivedCard( + board, + path.join(archivedList.archivedListPath, '000-only-card-ab123.md'), + listB, + ); + assert.equal(restored.ok, true); + assert.equal(restored.removedEmptyArchiveList, true); + + // Nested path in --as for restoreArchivedList must be rejected. + const listC = path.join(board, '002-Extra-stock'); + await fs.mkdir(listC, { recursive: true }); + const archivedC = await archive.archiveList(board, listC); + await assert.rejects( + () => archive.restoreArchivedList(board, archivedC.archivedListPath, '001-Done-stock/nested'), + /single valid folder name/, + ); +} + +async function testDuplicationPreservesWhitespaceAndSkipsLocks(tempRoot) { + const board = path.join(tempRoot, 'dupe-source'); + const list = path.join(board, '000-Todo-stock'); + const parent = path.join(tempRoot, 'dupe-parent'); + await fs.mkdir(list, { recursive: true }); + await fs.mkdir(parent, { recursive: true }); + + const bodyWithWhitespace = ' indented line\nsecond line\n\n'; + await cardFrontmatter.writeCard(path.join(list, '000-spaced-aa111.md'), { + frontmatter: { title: 'Spaced' }, + body: bodyWithWhitespace, + }); + await fs.writeFile(path.join(board, '.signboard-list-order.json'), '{}', 'utf8'); + await fs.writeFile(path.join(board, 'board-settings.md.sb-lock'), '123', 'utf8'); + + const result = await boardDuplication.duplicateBoard({ + sourceBoardRoot: board, + destinationParentPath: parent, + boardName: 'Duplicated', + }); + const copiedList = path.join(result.boardRoot, '000-Todo-stock'); + const copiedCards = (await fs.readdir(copiedList)).filter((name) => name.endsWith('.md')); + const copiedCard = await cardFrontmatter.readCard(path.join(copiedList, copiedCards[0])); + assert.equal(copiedCard.body, bodyWithWhitespace); + const rootEntries = await fs.readdir(result.boardRoot); + assert(!rootEntries.includes('.signboard-list-order.json')); + assert(!rootEntries.includes('board-settings.md.sb-lock')); +} + +async function testCliFastIdLookupBooleanFlagsAndTemplatePrefix(tempRoot) { + const board = path.join(tempRoot, 'cli-fast-board'); + const listA = path.join(board, '000-Todo-stock'); + const listB = path.join(board, '001-Doing-stock'); + await fs.mkdir(listA, { recursive: true }); + await fs.mkdir(listB, { recursive: true }); + + for (let i = 0; i < 40; i += 1) { + const id = `id${String(i).padStart(3, '0')}`; + await cardFrontmatter.writeCard(path.join(listA, `${String(i).padStart(3, '0')}-card-${id}.md`), { + frontmatter: { title: `Card ${i}` }, + body: `Body ${i}`, + }); + } + await cardFrontmatter.writeCard(path.join(listB, '000-target-zz999.md'), { + frontmatter: { title: 'Target Card' }, + body: 'Target body', + }); + + // 5-char ID lookup across all lists should NOT read the 40 unrelated cards. + const originalRead = fs.readFile; + let cardReads = 0; + fs.readFile = async (...args) => { + if (String(args[0]).startsWith(board) && String(args[0]).endsWith('.md')) { + cardReads += 1; + } + return originalRead(...args); + }; + try { + const resolved = await cliBoard.resolveCard(board, { cardRef: 'zz999' }); + assert.equal(resolved.title, 'Target Card'); + assert(cardReads <= 3, `expected <=3 .md reads (target card + board settings) for exact cardId lookup, got ${cardReads}`); + } finally { + fs.readFile = originalRead; + } + + // parseArgv boolean flags must NOT swallow the following positional list argument. + const parsed = cliApp.parseArgv(['cards', '--include-archive', 'Doing']); + assert.equal(parsed.options['include-archive'], true); + assert.deepEqual(parsed.positionals, ['cards', 'Doing']); + + // duplicateCard with titlePrefix: '' (used by `cards create --from-card`) must not prepend "Copy of ". + const fromTemplate = await cliBoard.duplicateCard(board, { + cardRef: 'zz999', + titlePrefix: '', + }); + assert.equal(fromTemplate.title, 'Target Card'); +} + +async function testMcpSplitChunkHeaderAndWindowsPathBody(tempRoot) { + const board = path.join(tempRoot, 'mcp-framing-board'); + const list = path.join(board, '000-Todo-stock'); + await fs.mkdir(list, { recursive: true }); + + const mcpScript = path.resolve(__dirname, '../bin/signboard-mcp.js'); + const child = spawn(process.execPath, [mcpScript], { + env: { + ...process.env, + SIGNBOARD_MCP_ALLOWED_ROOTS: tempRoot, + SIGNBOARD_MCP_READ_ONLY: 'false', + }, + stdio: ['pipe', 'pipe', 'pipe'], + }); + + let stdout = Buffer.alloc(0); + child.stdout.on('data', (chunk) => { + stdout = Buffer.concat([stdout, chunk]); + }); + + const payload = JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { + name: 'signboard_create_card', + arguments: { + boardRoot: board, + listName: '000-Todo-stock', + title: 'Windows Path Card', + body: 'See C:\\Users\\new\\notes.md and C:\\Notes\\readme.md', + }, + }, + }); + const header = `Content-Length: ${Buffer.byteLength(payload, 'utf8')}\r\n\r\n`; + // Deliberately split header across two chunks before \r\n\r\n, then immediately end stdin! + child.stdin.write(header.slice(0, 12)); + await new Promise((resolve) => setTimeout(resolve, 30)); + child.stdin.write(header.slice(12) + payload); + child.stdin.end(); + + const exitCode = await new Promise((resolve, reject) => { + child.on('error', reject); + child.on('close', resolve); + }); + assert.equal(exitCode, 0); + + const responseText = stdout.toString('utf8'); + const boundary = responseText.indexOf('\r\n\r\n'); + assert(boundary > 0, `expected header-framed response after split header + EOF, got: ${responseText}`); + const parsed = JSON.parse(responseText.slice(boundary + 4)); + assert.equal(parsed.id, 1); + assert.equal(parsed.result.isError, undefined); + assert.equal( + parsed.result.structuredContent.card.body, + 'See C:\\Users\\new\\notes.md and C:\\Notes\\readme.md', + ); +} + +async function testObsidianKanbanSettingsStripped(tempRoot) { + const board = path.join(tempRoot, 'obsidian-kanban-board'); + const sourceFile = path.join(tempRoot, 'Kanban.md'); + await fs.mkdir(board, { recursive: true }); + await fs.writeFile(sourceFile, [ + '---', + 'kanban-plugin: board', + '---', + '', + '## Backlog', + '', + '- [ ] Ship clean body', + ' Notes line', + '', + '%% kanban:settings', + '```', + '{"kanban-plugin":"board"}', + '```', + '%%', + '', + ].join('\n'), 'utf8'); + + await importObsidian({ boardRoot: board, sourcePaths: [sourceFile] }); + const lists = (await fs.readdir(board)).filter((name) => name.includes('Backlog')); + assert.equal(lists.length, 1); + const cards = (await fs.readdir(path.join(board, lists[0]))).filter((name) => name.endsWith('.md')); + const card = await cardFrontmatter.readCard(path.join(board, lists[0], cards[0])); + assert(!card.body.includes('kanban:settings'), `kanban:settings leaked into card body: ${card.body}`); +} + +async function testExternalCalendarUtf8Folding() { + const emojiTitle = '🚀'.repeat(30); + const ics = await buildExternalPublishedCalendarFeed({ + boardRoots: ['/tmp/fake-board'], + readBoardSettings: async () => ({ workflow: {}, externalPublishedCalendar: { include: true } }), + listLists: async () => ['000-Todo-stock'], + listCards: async () => ['000-emoji-ab123.md'], + readCard: async () => ({ + frontmatter: { title: emojiTitle, due: '2026-09-18' }, + body: '', + }), + getBoardName: () => 'Emoji Board', + }); + for (const line of ics.split('\r\n')) { + assert(Buffer.byteLength(line, 'utf8') <= 75, `ICS line exceeded 75 UTF-8 bytes (${Buffer.byteLength(line, 'utf8')})`); + assert(!/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { + calls.push([command, args]); + return { status: 0, stdout: 'signboard 1.7.9-1', stderr: '' }; + }); + assert.deepEqual(calls, [ + ['pacman', ['-Qp', pkgPath]], + ['pkexec', ['pacman', '-U', '--noconfirm', pkgPath]], + ]); + + const homeDir = path.join(tempRoot, 'linux-shim-home'); + await fs.mkdir(homeDir, { recursive: true }); + const installed = await installCliForCurrentUser({ + executablePath: '/opt/Signboard/Signboard', + appPath: '/opt/Signboard/resources/app.asar', + isPackaged: true, + platform: 'linux', + shellPath: '/bin/bash', + homeDir, + }); + const script = await fs.readFile(installed.scriptPath, 'utf8'); + assert(script.includes('exec env ELECTRON_RUN_AS_NODE=1'), 'Linux CLI shim should exec directly'); + assert(!script.includes('mktemp'), 'Linux CLI shim should not spawn mktemp'); +} + +async function main() { + const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'signboard-1.7.9-')); + try { + await testDotEntriesExcludedFromSnapshotAndListReorder(tempRoot); + await testSettingsAndFrontmatterBomAndCorruptionProtection(tempRoot); + await testFileTransactionStaleReapRecovery(tempRoot); + await testLinuxZeroBirthtimeFallback(); + await testInsertCardAtTopSkipsUnchangedExistingCards(tempRoot); + await testArchiveRestoreWithDsStoreAndSafeAsValidation(tempRoot); + await testDuplicationPreservesWhitespaceAndSkipsLocks(tempRoot); + await testCliFastIdLookupBooleanFlagsAndTemplatePrefix(tempRoot); + await testMcpSplitChunkHeaderAndWindowsPathBody(tempRoot); + await testObsidianKanbanSettingsStripped(tempRoot); + await testExternalCalendarUtf8Folding(); + await testAsyncLinuxPacmanAndLinuxCliShim(tempRoot); + console.log('1.7.9 speed and reliability regressions passed.'); + } finally { + await fs.rm(tempRoot, { recursive: true, force: true }); + } +} + +main().catch((error) => { + console.error(error && error.stack ? error.stack : String(error)); + process.exitCode = 1; +});