Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: expose the shared seams the beeper feature hooks into

tzioup39d3023bd84e
diff --git a/.gitignore b/.gitignore
index 4d97b6dc44..ea0aceab58 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,7 @@
# Dependencies
node_modules/
+/client/node_modules
+/server/node_modules
# Build output
dist/
diff --git a/AGENTS.md b/AGENTS.md
index 8e1a3b4d99..b4d458d528 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -119,7 +119,7 @@ Client- and server-specific conventions live in nested memory files that load wh
`server/lib/navManifest.js` is the single source of truth for navigation: `NAV_COMMANDS` + `resolveNavCommand()`, consumed by both the `⌘K` palette and the voice agent's `ui_navigate` tool. **Adding a `<Route>` without a `NAV_COMMANDS` entry leaves the page unreachable from `⌘K` and un-navigable by voice.** Invoke the `portos-add-page` skill for the entry shape, palette-action wiring, and the fail-fast guards.
-**Optional features gate navigation, not routes.** `server/lib/instanceFeatureRegistry.js` declares the optional per-install features (`post`, `datadog`, `jira`) the user toggles in **Settings > Features**; `server/services/instanceFeatures.js` resolves each one as stored override → auto-detection of the integration it fronts → `defaultEnabled`. A nav entry tagged `feature: '<id>'` (or living in a section listed in navManifest's `SECTION_FEATURE` map) drops out of `⌘K` and the sidebar while that feature is off — **the `<Route>` keeps working, so bookmarks, direct links, and voice `ui_navigate` still resolve**. The gate is applied CLIENT-side (`useInstanceFeatures` + `client/src/lib/navFeatures.js`), not by filtering the manifest response: `⌘K` and the voice widget each fetch `/api/palette/manifest` once per session and it is HTTP-cached, so a server-side filter would both defeat that cache and still show hidden pages until a reload. Tag the sidebar row in `client/src/components/Layout.jsx` with the same id; `navManifest.test.js` scrapes both lists and fails when they drift, when a tag names an unregistered feature, or when a `SECTION_FEATURE` key stops matching a live section.
+**Optional features gate navigation, not routes.** `server/lib/instanceFeatureRegistry.js` declares the optional per-install features (`post`, `datadog`, `jira`) the user toggles in **Settings > Features**; `server/services/instanceFeatures.js` resolves each one as stored override → auto-detection of the integration it fronts → `defaultEnabled`. A nav entry tagged `feature: '<id>'` (or living in a section listed in navManifest's `SECTION_FEATURE` map) drops out of `⌘K` and the sidebar while that feature is off — **the `<Route>` keeps working, so bookmarks, direct links, and voice `ui_navigate` still resolve**. The gate is applied CLIENT-side (`useInstanceFeatures` + `client/src/lib/navFeatures.js`), not by filtering the manifest response: `⌘K` and the voice widget each fetch `/api/palette/manifest` once per session and it is HTTP-cached, so a server-side filter would both defeat that cache and still show hidden pages until a reload. A sidebar row still needs its own `NAV_PRESENTATION` entry in `client/src/components/Layout.jsx` (path → icon); `feature`, `section` and `label` are inherited from `NAV_COMMANDS`, so the path is the one thing declared twice — the icon lives only in `NAV_PRESENTATION` — and a manifest tag alone yields no sidebar row — `NAV_PRESENTATION`'s keys are the set the sidebar iterates. `Layout.test.jsx` pins that every Settings, Digital Twin and Messages sub-tab path has a `NAV_PRESENTATION` entry, and that each entry stays presentation-only (an icon, no `to`/`label`/`section`/`feature`) keyed to a live manifest path. `navManifest.test.js` fails when a tag names an unregistered feature, or when a `SECTION_FEATURE` key stops matching a live section.
**Feature groups bucket related features under one toggle, additively.** `INSTANCE_FEATURE_GROUPS` in `server/lib/instanceFeatureRegistry.js` declares the groups (today: `comms`, holding FaceTime Audio, iMessage, Signal, X, Stacker News and Beeper); a feature joins one by carrying `group: '<groupId>'` on its descriptor, which is the whole edit. `resolveOne` in `server/services/instanceFeatures.js` resolves a grouped feature as **its own stored override → the group flag → the detector → `defaultEnabled`**: an explicit per-feature override always wins, and only a feature left on "inherit" answers to its group (group off hides it, group on hands it straight back to its normal resolution). Setting an override back to inherit deletes the stored key rather than writing a third sentinel, so it reads exactly like a feature nobody ever touched. **A group's own `enabled` defaults to `true` when no group state is stored** — that default is the parity guarantee: an install with no `instanceFeatureGroups` in settings resolves every member exactly as it did before the group existed, so registering a group is never a silent hide and needs no settings migration. Malformed group settings fail toward `false`, matching the per-feature override's own posture. An ungrouped feature is completely unaffected.
diff --git a/client/src/components/agents/tabs/WorldTab.jsx b/client/src/components/agents/tabs/WorldTab.jsx
index 2fb91f5fa8..98b6094578 100644
--- a/client/src/components/agents/tabs/WorldTab.jsx
+++ b/client/src/components/agents/tabs/WorldTab.jsx
@@ -1,6 +1,7 @@
import { useState, useEffect, useCallback } from 'react';
import toast from '../../ui/Toast';
import { FormField } from '../../ui/FormField';
+import ConnectionStatusDot from '../../ui/ConnectionStatusDot';
import * as api from '../../../services/api';
import BrailleSpinner from '../../BrailleSpinner';
import socket from '../../../services/socket';
@@ -390,13 +391,6 @@ export default function WorldTab({ agentId }) {
// leaving stale phantoms.
const displayNearby = presence !== null ? presence : nearby;
- const statusDotColor = {
- connected: 'bg-port-success',
- connecting: 'bg-port-warning animate-pulse',
- reconnecting: 'bg-port-warning animate-pulse',
- disconnected: 'bg-gray-600'
- }[connectionStatus] || 'bg-gray-600';
-
// Dynamic param fields for add-to-queue form
const renderQueueParamFields = () => {
switch (newActionType) {
@@ -447,11 +441,7 @@ export default function WorldTab({ agentId }) {
<div className="p-4">
{/* Connection Banner */}
<div className="flex flex-wrap items-center gap-4 mb-4 p-3 bg-port-card border border-port-border rounded-lg">
- <div className="flex items-center gap-2">
- <span className={`w-2.5 h-2.5 rounded-full ${statusDotColor}`} />
- <span className="text-sm text-gray-400">WebSocket:</span>
- <span className="text-sm text-white font-medium">{connectionStatus}</span>
- </div>
+ <ConnectionStatusDot status={connectionStatus} label="WebSocket:" />
<div className="flex gap-2 ml-auto">
{connectionStatus === 'disconnected' ? (
<button
diff --git a/client/src/components/ui/ConnectionStatusDot.jsx b/client/src/components/ui/ConnectionStatusDot.jsx
new file mode 100644
index 0000000000..2bb23b1c33
--- /dev/null
+++ b/client/src/components/ui/ConnectionStatusDot.jsx
@@ -0,0 +1,33 @@
+/**
+ * Live-connection status dot — a coloured dot, a caption, and the status word.
+ *
+ * Generalised from the Moltworld WebSocket banner (`agents/tabs/WorldTab.jsx`),
+ * which is where this shape was settled and which now renders through it. It is
+ * the ONE liveness surface for a long-lived transport (fork issue #33 decision 4
+ * picked it for Beeper too) — actionable faults belong in the feature's own
+ * settings card, and PortOS has no global socket-degradation banner by design.
+ *
+ * `status` is free-form so each transport can name its own states; anything
+ * unrecognised renders grey rather than blank, so a new state added on the
+ * server can never leave a dot with no colour.
+ */
+
+const STATUS_TONE = {
+ connected: 'bg-port-success',
+ connecting: 'bg-port-warning animate-pulse',
+ reconnecting: 'bg-port-warning animate-pulse',
+ disconnected: 'bg-gray-600',
+ down: 'bg-gray-600',
+ error: 'bg-port-error',
+};
+
+export default function ConnectionStatusDot({ status, label, className = '' }) {
+ const tone = STATUS_TONE[status] || 'bg-gray-600';
+ return (
+ <span className={`flex items-center gap-2 ${className}`}>
+ <span className={`w-2.5 h-2.5 rounded-full shrink-0 ${tone}`} data-testid="connection-status-dot" data-status={status || 'unknown'} />
+ {label && <span className="text-sm text-gray-400">{label}</span>}
+ <span className="text-sm text-white font-medium">{status || 'unknown'}</span>
+ </span>
+ );
+}
diff --git a/client/src/components/ui/README.md b/client/src/components/ui/README.md
index e84d7a944b..711c6216ef 100644
--- a/client/src/components/ui/README.md
+++ b/client/src/components/ui/README.md
@@ -14,6 +14,7 @@ accessibility). Feature-specific components live under their own feature directo
| `CollapsibleSection` | Disclosure section header — chevron, leading icon, collapsed summary, `aria-expanded`/`aria-controls`; `keepMounted` hides the body instead of unmounting it. |
| `CollapsibleText` | Collapsed content preview with a show-more/less toggle — line-clamped `text`, or `children` capped by `maxHeight` when `line-clamp` can't (rendered markdown). |
| `ConfirmButtonPair` | Compact inline confirm/cancel pair for a destructive action in a dense control row. |
+| `ConnectionStatusDot` | Live-transport status dot — coloured by connection state, with a caption and the state word. |
| `CopyableId` | Click-to-copy record-id badge — short prefix shown, full id copied. |
| `diffRuns` | Renders `{ text, changed }` runs from `diffWords` as highlighted nodes (shared by the diff views). |
| `FilePickerButton` | Opens the OS file picker, styled as a button or as a whole drop target. |
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 98fe07fcfd..3000dc0f63 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -190,6 +190,9 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useSongTraining` | Drives a song training run over one scope (whole song or a sliced section) on top of `useColorMatch`: counts in, walks + grades the scope's score, then folds the finished take into the rolling progress history (`songProgress.recordAttempt`) and surfaces the next aggregate via `onProgress`. Supports looping (auto-restart after a run) and keeps a `lastSummary`. Exposes `{ running, countingIn, noteColors, activeIndex, lastSummary, start, stop }`; cancels pending loop relaunches on stop/unmount. | The Song editor's Training panel. |
| `useSyncIntegrity` | Fetches per-kind integrity diff from every eligible online peer; reduces to worst-case `statusById` + `byPeer` breakdown maps. | Federated media sync integrity UI — badges, drawers, peer breakdown. |
| `useSyncSourceSettings` | Shared enabled/interval scheduler settings lifecycle for a machine-local sync source, including status loading, dirty tracking, interval clamping, and save state. | Source settings tabs that use `getSettings` / `updateSettings` with a source-specific status endpoint. |
+| `useBeeperOutbox` | The Beeper composer's send lifecycle (#36): `submit(body, { clearsDraft = true })` creates the durable outbox row then sends it, surfaces the server's first-contact refusal as an inline `confirmation` (never a toast, never `window.confirm`), and refetches when a confirmation invalidation lands. Never retries a send that touched the wire, and latches `submit` so two calls in one render cannot create two rows. `retry(entry)` is the narrow exception — it re-dispatches a row still `approved`, i.e. one refused before the server could claim it (`OUTBOX_BREAKER_OPEN`), where nothing reached Beeper; `dismiss(entry)` gives up on such a row, discarding it server-side. `onSent` fires only for a send whose text IS the draft (`clearsDraft`), so a failed row's retry cannot clear a newly typed message. Returns `{ entries, sending, error, confirmation, submit, confirmAndSend, cancelConfirmation, retry, dismiss, refresh }`. | The Beeper thread composer (#35's Send action, wired on #53). |
+| `useBeeperRealtime` | Subscribes to the server's Beeper realtime relay — invalidation frames (`{ kind, chatID, ids, seq, ts }`, never message content) plus the `connected` / `reconnecting` / `down` transport state. Re-emits `beeper:subscribe` on every socket `connect`. Returns `{ realtime, connectionState, lastInvalidation, seedRealtime }`. | Any Beeper surface that must refetch when the mirror changes (#33). |
+| `useBeeperSettings` | The `settings.beeper` ingestion + connection slice (`enabled`, `intervalMinutes`, `baseUrl`, `attachmentBudgetGb`) as a load/edit/save lifecycle, mirroring `useSyncSourceSettings` but for Beeper's extra fields. Deliberately never reads or writes `token`/`tokenExpiresAt` — the server redacts the token from every `getSettings` response and rejects one on write (#30/#31). Returns `{ loading, form, setForm, saving, dirty, save }`. | The Comms → Beeper settings card (#30). |
| `useSystemResourceReport` | The system-resource disk scan plus its cleanup lifecycle: generation-guarded `runReport` (a late scan can never resurrect rows a newer one removed), one-delete-at-a-time removal keyed on the candidate's server-issued action, and report invalidation after a successful delete. Returns `{ report, setReport, loading, runReport, cleanup }` — `cleanup` is the prop bag `StoragePanel`/`ModelsPanel`/`CleanupControl` expect. | Dev Tools → System Resources → Storage, and Models → Status. Don't re-wire the scan/cleanup pair by hand. |
| `useImageTo3dTargets` | The image-to-3D target registry (`GET /api/image-to-3d/targets`), fetched once per mount. Returns `{ targets, loading, error, reload }` — `error` is first-class, because a failed registry read is NOT an empty registry and both call sites render that distinction. | The `/3d` render flow (target picker + readiness summary) and Models → 3D (install/repair). Don't re-roll the fetch in a third surface. |
| `useTwinEvaluationSuite` | Shared lifecycle for the three Digital Twin evaluation-suite panels (Values-Alignment, Adversarial-Boundary, Multi-Turn): loads suite + recent history (silenced), runs every selected provider/model in parallel, prepends fresh runs, and handles the stale-persona / partial-failure toast fan-out. `countField` names the suite's pass-count key so history stays generic. Returns `{ items, history, loading, running, results, expanded, setExpanded, run, reload }`. | The Digital Twin `TwinEvaluationSuitePanel` presentation shell — don't re-roll the load/run/history dance per suite. |
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 044a6f5622..d5f2da53e1 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -50,6 +50,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `universeStylePreset.js` | Build the client-side style preset that `composeStyledPrompt` layers on top. |
| `universeRunTag.js` | `buildUniverseSectionRenderTag(universe, kindKey, entry)` — the durable `universeRun` job tag the canon-render call sites (UniverseCanonSection, NounsStage, Story Builder characters step) pass to `generateImage` so the server auto-files the render into the universe collection AND appends it to the entry's `imageRefs[]` (no client follow-up PATCH). |
| `autopilotMilestones.js` | Series-Autopilot milestone map. `buildAutopilotMilestones(plan, progress, {terminal})` folds the run's projected plan (the `start` frame) and its live progress snapshot (`progress` frames / the status route) into ordered rows with a `MILESTONE_STATUS` each — a furthest-index cursor, so a gate the run revisits can't un-finish the milestones after it; `summarizeAutopilotMilestones(rows)` rolls them into the header meter (a settled-but-unstepped milestone counts as complete); `describeAutopilotVerification(kind, verification)` renders what a gate actually validated — shared with the panel's `frameLabel`, since the milestone row and the activity log render the same telemetry; `isStoppedTerminal(terminal)` is the one definition of "the run stopped mid-plan"; `autopilotMarkerTerminal(status)` translates a persisted `autopilot.status` into the terminal frame type the fold reads, so a map rebuilt from the marker after a reload (#4140) flags the step a paused run stopped on. Also owns `AUTOPILOT_STEP_LABELS` / `autopilotStepLabel(kind)`, the one set of human labels for conductor step kinds (shared by the map and the panel's live status line). Used by `components/pipeline/AutopilotMilestones.jsx` + `AutopilotPanel.jsx`. |
+| `beeperMessageBody.js` | Beeper message bodies: `decodeHtmlEntities` (the five predefined entities plus `&nbsp;`, mirroring `server/lib/xmlEntities.js`), `looksLikeHtmlBody`, `parseMessageBody(body)` → blocks of marked spans (`p`/`div`/`br`/`blockquote`/`strong`/`b`/`em`/`i`/`a[href]`, `null` when the body carries none of them) and `messagePreviewText(body)` for the one-line rail row. Some networks deliver HTML (Discord, Matrix) and the mirror stores it verbatim, so the thread and the preview parse it into a data model and render React elements — never `dangerouslySetInnerHTML`; a non-http(s) `href` degrades to plain text. |
| `beatColors.js` | `BEAT_KIND_COLORS` + `getBeatKindColor(kind)` — per-kind display colors for reader-map emotional beats (kinds defined server-side in `storyArc.js`). Keeps every beat visualization consistent. |
| `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. |
| `bibleLimits.js` | `BIBLE_LIMITS` re-exported from the pure leaf `server/lib/bibleLimits.js`, plus the client-only `capImageRefs` / `appendImageRefById` for the optimistic imageRefs-append paths. |
diff --git a/docs/API.md b/docs/API.md
index 2930e0163a..43a056ec17 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -711,7 +711,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom
| `/api/memory` | Memory CRUD / search |
| `/api/brain`, `/api/brain/import` | Brain (second brain) and document import |
| `/api/media` | Media library |
-| `/api/imessage`, `/api/contacts`, `/api/signal`, `/api/spotify`, `/api/youtube` | Personal-data ingest |
+| `/api/imessage`, `/api/contacts`, `/api/signal`, `/api/beeper`, `/api/spotify`, `/api/youtube` | Personal-data ingest |
| `/api/notifications` | Notification stream |
| `/api/standardize` | App PM2 standardizer |
| `/api/stacker-news`, `/api/x` | Social integrations |
diff --git a/docs/README.md b/docs/README.md
index 5d1b8719e3..f7ec201bf9 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -49,7 +49,7 @@ Knowledge: [brain-system](./features/brain-system.md) · [untrusted messages and
Create: [writers-room](./features/writers-room.md) · [fableloom](./features/fableloom.md) · [Eidoverse Worlds integration](./features/eidoverse.md) · [OpenWorld historical reference](./features/openworld.md) · [sprite-export-contract](./features/sprite-export-contract.md) · [video-text-encoders](./features/video-text-encoders.md) · [video-speed-profiles](./features/video-speed-profiles.md) · [video-render-batches](./features/video-render-batches.md) · [video-upscale](./features/video-upscale.md)
-Comms & voice: [openclaw-operator-chat](./features/openclaw-operator-chat.md) ([pre-build audit](./research/2026-03-31-openclaw-operator-chat-audit.md)) · [stacker-news](./features/stacker-news.md) · [voice](./features/voice.md)
+Comms & voice: [beeper](./features/beeper.md) · [openclaw-operator-chat](./features/openclaw-operator-chat.md) ([pre-build audit](./research/2026-03-31-openclaw-operator-chat-audit.md)) · [stacker-news](./features/stacker-news.md) · [voice](./features/voice.md)
## Point-in-time records
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 50a116f81e..a72b09b3db 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -90,6 +90,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- Generated images — `data/images/*` bytes + `.metadata.json` sidecars; indexed into the `media_assets` table (#1000) keyed `image:<filename>`. Sidecars remain authoritative; the DB row is a derived, queryable mirror. Adapter: `server/services/mediaAssetIndex/`.
- Generated videos — `data/videos/*`, `data/video-thumbnails/*` bytes, tracked in `data/video-history.json`; indexed into `media_assets` keyed `video:<jobId>`. History file remains authoritative.
- Game asset manifests — immutable `data/games/{id}/manifests/game-assets-v{N}.json` artifacts reference sprite atlas and music-library bytes by stable path + SHA-256; the `games` DB record owns the current pointer and history. Both halves are backed up: PostgreSQL by the required dump, manifests and referenced media by the rsync snapshot.
+- Beeper attachment mirror (#37) — message media stays on disk under `data/beeper/attachments/<sha256 prefix>/<sha256>.<ext>` (content-addressed, so one forwarded photo is one file); `beeper_attachments` in PostgreSQL holds the metadata plus `local_path` / `sha256` / `byte_length` / `keep`. Machine-local and **never federated** (message content is PII — see the message-bodies ADR); a lazy CACHE rather than an archive, so it is excluded from backup by default (overridable) while the rows that describe it ride the Postgres dump. The bytes are re-fetchable from Beeper Desktop for as long as the source network still holds the media, and the surface renders a labelled reference when it does not.
- Media collections — many-to-many links over assets/universes/series/catalog media pointers (`db-primary` link tables) pointing at `asset-file-db-indexed` bytes. **Still `data/media-collections/*` JSON today** — a follow-up slice of #1000.
**Media asset index (`media_assets`, #1000).** One row per generated image/video: `media_key` (`<kind>:<ref>`) PK, `kind`/`ref`/`created_at` mirror columns for queries, the full metadata record in `data` JSONB. It is a **derived index** — the on-disk sidecars + `video-history.json` stay authoritative — reconciled from disk at boot (upsert every asset, prune rows whose file is gone) and kept warm by a generation-`completed` hook. Local-only (rebuilt from disk), so no sync cursor/tombstone. Adapter: `server/services/mediaAssetIndex/{logic,db,index}.js`.
diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.md
index 89768caf5e..735bb099a1 100644
--- a/docs/features/product-surfaces.md
+++ b/docs/features/product-surfaces.md
@@ -177,6 +177,7 @@ Unified communication channels, local voice assistant, community stewardship, an
| **Comms Inbox & Drafts** | `/messages/inbox`, `/messages/drafts`, `/messages/sync` | Centralized message triage, drafting assistant, and cross-channel message synchronization. | [Messages Security](./messages-security.md) |
| **iMessage Sync & Contacts** | `/messages/imessage`, `/messages/contacts` | Local macOS `chat.db` SQLite ingestion, sender identity resolution, spam filtering, and address book contact merging. | [Messages Security](./messages-security.md) |
| **Signal Integration** | `/settings/signal` | Encrypted local sync from Signal Desktop SQLCipher database. | [Messages Security](./messages-security.md) |
+| **Beeper Bridge** | `/messages/beeper`, `/messages/beeper?settings=1` | Local Beeper Desktop bridge mirroring WhatsApp, Discord, Telegram, and other bridged networks into a machine-local store, with a human-gated one-message-at-a-time outbox; the settings drawer connects an account and configures scheduled sync. | [Beeper](./beeper.md) |
| **Telegram & X (Twitter)** | `/settings/telegram`, `/x` | Social channel monitoring, outreach staging, engagement diagnostics, and shadowban checks. | — |
| **Stacker News Stewardship** | `/stacker-news` | Community territory moderation, Bitcoin Lightning tipping, post review, and encrypted credential storage. | [Stacker News](./stacker-news.md) |
| **OpenClaw Operator Chat** | `/openclaw` | Real-time interactive operator agent runtime with streaming sessions and persistent execution. | [OpenClaw Operator Chat](./openclaw-operator-chat.md) |
diff --git a/docs/features/product-surfaces.test.js b/docs/features/product-surfaces.test.js
new file mode 100644
index 0000000000..f395f5ca30
--- /dev/null
+++ b/docs/features/product-surfaces.test.js
@@ -0,0 +1,79 @@
+/**
+ * Route-inventory guard for docs/features/product-surfaces.md, scoped to the
+ * Comms section of the nav manifest (#40/#30: the Comms feature group and the
+ * Beeper bridge).
+ *
+ * docs/README.md calls this file "a complete, user-facing inventory" with one
+ * row per route, and nothing enforced that claim: /messages/beeper and
+ * /messages/beeper?settings=1 shipped with no row at all. This guard catches
+ * the next Comms route that lands the same way.
+ *
+ * Scope is deliberately narrower than "every NAV_COMMANDS path" — this change
+ * only touches the Comms section, and a repo-wide version of this guard would
+ * fail today on pre-existing gaps this change did not introduce:
+ * - /messages/signal — the doc row still names the pre-#30 previousPath
+ * `/settings/signal`, not the live path.
+ * - /messages/config — no row at all.
+ * - /messages/imessage?settings=1 — no row at all (the bare /messages/imessage
+ * row does not cover the settings-drawer deep link).
+ * Those are listed as a follow-up in this change's PR description rather than
+ * fixed here; KNOWN_UNRELATED_GAPS keeps this guard from failing on them so it
+ * can still catch a *new* undocumented Comms route.
+ */
+import { readFileSync } from 'fs';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import { describe, expect, it } from 'vitest';
+import { NAV_COMMANDS } from '../../server/lib/navManifest.js';
+
+const DOC = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'product-surfaces.md'), 'utf8');
+
+const SECTION_HEADING = '## 6. Communications, Voice, Social, & Spatial UI';
+
+// Pre-existing gaps this change did not introduce — see the file comment above.
+const KNOWN_UNRELATED_GAPS = new Set([
+ '/messages/signal',
+ '/messages/config',
+ '/messages/imessage?settings=1',
+]);
+
+/**
+ * Every backticked path in the Route(s) column of the Comms/messaging section's
+ * table rows. Scoped to that one section (between its heading and the next
+ * `## `) rather than the whole document, so a path documented somewhere else
+ * entirely (a Settings or Digital Twin row reusing similar wording) can't be
+ * mistaken for coverage here.
+ */
+function commsSectionDocumentedPaths() {
+ const start = DOC.indexOf(SECTION_HEADING);
+ const afterHeading = DOC.slice(start + SECTION_HEADING.length);
+ const end = afterHeading.indexOf('\n## ');
+ const section = end === -1 ? afterHeading : afterHeading.slice(0, end);
+ const paths = new Set();
+ for (const line of section.split('\n')) {
+ if (!line.startsWith('|')) continue;
+ const routeCell = line.split('|')[2] ?? '';
+ for (const match of routeCell.matchAll(/`([^`]+)`/g)) {
+ paths.add(match[1]);
+ }
+ }
+ return paths;
+}
+
+describe('docs/features/product-surfaces.md — Comms route inventory', () => {
+ it('documents every Comms nav-manifest path not already tracked as a pre-existing gap', () => {
+ const documented = commsSectionDocumentedPaths();
+ const commsPaths = NAV_COMMANDS
+ .filter((command) => command.section === 'Comms')
+ .map((command) => command.path)
+ .filter((path) => !KNOWN_UNRELATED_GAPS.has(path));
+
+ const missing = commsPaths.filter((path) => !documented.has(path));
+ expect(missing).toEqual([]);
+ });
+
+ it('scans a non-empty set of manifest paths and documented routes (detector self-check)', () => {
+ expect(NAV_COMMANDS.filter((command) => command.section === 'Comms').length).toBeGreaterThan(0);
+ expect(commsSectionDocumentedPaths().size).toBeGreaterThan(0);
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 47cc9c55e8..69a76ec6cc 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -386,6 +386,8 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `tailcatVersion.js` | Tailcat CLI version floor for managed install/detect: `MIN_TAILCAT_VERSION` (`0.6.0` — PSK on by default in modern `serve`), `parseTailcatVersion` (handles the CLI's `v0.6.0` banner that `parseHarnessVersion` cannot), `isTailcatVersionAtLeast`, and `tailcatVersionTooOldMessage` for operator-facing upgrade guidance. Consumed by `services/tailcatPeer.js` so Dial-them and They-dial-us refuse ≤0.5.x rather than silently timing out on TCP. |
| `httpsState.js` | Captures whether PortOS booted with HTTPS active. |
| `bareUrl.js` | `parseBareUrl(text)` — returns the normalized URL when a captured string is nothing *but* a URL (bare host gets `https://`), else null. Drives the brain-capture short-circuit that files a pasted URL straight to Links instead of running the classifier. Stricter than the client's `urlNormalize.js` `isUrl` (needs a plausible TLD; http/https/`git@` only) because it picks a storage destination rather than a hint. |
+| `beeperAttachmentPaths.js` | Layout rules for the Beeper attachment byte mirror (#37): `BEEPER_ATTACHMENT_MAX_BYTES` (32 MiB, matching `FEDERATED_MEDIA_ASSET_MAX_BYTES` — a constant, not a setting), `attachmentExtension({ mimeType, fileName })`, `attachmentRelativePath(sha256, ext)` (`<sha256[0..2]>/<sha256>.<ext>`, `null` for anything that is not a 64-hex digest) and `isSafeAttachmentRelativePath(p)`. Content-addressed, so one forwarded photo is one file and every delete path owes a reference check first; the extension is cosmetic because `GET /v1/assets/serve` sends no `Content-Type` and the mirror serves from the stored `mimeType` instead. |
+| `beeperOAuthOrigin.js` | Which origin the Beeper OAuth `redirect_uri` is built from: `parseBrowserOrigin` (a bare `http(s)://host[:port]`, else null), `hostnameOf`, `isLoopbackHostname` (the loopback-spelling predicate reused by the `settings.beeper.baseUrl` gate and the OAuth token-endpoint host pin), and `resolveOAuthOrigin({ clientOrigin, requestOrigin, configuredOrigins })` → `{ origin, source, rejectedClientOrigin }`. The browser sends `window.location.origin` because the request-derived origin is the API's own under the Vite dev proxy (`changeOrigin`, no `x-forwarded-*`), which sends the consent redirect to a host the TLS cert does not cover; the value is untrusted, so it is accepted only for a loopback host, the request's own host, or a configured `PORTOS_UI_URL`/`PORTOS_API_URL` host — port unpinned, since UI and API are different ports of one install. Rejection falls back to the request origin. Pure. |
| `isSafeHref.js` | Pure http(s)-only scheme check (`isSafeHref`) for user-supplied URL fields that get rendered as a clickable `<a href>` — rejects `javascript:`/`data:`/etc. stored-XSS payloads. `client/src/lib/isSafeHref.js` re-exports it, and `client/src/utils/urlNormalize.js` re-exports that as `isHttpUrl`. |
| `networkExposure.js` | Runtime scheme/bind/cert snapshot plus the shared ordered Tailscale, MagicDNS, certificate, and trusted-launch setup guide used by CLI and UI; `localApiBaseUrl()` resolves the plain-HTTP loopback origin (mirror port under HTTPS, API port otherwise) for local scripts and agent-facing curl snippets. |
@@ -505,7 +507,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `signalCrypto.js` | Pure, dependency-free crypto for reading Signal Desktop's encrypted chat DB (#2154): SQLCipher-4 page decryption (`decryptSqlcipherDatabase`, `deriveSqlcipherKeys`, `sqlcipherPageHmac` — PBKDF2-SHA512 HMAC key + AES-256-CBC per page + HMAC-SHA512 verify → plaintext SQLite buffer the built-in `node:sqlite` can open) and Chromium/Electron `safeStorage` unwrap (`decryptSafeStorageValue`, `deriveSafeStorageKey` — macOS AES-128-CBC + PBKDF2-SHA1 over the keychain password). All functions return `{ ok, ... }` reports (never throw) for graceful degradation. Consumed by `services/signalSync.js`. |
| `timezone.js` | Timezone utilities for scheduling. `getLocalParts(utcDate, timezone)` / `getUtcOffsetMs(utcDate, timezone)` are the primitives; `nextLocalTime(afterMs, hours, minutes, timezone)` finds the next UTC instant matching a local HH:MM. `anchorLocalMidnightUtc(dayStr, tz)` resolves the first UTC instant belonging to a local date, including zones whose DST transition skips 00:00; `localDayWindowUtc(timezone, atDate?)` exposes an inclusive ISO-string window, while `localDayRangeUtc(dateStr, timezone)` returns a validated half-open `{ start, end }` `Date` pair ending at the next local-date boundary so 23h/25h transition days remain exact. Also owns `HHMM_RE`/`HHMM_STRICT_RE`, `parseHHMM`, and `isWithinTimeWindow` (mirrored client-side in `client/src/utils/timeWindow.js`). |
| `tribeCadence.js` | Authoritative, pure Tribe care-cadence rules (single source of truth, mirrored to `client/src/lib/tribeCadence.js`): `cadenceStatus(entity)` → `{ state: external/missing/overdue/soon/steady, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS` (45), `SOON_WINDOW_DAYS` (7). Consumed by `personCadenceStatus` / `getCareSummary` in `services/tribe.js` (proactive alert + Care widget) and by the client Tribe page/map. |
-| `tribeMatch.js` | Pure, deterministic matcher mapping a calendar attendee / message counterpart (`{ email, phone, name }`) to a tracked Tribe person for auto-logged touchpoints (#2033, #2151): `buildPersonMatchIndex(people)` → `{ byIdentifier, byPhone, byName }`, `matchPerson(identity, index)` (email/handle authoritative, then E.164 phone, then exact unique name fallback — no fuzzy matching), `matchPeople(identities, index)` → de-duplicated Set of personIds, `normalizeIdentifier(value)`, `normalizePhone(value)` (E.164 normalization for iMessage/Signal handles), `identityFromHandle(handle)` (classify a raw `chat.db` handle into email-or-phone). Consumed by `autoLogTouchpoints` in `services/tribe.js` from the calendar, message, and iMessage sync producers. |
+| `tribeMatch.js` | Pure, deterministic matcher mapping a calendar attendee / message counterpart (`{ email, phone, name }`) to a tracked Tribe person for auto-logged touchpoints (#2033, #2151): `buildPersonMatchIndex(people)` → `{ byIdentifier, byPhone, byName }`, `matchPerson(identity, index)` (email/handle authoritative, then E.164 phone, then exact unique name fallback — no fuzzy matching), `matchPeople(identities, index)` → de-duplicated Set of personIds, `normalizeIdentifier(value)`, `normalizePhone(value)` (E.164 normalization for iMessage/Signal handles), `identityFromHandle(handle)` (classify a raw `chat.db` handle into email-or-phone). Also `resolveLinkedPersonId(tribePersonId, tribePersonDeleted)` — the shared soft-delete predicate a `beeper_participants` row's `tribe_person_id` cache must pass through everywhere it is shaped, so a soft-deleted Tribe person reads as unlinked in both `services/beeperConversations.js` and `services/beeperTribe.js`. Consumed by `autoLogTouchpoints` in `services/tribe.js` from the calendar, message, and iMessage sync producers. |
| `viteAllowedHosts.js` | Detect and remediate a managed app's Vite `server.allowedHosts`. `findViteConfig(repoPath)` locates the config; `parseAllowedHosts(src)` / `hostIsAllowed(parsed, host)` decide whether a Tailscale/IP host would be accepted (mirrors Vite's localhost+IP-always-allowed and leading-dot-suffix rules); `rewriteAllowedHosts(src)` deterministically injects `allowedHosts: true` (or bails `ok:false` on ambiguous shapes so the caller can fall back to an LLM fix); `checkViteHost(repoPath, host)` is the one-shot status used by `GET /api/apps/:id/vite-host-check`. |
| `buildId.js` | Build-ID derived from the built client bundle. |
| `buildIdentity.js` | `getBuildIdentity()` / `getCachedBuildIdentity()` / `formatBuildIdentity()` / `parsePorcelainV2()` — which git commit the RUNNING server process was started from (#4694): `{ commit, shortCommit, branch, dirty }` from ONE `git status --porcelain=v2 --branch` spawn, cached per process (the promise, so concurrent first callers share it). Answers "is this the code I am testing?" on a machine where one PM2 server serves :5555 while many worktrees hold different code — `version` cannot, since package.json's version is identical across every development commit. Served on its own `GET /api/system/build`, NOT on `/health/details`: peers scrape that payload and persist it verbatim, and this stays machine-local. Complements `buildId.js` (bundle hash, not commit), which travels separately on the `build:id` socket frame — the socket path reaches peer relays, so the commit does not use it. Non-throwing, every field independently nullable (no `.git` → `commit: null`, never `''`). |
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index a13290f510..84e9c03175 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -1988,4 +1988,33 @@ describe('serveLocalFile (shared attachment serving pipeline)', () => {
})).rejects.toMatchObject({ status: 404, code: 'NOT_ON_THIS_MACHINE' });
expect(res.sendFile).not.toHaveBeenCalled();
});
+
+ // The declared `contentType` override (Beeper attachment mirror, #37/SEC-1):
+ // a remote sender's declared type is normalized (case folded, parameters
+ // dropped) and the disposition decision is taken on BOTH the declared value
+ // and whatever the type is bounded down to — so downgrading a risky
+ // `text/html` to `application/octet-stream` never costs it the attachment
+ // header it earned.
+ it.each([
+ ['text/HTML'],
+ ['TEXT/html'],
+ [' text/html ;charset=utf-8'],
+ ['Image/SVG+xml'],
+ ['application/xhtml+xml'],
+ ['text/xml'],
+ ])('forces Content-Disposition: attachment for a contentType override of %j', async (contentType) => {
+ writeFileSync(join(dir, 'override.bin'), 'x');
+ const res = mockRes();
+ await serveLocalFile(res, dir, 'override.bin', { contentType });
+ expect(res.headers['Content-Disposition']).toBe('attachment; filename="override.bin"');
+ });
+
+ it('bounds a contentType override outside the mirrored set to application/octet-stream instead of echoing it', async () => {
+ writeFileSync(join(dir, 'mystery.bin'), 'x');
+ const res = mockRes();
+ await serveLocalFile(res, dir, 'mystery.bin', { contentType: 'application/x-not-a-mirrored-type' });
+ expect(res.type).toHaveBeenCalledWith('application/octet-stream');
+ // Not risky, and the bounded type isn't either — no disposition override.
+ expect(res.headers['Content-Disposition']).toBeUndefined();
+ });
});
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index cf2d0b3c3d..2f66b2046a 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -292,7 +292,27 @@ describe('deferred imports stay deferred (#6156)', () => {
// and it pulls in nothing new (its only import, `generationModes.js`, was
// already in every one of them). A leaf with nothing behind it to defer is the
// tolerated shape. The allowance had drifted to ~30 again, so restore the ~1.5k.
-const MAX_STATIC_INSTANTIATIONS = 98500;
+//
+// The Beeper fork carries its own suites, so this budget is above upstream's.
+// Measured on the merge of upstream v2.60.0: 99,024 against upstream's own
+// 97,070 at the same commit, +1,954. Two parts, both the tolerated shape and
+// neither an eager edge into a heavy subtree. 1,030 is 21 test files upstream
+// does not have, whose mean closure (49) is BELOW the tree's (58) — mass, not
+// depth. The other 924 is diffuse: +19 on routes/settings.test.js and +2/+3
+// across ~300 suites, from dependency-free leaves reached through
+// `validation.js`'s flat re-export of `mediaValidation.js`. The largest of
+// them, `beeperOAuthOrigin.js`, has a closure of exactly 1 and imports
+// nothing, and it is read inside a synchronous zod refine — there is no
+// subtree to narrow and no call site to defer to. So restore the ~1.5k
+// allowance over the measured total rather than pretend the delta is free.
+//
+// Re-measured after rebuilding this branch as three layered commits on top
+// of a newer upstream/main (9 commits past the previous base, none of them
+// touching a heavy subtree): 99,168, essentially flat against the 99,024
+// measured above at the older v2.60.0 merge point (+144 — ordinary drift
+// from upstream's own intervening growth, not a new eager edge this branch
+// introduced). Restore the same ~1.5k allowance over that fresh total.
+const MAX_STATIC_INSTANTIATIONS = 100668;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
const serverTestFiles = (dir = SERVER_DIR, out = []) => {
diff --git a/server/lib/mimeTypes.js b/server/lib/mimeTypes.js
index 5acc629342..1bf78c8eb8 100644
--- a/server/lib/mimeTypes.js
+++ b/server/lib/mimeTypes.js
@@ -2,9 +2,24 @@
import { basename, extname } from 'path';
/**
- * MIME types that could execute scripts when served inline — force Content-Disposition: attachment
+ * MIME types that could execute scripts when served inline — force
+ * Content-Disposition: attachment.
+ *
+ * Lowercase by construction: RFC 2045 makes a media type case-insensitive, so
+ * every membership test has to fold case first (`serveLocalFile` does).
+ * `application/xhtml+xml` and `text/xml` are here because both render as a
+ * document with script enabled in every browser that accepts them, which makes
+ * them the same hazard as `text/html` under a different spelling.
*/
-export const RISKY_MIME_TYPES = new Set(['text/html', 'image/svg+xml', 'application/javascript', 'text/javascript', 'application/xml']);
+export const RISKY_MIME_TYPES = new Set([
+ 'text/html',
+ 'application/xhtml+xml',
+ 'image/svg+xml',
+ 'application/javascript',
+ 'text/javascript',
+ 'application/xml',
+ 'text/xml',
+]);
/**
* Full extension→MIME map covering documents, images, audio, video, code, and
diff --git a/server/lib/paths.js b/server/lib/paths.js
index e6b74acf5f..90d4e0bb34 100644
--- a/server/lib/paths.js
+++ b/server/lib/paths.js
@@ -131,6 +131,14 @@ export const PATHS = {
// only the metadata syncs inside the brain `songs` record; peers lacking a
// file render "not on this machine". Covered by backup via data/brain/.
brainSongbook: join(INSTALL_ROOT, 'data/brain/songbook'),
+ // Beeper attachment BYTES (#37) — content-addressed as
+ // `<sha256[0..2]>/<sha256>.<ext>`, mirrored lazily on first human view and
+ // bounded by `settings.beeper.attachmentBudgetGb`. Machine-local and never
+ // federated, like every other Beeper mirror row; excluded from backups by
+ // default (overridable) because it is re-fetchable from Beeper for as long
+ // as the source network still holds the media, and the mirror renders the
+ // reference when it does not.
+ beeperAttachments: join(INSTALL_ROOT, 'data/beeper/attachments'),
slashdo: join(CODE_ROOT, 'lib/slashdo'),
// Fully-resolved slashdo command bodies written for CoS agents to READ on
// demand instead of receiving them pasted into the prompt (issue #3110).
diff --git a/server/lib/uploads.js b/server/lib/uploads.js
index 8e5ac2069a..35ab36bcd8 100644
--- a/server/lib/uploads.js
+++ b/server/lib/uploads.js
@@ -2,6 +2,7 @@
import { readFile, stat, unlink } from 'fs/promises';
import { randomUUID } from 'crypto';
import { join, resolve as resolvePath } from 'path';
+import { MIRRORED_MIME_TYPES } from './beeperAttachmentPaths.js';
import { ServerError } from './errorHandler.js';
import { copyFileGuarded, ensureDir, pathExists, writeFileGuarded } from './fileCore.js';
import { detectImageFormat, getFileExtension, getMimeType, RISKY_MIME_TYPES, sanitizeFilename } from './mimeTypes.js';
@@ -167,6 +168,16 @@ export async function saveBase64Upload(dir, { filename, data }, { allowedExtensi
return { id, filename: fname, filePath, buffer, size: buffer.length, mime: getMimeType(getFileExtension(fname)) };
}
+/**
+ * A declared media type reduced to a bare, comparable `type/subtype`:
+ * parameters dropped, whitespace trimmed on BOTH sides of the split (a value
+ * like ` text/html ;charset=utf-8` leaves a trailing space otherwise), case
+ * folded. Returns `''` for anything that is not a non-empty string.
+ */
+function normalizeDeclaredMimeType(value) {
+ return typeof value === 'string' ? value.split(';')[0].trim().toLowerCase() : '';
+}
+
/**
* Serve a machine-local file from `dir` by user-supplied filename with the
* shared safety pipeline: sanitize → containment guard (400
@@ -176,12 +187,35 @@ export async function saveBase64Upload(dir, { filename, data }, { allowedExtensi
*
* Mirrors the exact serving behavior of `routes/attachments.js`.
*
+ * `contentType` overrides the extension-derived type for a store whose
+ * filenames carry no meaning. The Beeper attachment mirror (#37) is the
+ * caller: it is content-addressed (`<sha256>.<ext>`), and the source it
+ * downloads from (`GET /v1/assets/serve`) sends no `Content-Type` header at
+ * all, so the type Beeper declared in the message payload is the only real
+ * answer and the extension is decoration.
+ *
+ * That declared type is written by a REMOTE SENDER and this route is on the
+ * authenticated dashboard origin, so the override is normalized and bounded
+ * rather than trusted:
+ *
+ * - Normalized first — parameters dropped, trimmed, lowercased. A media type
+ * is case-insensitive (RFC 2045) while `RISKY_MIME_TYPES` is a lowercase
+ * set, so `text/HTML` walked straight past the guard until this step
+ * existed and executed inline on the dashboard's own origin.
+ * - Bounded second — only a type the mirror itself can produce
+ * (`MIRRORED_MIME_TYPES`) is echoed; anything else is served as
+ * `application/octet-stream` instead of whatever was declared.
+ *
+ * The disposition decision is then taken on the declared type as well as the
+ * served one, so downgrading a `text/html` to octet-stream never costs it the
+ * attachment header it earned.
+ *
* @param {import('express').Response} res
* @param {string} dir - The containing directory.
* @param {string} filename - Raw user-supplied filename.
- * @param {{ missingError?: { message: string, code: string } }} [opts]
+ * @param {{ missingError?: { message: string, code: string }, contentType?: string }} [opts]
*/
-export async function serveLocalFile(res, dir, filename, { missingError } = {}) {
+export async function serveLocalFile(res, dir, filename, { missingError, contentType } = {}) {
const safeFilename = sanitizeFilename(filename);
const filePath = resolvePath(dir, safeFilename);
@@ -194,9 +228,12 @@ export async function serveLocalFile(res, dir, filename, { missingError } = {})
throw new ServerError(message, { status: 404, code });
}
- const mimeType = getMimeType(getFileExtension(safeFilename));
+ const declared = normalizeDeclaredMimeType(contentType);
+ const mimeType = declared
+ ? (MIRRORED_MIME_TYPES.has(declared) ? declared : 'application/octet-stream')
+ : getMimeType(getFileExtension(safeFilename));
res.set('X-Content-Type-Options', 'nosniff');
- if (RISKY_MIME_TYPES.has(mimeType)) {
+ if (RISKY_MIME_TYPES.has(mimeType) || RISKY_MIME_TYPES.has(declared)) {
res.set('Content-Disposition', `attachment; filename="${safeFilename}"`);
}
res.type(mimeType).sendFile(filePath);
diff --git a/server/services/backup.js b/server/services/backup.js
index dd1b137546..e9bb264a24 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -141,7 +141,16 @@ export const DEFAULT_EXCLUDES = [
// machine's conditioning bytes, staged for one federated render and swept on
// a TTL measured in hours. Nothing here is this install's data to keep, and a
// restored inbox entry is either already expired or already rendered.
- { path: '/federated-media-inbox/', reason: 'Conditioning images an allowlisted peer uploaded for one federated render — TTL-swept, and another machine\'s data rather than this install\'s', overridable: false }
+ { path: '/federated-media-inbox/', reason: 'Conditioning images an allowlisted peer uploaded for one federated render — TTL-swept, and another machine\'s data rather than this install\'s', overridable: false },
+ // Anchored, like every entry here. The Beeper attachment mirror (#37) is a
+ // lazy CACHE of bytes Beeper Desktop can re-supply, re-fetched on first view
+ // and rendered as a labelled reference when it cannot — so a snapshot that
+ // skips it loses no record, only a re-download. It is also by far the largest
+ // thing the Comms feature puts on disk, which is exactly the kind of
+ // directory that turns a nightly snapshot into an hour.
+ // Overridable, because an archive of a conversation is more useful with its
+ // photos in it, and someone keeping one may well want to pay for them.
+ { path: '/beeper/attachments/', reason: 'Beeper attachment byte mirror — a lazy cache re-fetchable from Beeper Desktop; the message bodies and attachment metadata live in Postgres and ARE backed up', overridable: true }
// NOTE: legacy file→Postgres migration artifacts (`.imported` / `.bak-NNN`)
// are intentionally NOT excluded here. They are deleted on disk by the
// boot-time prune (pruneImportedLegacyFiles.js) the same boot the migration
diff --git a/server/services/dataManager.categories.test.js b/server/services/dataManager.categories.test.js
index 4f7448e4c3..e5a2696ab8 100644
--- a/server/services/dataManager.categories.test.js
+++ b/server/services/dataManager.categories.test.js
@@ -158,6 +158,17 @@ describe('dataManager purge scope (#3327)', () => {
expect(CATEGORIES.screenshots.purgeScope).toBe('category');
});
+ // Audit cluster 04, decision 2: `data/beeper/` holds one subdirectory
+ // (`attachments/`), so neither purge form was ever reachable — a category
+ // wipe needs `purgeScope: 'category'` and a per-item purge refuses a
+ // directory entry outright. The visible purge control was dead either way;
+ // this category now reports size only and reclamation happens through the
+ // attachment budget sweep and the per-conversation purge instead.
+ it('reports the Beeper attachment mirror as size-only — no purge control that was never reachable', () => {
+ expect(CATEGORIES.beeper.deletable).toBe(false);
+ expect(CATEGORIES.beeper.purgeScope).toBeUndefined();
+ });
+
// These only exercise the refusal paths, which all return before purgeCategory
// touches the filesystem — no test here may reach `rm` against the real data/.
it('refuses a category-wide purge for item-scoped and protected categories', async () => {
@@ -165,6 +176,8 @@ describe('dataManager purge scope (#3327)', () => {
await expect(purgeCategory('videos')).rejects.toThrow(/only supports per-item purge/);
await expect(purgeCategory('loras')).rejects.toThrow(/is not purgeable/);
await expect(purgeCategory('loras', { subPath: 'anything' })).rejects.toThrow(/is not purgeable/);
+ await expect(purgeCategory('beeper')).rejects.toThrow(/is not purgeable/);
+ await expect(purgeCategory('beeper', { subPath: 'attachments' })).rejects.toThrow(/is not purgeable/);
});
it('fails closed when a deletable category has no recognized purgeScope', async () => {
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index 3a3d9a6f94..e72c63d24a 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -52,6 +52,22 @@ export const CATEGORIES = {
'avatar': { label: 'Avatar', description: 'Uploaded avatar images', archivable: true, deletable: false },
'backup': { label: 'Backups', description: 'Data backup archives', archivable: false, deletable: true, purgeScope: 'category' },
'brain': { label: 'Brain', description: 'Brain items and sync log', archivable: true, deletable: false },
+ // The Beeper attachment byte mirror (#37) — the only thing the Beeper feature
+ // writes to `data/`; every other Beeper record is Postgres. Not archivable:
+ // the tarball would land inside `data/` and grow the number the user came here
+ // to shrink, and the bytes are re-fetchable from Beeper anyway. NOT deletable
+ // from here either (audit cluster 04, decision 2): the directory holds a
+ // single subdirectory, `attachments/`, which the per-item purge form refuses
+ // outright (item-scoped purges remove a single FILE and never recurse — see
+ // `purgeCategory` below) and the category-wide form was never reachable
+ // without `purgeScope: 'category'`. The visible purge control was dead on
+ // arrival either way. Reclamation is two paths that both reference-check
+ // before touching a byte: the attachment budget sweep (least-recently-viewed
+ // eviction, bounded by `settings.beeper.attachmentBudgetGb`) and the
+ // per-conversation purge (`DELETE /api/beeper/conversations/:id`, content-
+ // addressed so a photo forwarded into three chats survives one being
+ // purged). This category reports size only.
+ 'beeper': { label: 'Beeper Attachments', description: 'Mirrored Beeper attachment bytes — reclaimed by the attachment budget sweep and per-conversation purge, not from here', archivable: false, deletable: false },
// Legacy location — current installs download to ~/Downloads (PATHS.browserDownloads),
// but installs that predate that move still carry the dir, and backup still excludes it.
'browser-downloads': { label: 'Browser Downloads', description: 'Files the agent browser downloaded — re-downloadable, safe to purge', archivable: false, deletable: true, purgeScope: 'category' },
diff --git a/server/services/sharing/peerMediaLibrarySync.js b/server/services/sharing/peerMediaLibrarySync.js
index 282efd260e..59fc9afc06 100644
--- a/server/services/sharing/peerMediaLibrarySync.js
+++ b/server/services/sharing/peerMediaLibrarySync.js
@@ -58,7 +58,13 @@ import { findPeerById, isNonEmptyStr, FORCE_REVALIDATE_EVERY } from './peerSyncS
// honored. `image` carries a gen-params sidecar (rides via hashImageForManifest);
// the rest are flat bytes. image-refs are EXCLUDED (ephemeral FLUX multi-ref
// scratch); video-thumbnails are EXCLUDED (regenerated locally on video pull).
-function mediaLibraryDirs() {
+//
+// Exported because this list — not MEDIA_LIBRARY_KIND_DIRNAMES below, which
+// only translates kinds into backup exclude patterns — is what actually
+// decides which `data/` directories cross to a peer. The #28 federation guard
+// asserts against it directly, so a machine-local media kind cannot be added
+// to the walk unnoticed.
+export function mediaLibraryDirs() {
return [
{ kind: 'image', dir: PATHS.images },
{ kind: 'video', dir: PATHS.videos },
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 9683ffb26b..c094e0d903 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -3959,12 +3959,12 @@ describe('peerSync', () => {
// record of a button someone pressed on another install.
// This guard pins that decision: federating any of them later is a conscious
// act — wire the kind AND update this assertion + the ADR together.
- const localOnlyKinds = ['tribe', 'tribePerson', 'tribeTouchpoint', 'tribeMemoryLink', 'universeRun', 'humanActivityEvent', 'userActionEvent'];
+ const localOnlyKinds = ['tribe', 'tribePerson', 'tribeTouchpoint', 'tribeMemoryLink', 'tribeIdentity', 'universeRun', 'humanActivityEvent', 'userActionEvent'];
for (const kind of localOnlyKinds) {
expect(PEER_SUBSCRIBABLE_KINDS).not.toContain(kind);
expect(RECORD_KIND_SCHEMA_CATEGORIES[kind]).toBeUndefined();
}
- const localOnlyCategories = ['tribe', 'tribePeople', 'tribeTouchpoints', 'tribeMemoryLinks', 'universeRuns', 'humanActivityEvents', 'userActionEvents'];
+ const localOnlyCategories = ['tribe', 'tribePeople', 'tribeTouchpoints', 'tribeMemoryLinks', 'tribeIdentities', 'universeRuns', 'humanActivityEvents', 'userActionEvents'];
for (const category of localOnlyCategories) {
expect(PORTOS_SCHEMA_VERSIONS[category]).toBeUndefined();
expect(NON_RECORD_SCHEMA_CATEGORIES.has(category)).toBe(false);
diff --git a/server/services/tribe.js b/server/services/tribe.js
index 0ead628b74..c5de5be044 100644
--- a/server/services/tribe.js
+++ b/server/services/tribe.js
@@ -464,7 +464,14 @@ export async function createCalendarTouchpoint(personId, { accountId, eventId, s
// (the partial unique index idx_tribe_touchpoints_dedupe). Returns the created
// touchpoint, or `null` when this person+dedupeKey was already logged (re-sync).
// Only advances last_contact_on when a row is actually inserted.
-async function autoCreateTouchpoint(personId, data) {
+//
+// Exported (in addition to being used internally by autoLogTouchpoints below)
+// so a caller that has ALREADY resolved a personId through a different axis —
+// server/services/beeperTribe.js resolves via tribe_identities / the
+// beeper_participants cache, not the email/phone/name matcher in
+// tribeMatch.js — can reuse this exact dedupe-keyed insert + last_contact_on
+// advance instead of re-implementing it (#34).
+export async function autoCreateTouchpoint(personId, data) {
const happenedAt = data.happenedAt || new Date().toISOString();
return withTransaction(async (client) => {
const result = await client.query(